commit 73320561b000d57023db1331e4619c3b82ee6096 Author: Aditya Siregar Date: Wed Jul 30 22:38:44 2025 +0700 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bde8d36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,46 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ +*.cxx/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +.vscode/templates diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..417ad2f --- /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: "ef1af02aead6fe2414f3aafa5a61087b610e1332" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: android + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: ios + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: linux + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: macos + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: web + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + - platform: windows + create_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + base_revision: ef1af02aead6fe2414f3aafa5a61087b610e1332 + + # 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/README.md b/README.md new file mode 100644 index 0000000..16efea5 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# EnakloPOS + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..6f56801 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..7ecc902 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,72 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +android { + namespace "com.example.enaklo_pos" + compileSdkVersion 35 + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "com.example.enaklo_pos" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. + minSdkVersion 21 + targetSdkVersion 35 + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + multiDexEnabled true + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.debug + } + } +} + +flutter { + source '../..' +} + +dependencies { + //multiDex + implementation 'com.android.support:multidex:1.0.3' + implementation 'androidx.multidex:multidex:2.0.1' +} 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..0b2dde7 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/enaklo_pos/MainActivity.kt b/android/app/src/main/kotlin/com/example/enaklo_pos/MainActivity.kt new file mode 100644 index 0000000..771aa26 --- /dev/null +++ b/android/app/src/main/kotlin/com/example/enaklo_pos/MainActivity.kt @@ -0,0 +1,6 @@ +package com.example.enaklo_pos + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..fb5924d Binary files /dev/null and b/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..ac2322b Binary files /dev/null and b/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ 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-xhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..77d043d Binary files /dev/null and b/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..36346e3 Binary files /dev/null and b/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..42d2059 Binary files /dev/null and b/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ 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-anydpi-v26/launcher_icon.xml b/android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml new file mode 100644 index 0000000..5f349f7 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml @@ -0,0 +1,5 @@ + + + + + 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-hdpi/launcher_icon.png b/android/app/src/main/res/mipmap-hdpi/launcher_icon.png new file mode 100644 index 0000000..255f6e7 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/launcher_icon.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-mdpi/launcher_icon.png b/android/app/src/main/res/mipmap-mdpi/launcher_icon.png new file mode 100644 index 0000000..bf1325e Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/launcher_icon.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-xhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.png new file mode 100644 index 0000000..b76448e Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/launcher_icon.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-xxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.png new file mode 100644 index 0000000..6e71dd1 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/launcher_icon.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/mipmap-xxxhdpi/launcher_icon.png b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.png new file mode 100644 index 0000000..bbe6bc1 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/launcher_icon.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/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..c5d5899 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,4 @@ + + + #FFFFFF + \ No newline at end of file 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 b/android/build.gradle new file mode 100644 index 0000000..cc71bc7 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,30 @@ +buildscript { + ext.kotlin_version = '2.0.0' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +tasks.register("clean", Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..598d13f --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx4G +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..4d6272d --- /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-8.4-bin.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..a00b697 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,29 @@ +pluginManagement { + def flutterSdkPath = { + def properties = new Properties() + file("local.properties").withInputStream { properties.load(it) } + def flutterSdkPath = properties.getProperty("flutter.sdk") + assert flutterSdkPath != null, "flutter.sdk not set in local.properties" + return flutterSdkPath + } + settings.ext.flutterSdkPath = flutterSdkPath() + + includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } + + plugins { + id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + } +} + +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.3.0" apply false +} + +include ":app" diff --git a/assets/icons/all_categories.svg b/assets/icons/all_categories.svg new file mode 100644 index 0000000..a7860d5 --- /dev/null +++ b/assets/icons/all_categories.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/calendar.svg b/assets/icons/calendar.svg new file mode 100644 index 0000000..4e4ffd3 --- /dev/null +++ b/assets/icons/calendar.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/cash.svg b/assets/icons/cash.svg new file mode 100644 index 0000000..b18590c --- /dev/null +++ b/assets/icons/cash.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/assets/icons/dashboard.svg b/assets/icons/dashboard.svg new file mode 100644 index 0000000..ce8f080 --- /dev/null +++ b/assets/icons/dashboard.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/debit.svg b/assets/icons/debit.svg new file mode 100644 index 0000000..21aee2d --- /dev/null +++ b/assets/icons/debit.svg @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/assets/icons/delete.svg b/assets/icons/delete.svg new file mode 100644 index 0000000..efcf6fe --- /dev/null +++ b/assets/icons/delete.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/discount.svg b/assets/icons/discount.svg new file mode 100644 index 0000000..909706a --- /dev/null +++ b/assets/icons/discount.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/diskon.svg b/assets/icons/diskon.svg new file mode 100644 index 0000000..12e2d5e --- /dev/null +++ b/assets/icons/diskon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/done.svg b/assets/icons/done.svg new file mode 100644 index 0000000..8495552 --- /dev/null +++ b/assets/icons/done.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/drink.svg b/assets/icons/drink.svg new file mode 100644 index 0000000..93b7b7c --- /dev/null +++ b/assets/icons/drink.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/icons/edit.svg b/assets/icons/edit.svg new file mode 100644 index 0000000..d86f40c --- /dev/null +++ b/assets/icons/edit.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/food.svg b/assets/icons/food.svg new file mode 100644 index 0000000..ea4d7c7 --- /dev/null +++ b/assets/icons/food.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/history.svg b/assets/icons/history.svg new file mode 100644 index 0000000..e2b93bc --- /dev/null +++ b/assets/icons/history.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/icons/home-resto.svg b/assets/icons/home-resto.svg new file mode 100644 index 0000000..d4e50cd --- /dev/null +++ b/assets/icons/home-resto.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/home.svg b/assets/icons/home.svg new file mode 100644 index 0000000..ce62918 --- /dev/null +++ b/assets/icons/home.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/icons/image.svg b/assets/icons/image.svg new file mode 100644 index 0000000..a1e9610 --- /dev/null +++ b/assets/icons/image.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/kelola-diskon.svg b/assets/icons/kelola-diskon.svg new file mode 100644 index 0000000..6f637a9 --- /dev/null +++ b/assets/icons/kelola-diskon.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/kelola-pajak.svg b/assets/icons/kelola-pajak.svg new file mode 100644 index 0000000..4939a89 --- /dev/null +++ b/assets/icons/kelola-pajak.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/kelola-printer.svg b/assets/icons/kelola-printer.svg new file mode 100644 index 0000000..8ce98a0 --- /dev/null +++ b/assets/icons/kelola-printer.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/kelola-produk.svg b/assets/icons/kelola-produk.svg new file mode 100644 index 0000000..1cc7a84 --- /dev/null +++ b/assets/icons/kelola-produk.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/layanan.svg b/assets/icons/layanan.svg new file mode 100644 index 0000000..54c9dd3 --- /dev/null +++ b/assets/icons/layanan.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/logout.svg b/assets/icons/logout.svg new file mode 100644 index 0000000..2b8f6d2 --- /dev/null +++ b/assets/icons/logout.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/no-product.svg b/assets/icons/no-product.svg new file mode 100644 index 0000000..77c5134 --- /dev/null +++ b/assets/icons/no-product.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/ongkir.svg b/assets/icons/ongkir.svg new file mode 100644 index 0000000..4cb734b --- /dev/null +++ b/assets/icons/ongkir.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/orders.svg b/assets/icons/orders.svg new file mode 100644 index 0000000..7167e85 --- /dev/null +++ b/assets/icons/orders.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/pajak.svg b/assets/icons/pajak.svg new file mode 100644 index 0000000..2b6cc66 --- /dev/null +++ b/assets/icons/pajak.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/payments.svg b/assets/icons/payments.svg new file mode 100644 index 0000000..13715dc --- /dev/null +++ b/assets/icons/payments.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/print.svg b/assets/icons/print.svg new file mode 100644 index 0000000..b54f535 --- /dev/null +++ b/assets/icons/print.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/assets/icons/qr_code.svg b/assets/icons/qr_code.svg new file mode 100644 index 0000000..173fb1d --- /dev/null +++ b/assets/icons/qr_code.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/assets/icons/report.svg b/assets/icons/report.svg new file mode 100644 index 0000000..541c01d --- /dev/null +++ b/assets/icons/report.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/setting.svg b/assets/icons/setting.svg new file mode 100644 index 0000000..79da7cd --- /dev/null +++ b/assets/icons/setting.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/shopping-basket.svg b/assets/icons/shopping-basket.svg new file mode 100644 index 0000000..c461734 --- /dev/null +++ b/assets/icons/shopping-basket.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/icons/snack.svg b/assets/icons/snack.svg new file mode 100644 index 0000000..5bbb7c8 --- /dev/null +++ b/assets/icons/snack.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/icons/success.svg b/assets/icons/success.svg new file mode 100644 index 0000000..3887db6 --- /dev/null +++ b/assets/icons/success.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/images/drink1.png b/assets/images/drink1.png new file mode 100644 index 0000000..1ae33a9 Binary files /dev/null and b/assets/images/drink1.png differ diff --git a/assets/images/drink2.png b/assets/images/drink2.png new file mode 100644 index 0000000..ea9c91f Binary files /dev/null and b/assets/images/drink2.png differ diff --git a/assets/images/drink3.png b/assets/images/drink3.png new file mode 100644 index 0000000..9cc6633 Binary files /dev/null and b/assets/images/drink3.png differ diff --git a/assets/images/drink4.png b/assets/images/drink4.png new file mode 100644 index 0000000..2be71ff Binary files /dev/null and b/assets/images/drink4.png differ diff --git a/assets/images/drink5.png b/assets/images/drink5.png new file mode 100644 index 0000000..b7e8034 Binary files /dev/null and b/assets/images/drink5.png differ diff --git a/assets/images/drink6.png b/assets/images/drink6.png new file mode 100644 index 0000000..f486f4c Binary files /dev/null and b/assets/images/drink6.png differ diff --git a/assets/images/drink7.png b/assets/images/drink7.png new file mode 100644 index 0000000..4d27fe9 Binary files /dev/null and b/assets/images/drink7.png differ diff --git a/assets/images/logo.png b/assets/images/logo.png new file mode 100644 index 0000000..56400eb Binary files /dev/null and b/assets/images/logo.png differ diff --git a/assets/images/manage_printer.png b/assets/images/manage_printer.png new file mode 100644 index 0000000..5832bbd Binary files /dev/null and b/assets/images/manage_printer.png differ diff --git a/assets/images/manage_product.png b/assets/images/manage_product.png new file mode 100644 index 0000000..4c3bdf9 Binary files /dev/null and b/assets/images/manage_product.png differ diff --git a/assets/images/manage_qr.png b/assets/images/manage_qr.png new file mode 100644 index 0000000..8ef2769 Binary files /dev/null and b/assets/images/manage_qr.png differ diff --git a/assets/images/menu1.png b/assets/images/menu1.png new file mode 100644 index 0000000..dffbcaa Binary files /dev/null and b/assets/images/menu1.png differ diff --git a/assets/images/menu10.png b/assets/images/menu10.png new file mode 100644 index 0000000..682f37b Binary files /dev/null and b/assets/images/menu10.png differ diff --git a/assets/images/menu11.png b/assets/images/menu11.png new file mode 100644 index 0000000..a7faeaa Binary files /dev/null and b/assets/images/menu11.png differ diff --git a/assets/images/menu12.png b/assets/images/menu12.png new file mode 100644 index 0000000..f8e9ebb Binary files /dev/null and b/assets/images/menu12.png differ diff --git a/assets/images/menu13.png b/assets/images/menu13.png new file mode 100644 index 0000000..37aacad Binary files /dev/null and b/assets/images/menu13.png differ diff --git a/assets/images/menu14.png b/assets/images/menu14.png new file mode 100644 index 0000000..0328845 Binary files /dev/null and b/assets/images/menu14.png differ diff --git a/assets/images/menu2.png b/assets/images/menu2.png new file mode 100644 index 0000000..93cf9eb Binary files /dev/null and b/assets/images/menu2.png differ diff --git a/assets/images/menu3.png b/assets/images/menu3.png new file mode 100644 index 0000000..ee7b67e Binary files /dev/null and b/assets/images/menu3.png differ diff --git a/assets/images/menu4.png b/assets/images/menu4.png new file mode 100644 index 0000000..9b80a6c Binary files /dev/null and b/assets/images/menu4.png differ diff --git a/assets/images/menu5.png b/assets/images/menu5.png new file mode 100644 index 0000000..0b13d6d Binary files /dev/null and b/assets/images/menu5.png differ diff --git a/assets/images/menu6.png b/assets/images/menu6.png new file mode 100644 index 0000000..6d61b6d Binary files /dev/null and b/assets/images/menu6.png differ diff --git a/assets/images/menu7.png b/assets/images/menu7.png new file mode 100644 index 0000000..8d19814 Binary files /dev/null and b/assets/images/menu7.png differ diff --git a/assets/images/menu8.png b/assets/images/menu8.png new file mode 100644 index 0000000..49414bb Binary files /dev/null and b/assets/images/menu8.png differ diff --git a/assets/images/product1.jpg b/assets/images/product1.jpg new file mode 100644 index 0000000..03285ba Binary files /dev/null and b/assets/images/product1.jpg differ diff --git a/assets/images/product2.jpg b/assets/images/product2.jpg new file mode 100644 index 0000000..19b0751 Binary files /dev/null and b/assets/images/product2.jpg differ diff --git a/assets/images/product3.jpg b/assets/images/product3.jpg new file mode 100644 index 0000000..8622737 Binary files /dev/null and b/assets/images/product3.jpg differ diff --git a/assets/images/product4.jpg b/assets/images/product4.jpg new file mode 100644 index 0000000..edc8aa6 Binary files /dev/null and b/assets/images/product4.jpg differ diff --git a/assets/logo/logo.png b/assets/logo/logo.png new file mode 100644 index 0000000..733fa8c Binary files /dev/null and b/assets/logo/logo.png differ diff --git a/assets/logo/logo2.png b/assets/logo/logo2.png new file mode 100644 index 0000000..733fa8c Binary files /dev/null and b/assets/logo/logo2.png differ diff --git a/assets/logo/logo3.png b/assets/logo/logo3.png new file mode 100644 index 0000000..95d3402 Binary files /dev/null and b/assets/logo/logo3.png differ diff --git a/assets/logo/logo4.png b/assets/logo/logo4.png new file mode 100644 index 0000000..37a397a Binary files /dev/null and b/assets/logo/logo4.png differ diff --git a/assets/logo/logo5.png b/assets/logo/logo5.png new file mode 100644 index 0000000..9b330af Binary files /dev/null and b/assets/logo/logo5.png differ diff --git a/assets/logo/logo6.png b/assets/logo/logo6.png new file mode 100644 index 0000000..c1bdfcb Binary files /dev/null and b/assets/logo/logo6.png differ diff --git a/assets/logo/logo_app_icon.png b/assets/logo/logo_app_icon.png new file mode 100644 index 0000000..683a633 --- /dev/null +++ b/assets/logo/logo_app_icon.png @@ -0,0 +1,6 @@ +# This is a placeholder file +# Please replace this with your actual logo file that has: +# 1. Transparent background (not dark blue) +# 2. White or light colored elements that will be visible on mobile devices +# 3. Minimum size of 1024x1024 pixels for best quality +# 4. PNG format with transparency support \ No newline at end of file diff --git a/assets/logo/mylogo.png b/assets/logo/mylogo.png new file mode 100644 index 0000000..733fa8c Binary files /dev/null and b/assets/logo/mylogo.png differ diff --git a/config.json b/config.json new file mode 100644 index 0000000..8b3d807 --- /dev/null +++ b/config.json @@ -0,0 +1,12 @@ +{ + "modules": [], + "module_directory_name": "module", + "experimental_mode": false, + "learning_mode": false, + "unfreezed": true, + "use_cubit": false, + "ignore_core_generator_for_directories": [ + "lib/model", + "lib/models" + ] +} \ No newline at end of file diff --git a/generate_app_icon.dart b/generate_app_icon.dart new file mode 100644 index 0000000..da080e4 --- /dev/null +++ b/generate_app_icon.dart @@ -0,0 +1,34 @@ +import 'dart:io'; +import 'package:flutter/material.dart'; +import 'lib/core/utils/app_icon_generator.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + + print('Generating EnakloPOS app icon...'); + + try { + final iconData = await AppIconGenerator.generateAppIcon(); + + // Ensure the assets/logo directory exists + final logoDir = Directory('assets/logo'); + if (!await logoDir.exists()) { + await logoDir.create(recursive: true); + } + + // Write the generated icon to file + final iconFile = File('assets/logo/logo_app_icon.png'); + await iconFile.writeAsBytes(iconData); + + print('✅ App icon generated successfully at: assets/logo/logo_app_icon.png'); + print('📱 The icon features:'); + print(' - White background for visibility'); + print(' - Blue circular background'); + print(' - Gift box with "e" inside'); + print(' - "ENAKLO" and "POS" text'); + print(' - 1024x1024 resolution for high quality'); + + } catch (e) { + print('❌ Error generating app icon: $e'); + } +} \ No newline at end of file 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..7c56964 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 12.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100644 index 0000000..d97f17e --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,44 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '12.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100644 index 0000000..d3ec607 --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,61 @@ +PODS: + - Flutter (1.0.0) + - image_picker_ios (0.0.1): + - Flutter + - open_file_plus (1.0.0): + - Flutter + - path_provider_foundation (0.0.1): + - Flutter + - FlutterMacOS + - permission_handler_apple (9.3.0): + - Flutter + - print_bluetooth_thermal (0.0.1): + - Flutter + - shared_preferences_foundation (0.0.1): + - Flutter + - FlutterMacOS + - sqflite_darwin (0.0.4): + - Flutter + - FlutterMacOS + +DEPENDENCIES: + - Flutter (from `Flutter`) + - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) + - open_file_plus (from `.symlinks/plugins/open_file_plus/ios`) + - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + - permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`) + - print_bluetooth_thermal (from `.symlinks/plugins/print_bluetooth_thermal/ios`) + - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) + - sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + image_picker_ios: + :path: ".symlinks/plugins/image_picker_ios/ios" + open_file_plus: + :path: ".symlinks/plugins/open_file_plus/ios" + path_provider_foundation: + :path: ".symlinks/plugins/path_provider_foundation/darwin" + permission_handler_apple: + :path: ".symlinks/plugins/permission_handler_apple/ios" + print_bluetooth_thermal: + :path: ".symlinks/plugins/print_bluetooth_thermal/ios" + shared_preferences_foundation: + :path: ".symlinks/plugins/shared_preferences_foundation/darwin" + sqflite_darwin: + :path: ".symlinks/plugins/sqflite_darwin/darwin" + +SPEC CHECKSUMS: + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + image_picker_ios: c560581cceedb403a6ff17f2f816d7fea1421fc1 + open_file_plus: 05737718530c14cf02868e3b7754d7fe4df76d8b + path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46 + permission_handler_apple: 9878588469a2b0d0fc1e048d9f43605f92e6cec2 + print_bluetooth_thermal: 54a9ba9436479dd633d18f393669ee793ee498fa + shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 + sqflite_darwin: a553b1fd6fe66f53bbb0fe5b4f5bab93f08d7a13 + +PODFILE CHECKSUM: 819463e6a0290f5a72f145ba7cde16e8b6ef0796 + +COCOAPODS: 1.15.2 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..089aff6 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,740 @@ +// !$*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 */; }; + 7B840F0BF377D6EFB91BAEC2 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DED3A8A51EBB71FBE0568AA /* Pods_RunnerTests.framework */; }; + 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 */; }; + D5782DC0F9DAD73DE55BB88A /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BE72BB1EADB981A3797BD481 /* Pods_Runner.framework */; }; +/* 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 */ + 148680F04D80817E831C8F16 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + 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 = ""; }; + 1DED3A8A51EBB71FBE0568AA /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 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 = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 806C406591DBFE22175B1FD6 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.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 = ""; }; + A57BF56CA8A87C4EA1794DDE /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; + A66B845A3ED73041F90381DB /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + BE72BB1EADB981A3797BD481 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + D86587AB1C457765BBEF3921 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + EE2D729E114EAE99E5BCC8C7 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D5782DC0F9DAD73DE55BB88A /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9BEA62011630D303A0F29D0E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 7B840F0BF377D6EFB91BAEC2 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 41D5103E3F1E533FA2395370 /* Frameworks */ = { + isa = PBXGroup; + children = ( + BE72BB1EADB981A3797BD481 /* Pods_Runner.framework */, + 1DED3A8A51EBB71FBE0568AA /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + BBBFAE7598EB988D6905ED40 /* Pods */, + 41D5103E3F1E533FA2395370 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; + BBBFAE7598EB988D6905ED40 /* Pods */ = { + isa = PBXGroup; + children = ( + EE2D729E114EAE99E5BCC8C7 /* Pods-Runner.debug.xcconfig */, + 806C406591DBFE22175B1FD6 /* Pods-Runner.release.xcconfig */, + A66B845A3ED73041F90381DB /* Pods-Runner.profile.xcconfig */, + D86587AB1C457765BBEF3921 /* Pods-RunnerTests.debug.xcconfig */, + A57BF56CA8A87C4EA1794DDE /* Pods-RunnerTests.release.xcconfig */, + 148680F04D80817E831C8F16 /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 6DEA3EF66B2C771562D1130E /* [CP] Check Pods Manifest.lock */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 9BEA62011630D303A0F29D0E /* Frameworks */, + ); + 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 = ( + 890E2A68E9CBB091D9B9A7C1 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + D4F49B13C53DD1F13CE61FD3 /* [CP] Embed Pods Frameworks */, + 7FF968889934AE1A2E5FDDB6 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 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; + 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"; + }; + 6DEA3EF66B2C771562D1130E /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 7FF968889934AE1A2E5FDDB6 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Copy Pods Resources"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + 890E2A68E9CBB091D9B9A7C1 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 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"; + }; + D4F49B13C53DD1F13CE61FD3 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.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.flutterPosrestoApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = D86587AB1C457765BBEF3921 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterPosrestoApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A57BF56CA8A87C4EA1794DDE /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterPosrestoApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 148680F04D80817E831C8F16 /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterPosrestoApp.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.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.flutterPosrestoApp; + 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.flutterPosrestoApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/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..8e3ca5d --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..21a3cc1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + 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..b636303 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..fe17dc9 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..62e6e0a 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..4fd1115 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..bb37dbb 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..66b7659 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..697aa91 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..a3d490b 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..4fd1115 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..881007f 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..8fd7e63 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-50x50@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png new file mode 100644 index 0000000..f7d3438 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png new file mode 100644 index 0000000..dea8518 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png new file mode 100644 index 0000000..5d60416 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png new file mode 100644 index 0000000..4c51fa9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.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..8fd7e63 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..aec4644 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-72x72@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png new file mode 100644 index 0000000..2105988 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png new file mode 100644 index 0000000..baf1a6a Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.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..3c68433 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..adc2635 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..f2bfd8b 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..0a7712c --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + EnakloPOS + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + enaklo_pos + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + 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/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/core/assets/assets.gen.dart b/lib/core/assets/assets.gen.dart new file mode 100644 index 0000000..85b1d40 --- /dev/null +++ b/lib/core/assets/assets.gen.dart @@ -0,0 +1,489 @@ +/// GENERATED CODE - DO NOT MODIFY BY HAND +/// ***************************************************** +/// FlutterGen +/// ***************************************************** + +// coverage:ignore-file +// ignore_for_file: type=lint +// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_svg/flutter_svg.dart' as _svg; +import 'package:vector_graphics/vector_graphics.dart' as _vg; + +class $AssetsIconsGen { + const $AssetsIconsGen(); + + /// File path: assets/icons/all_categories.svg + SvgGenImage get allCategories => + const SvgGenImage('assets/icons/all_categories.svg'); + + /// File path: assets/icons/calendar.svg + SvgGenImage get calendar => const SvgGenImage('assets/icons/calendar.svg'); + + /// File path: assets/icons/cash.svg + SvgGenImage get cash => const SvgGenImage('assets/icons/cash.svg'); + + /// File path: assets/icons/dashboard.svg + SvgGenImage get dashboard => const SvgGenImage('assets/icons/dashboard.svg'); + + /// File path: assets/icons/debit.svg + SvgGenImage get debit => const SvgGenImage('assets/icons/debit.svg'); + + /// File path: assets/icons/delete.svg + SvgGenImage get delete => const SvgGenImage('assets/icons/delete.svg'); + + /// File path: assets/icons/discount.svg + SvgGenImage get discount => const SvgGenImage('assets/icons/discount.svg'); + + /// File path: assets/icons/diskon.svg + SvgGenImage get diskon => const SvgGenImage('assets/icons/diskon.svg'); + + /// File path: assets/icons/done.svg + SvgGenImage get done => const SvgGenImage('assets/icons/done.svg'); + + /// File path: assets/icons/drink.svg + SvgGenImage get drink => const SvgGenImage('assets/icons/drink.svg'); + + /// File path: assets/icons/edit.svg + SvgGenImage get edit => const SvgGenImage('assets/icons/edit.svg'); + + /// File path: assets/icons/food.svg + SvgGenImage get food => const SvgGenImage('assets/icons/food.svg'); + + /// File path: assets/icons/history.svg + SvgGenImage get history => const SvgGenImage('assets/icons/history.svg'); + + /// File path: assets/icons/home-resto.svg + SvgGenImage get homeResto => const SvgGenImage('assets/icons/home-resto.svg'); + + /// File path: assets/icons/home.svg + SvgGenImage get home => const SvgGenImage('assets/icons/home.svg'); + + /// File path: assets/icons/image.svg + SvgGenImage get image => const SvgGenImage('assets/icons/image.svg'); + + /// File path: assets/icons/kelola-diskon.svg + SvgGenImage get kelolaDiskon => + const SvgGenImage('assets/icons/kelola-diskon.svg'); + + /// File path: assets/icons/kelola-pajak.svg + SvgGenImage get kelolaPajak => + const SvgGenImage('assets/icons/kelola-pajak.svg'); + + /// File path: assets/icons/kelola-printer.svg + SvgGenImage get kelolaPrinter => + const SvgGenImage('assets/icons/kelola-printer.svg'); + + /// File path: assets/icons/kelola-produk.svg + SvgGenImage get kelolaProduk => + const SvgGenImage('assets/icons/kelola-produk.svg'); + + /// File path: assets/icons/layanan.svg + SvgGenImage get layanan => const SvgGenImage('assets/icons/layanan.svg'); + + /// File path: assets/icons/logout.svg + SvgGenImage get logout => const SvgGenImage('assets/icons/logout.svg'); + + /// File path: assets/icons/no-product.svg + SvgGenImage get noProduct => const SvgGenImage('assets/icons/no-product.svg'); + + /// File path: assets/icons/ongkir.svg + SvgGenImage get ongkir => const SvgGenImage('assets/icons/ongkir.svg'); + + /// File path: assets/icons/orders.svg + SvgGenImage get orders => const SvgGenImage('assets/icons/orders.svg'); + + /// File path: assets/icons/pajak.svg + SvgGenImage get pajak => const SvgGenImage('assets/icons/pajak.svg'); + + /// File path: assets/icons/payments.svg + SvgGenImage get payments => const SvgGenImage('assets/icons/payments.svg'); + + /// File path: assets/icons/print.svg + SvgGenImage get print => const SvgGenImage('assets/icons/print.svg'); + + /// File path: assets/icons/qr_code.svg + SvgGenImage get qrCode => const SvgGenImage('assets/icons/qr_code.svg'); + + /// File path: assets/icons/report.svg + SvgGenImage get report => const SvgGenImage('assets/icons/report.svg'); + + /// File path: assets/icons/setting.svg + SvgGenImage get setting => const SvgGenImage('assets/icons/setting.svg'); + + /// File path: assets/icons/shopping-basket.svg + SvgGenImage get shoppingBasket => + const SvgGenImage('assets/icons/shopping-basket.svg'); + + /// File path: assets/icons/snack.svg + SvgGenImage get snack => const SvgGenImage('assets/icons/snack.svg'); + + /// File path: assets/icons/success.svg + SvgGenImage get success => const SvgGenImage('assets/icons/success.svg'); + + /// List of all assets + List get values => [ + allCategories, + calendar, + cash, + dashboard, + debit, + delete, + discount, + diskon, + done, + drink, + edit, + food, + history, + homeResto, + home, + image, + kelolaDiskon, + kelolaPajak, + kelolaPrinter, + kelolaProduk, + layanan, + logout, + noProduct, + ongkir, + orders, + pajak, + payments, + print, + qrCode, + report, + setting, + shoppingBasket, + snack, + success + ]; +} + +class $AssetsImagesGen { + const $AssetsImagesGen(); + + /// File path: assets/images/drink1.png + AssetGenImage get drink1 => const AssetGenImage('assets/images/drink1.png'); + + /// File path: assets/images/drink2.png + AssetGenImage get drink2 => const AssetGenImage('assets/images/drink2.png'); + + /// File path: assets/images/drink3.png + AssetGenImage get drink3 => const AssetGenImage('assets/images/drink3.png'); + + /// File path: assets/images/drink4.png + AssetGenImage get drink4 => const AssetGenImage('assets/images/drink4.png'); + + /// File path: assets/images/drink5.png + AssetGenImage get drink5 => const AssetGenImage('assets/images/drink5.png'); + + /// File path: assets/images/drink6.png + AssetGenImage get drink6 => const AssetGenImage('assets/images/drink6.png'); + + /// File path: assets/images/drink7.png + AssetGenImage get drink7 => const AssetGenImage('assets/images/drink7.png'); + + /// File path: assets/images/logo.png + AssetGenImage get logo => const AssetGenImage('assets/images/logo.png'); + + /// File path: assets/images/manage_printer.png + AssetGenImage get managePrinter => + const AssetGenImage('assets/images/manage_printer.png'); + + /// File path: assets/images/manage_product.png + AssetGenImage get manageProduct => + const AssetGenImage('assets/images/manage_product.png'); + + /// File path: assets/images/manage_qr.png + AssetGenImage get manageQr => + const AssetGenImage('assets/images/manage_qr.png'); + + /// File path: assets/images/menu1.png + AssetGenImage get menu1 => const AssetGenImage('assets/images/menu1.png'); + + /// File path: assets/images/menu10.png + AssetGenImage get menu10 => const AssetGenImage('assets/images/menu10.png'); + + /// File path: assets/images/menu11.png + AssetGenImage get menu11 => const AssetGenImage('assets/images/menu11.png'); + + /// File path: assets/images/menu12.png + AssetGenImage get menu12 => const AssetGenImage('assets/images/menu12.png'); + + /// File path: assets/images/menu13.png + AssetGenImage get menu13 => const AssetGenImage('assets/images/menu13.png'); + + /// File path: assets/images/menu14.png + AssetGenImage get menu14 => const AssetGenImage('assets/images/menu14.png'); + + /// File path: assets/images/menu2.png + AssetGenImage get menu2 => const AssetGenImage('assets/images/menu2.png'); + + /// File path: assets/images/menu3.png + AssetGenImage get menu3 => const AssetGenImage('assets/images/menu3.png'); + + /// File path: assets/images/menu4.png + AssetGenImage get menu4 => const AssetGenImage('assets/images/menu4.png'); + + /// File path: assets/images/menu5.png + AssetGenImage get menu5 => const AssetGenImage('assets/images/menu5.png'); + + /// File path: assets/images/menu6.png + AssetGenImage get menu6 => const AssetGenImage('assets/images/menu6.png'); + + /// File path: assets/images/menu7.png + AssetGenImage get menu7 => const AssetGenImage('assets/images/menu7.png'); + + /// File path: assets/images/menu8.png + AssetGenImage get menu8 => const AssetGenImage('assets/images/menu8.png'); + + /// File path: assets/images/product1.jpg + AssetGenImage get product1 => + const AssetGenImage('assets/images/product1.jpg'); + + /// File path: assets/images/product2.jpg + AssetGenImage get product2 => + const AssetGenImage('assets/images/product2.jpg'); + + /// File path: assets/images/product3.jpg + AssetGenImage get product3 => + const AssetGenImage('assets/images/product3.jpg'); + + /// File path: assets/images/product4.jpg + AssetGenImage get product4 => + const AssetGenImage('assets/images/product4.jpg'); + + /// List of all assets + List get values => [ + drink1, + drink2, + drink3, + drink4, + drink5, + drink6, + drink7, + logo, + managePrinter, + manageProduct, + manageQr, + menu1, + menu10, + menu11, + menu12, + menu13, + menu14, + menu2, + menu3, + menu4, + menu5, + menu6, + menu7, + menu8, + product1, + product2, + product3, + product4 + ]; +} + +class $AssetsLogoGen { + const $AssetsLogoGen(); + + /// File path: assets/logo/logo.png + AssetGenImage get logo => const AssetGenImage('assets/logo/logo.png'); + + /// File path: assets/logo/logo2.png + AssetGenImage get logo2 => const AssetGenImage('assets/logo/logo2.png'); + + /// File path: assets/logo/logo3.png + AssetGenImage get logo3 => const AssetGenImage('assets/logo/logo3.png'); + + /// File path: assets/logo/logo4.png + AssetGenImage get logo4 => const AssetGenImage('assets/logo/logo4.png'); + + /// File path: assets/logo/logo5.png + AssetGenImage get logo5 => const AssetGenImage('assets/logo/logo5.png'); + + /// File path: assets/logo/logo6.png + AssetGenImage get logo6 => const AssetGenImage('assets/logo/logo6.png'); + + /// File path: assets/logo/logo_app_icon.png + AssetGenImage get logoAppIcon => + const AssetGenImage('assets/logo/logo_app_icon.png'); + + /// File path: assets/logo/mylogo.png + AssetGenImage get mylogo => const AssetGenImage('assets/logo/mylogo.png'); + + /// List of all assets + List get values => + [logo, logo2, logo3, logo4, logo5, logo6, logoAppIcon, mylogo]; +} + +class Assets { + Assets._(); + + static const $AssetsIconsGen icons = $AssetsIconsGen(); + static const $AssetsImagesGen images = $AssetsImagesGen(); + static const $AssetsLogoGen logo = $AssetsLogoGen(); +} + +class AssetGenImage { + const AssetGenImage( + this._assetName, { + this.size, + this.flavors = const {}, + }); + + final String _assetName; + + final Size? size; + final Set flavors; + + Image image({ + Key? key, + AssetBundle? bundle, + ImageFrameBuilder? frameBuilder, + ImageErrorWidgetBuilder? errorBuilder, + String? semanticLabel, + bool excludeFromSemantics = false, + double? scale, + double? width, + double? height, + Color? color, + Animation? opacity, + BlendMode? colorBlendMode, + BoxFit? fit, + AlignmentGeometry alignment = Alignment.center, + ImageRepeat repeat = ImageRepeat.noRepeat, + Rect? centerSlice, + bool matchTextDirection = false, + bool gaplessPlayback = true, + bool isAntiAlias = false, + String? package, + FilterQuality filterQuality = FilterQuality.low, + int? cacheWidth, + int? cacheHeight, + }) { + return Image.asset( + _assetName, + key: key, + bundle: bundle, + frameBuilder: frameBuilder, + errorBuilder: errorBuilder, + semanticLabel: semanticLabel, + excludeFromSemantics: excludeFromSemantics, + scale: scale, + width: width, + height: height, + color: color, + opacity: opacity, + colorBlendMode: colorBlendMode, + fit: fit, + alignment: alignment, + repeat: repeat, + centerSlice: centerSlice, + matchTextDirection: matchTextDirection, + gaplessPlayback: gaplessPlayback, + isAntiAlias: isAntiAlias, + package: package, + filterQuality: filterQuality, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + ); + } + + ImageProvider provider({ + AssetBundle? bundle, + String? package, + }) { + return AssetImage( + _assetName, + bundle: bundle, + package: package, + ); + } + + String get path => _assetName; + + String get keyName => _assetName; +} + +class SvgGenImage { + const SvgGenImage( + this._assetName, { + this.size, + this.flavors = const {}, + }) : _isVecFormat = false; + + const SvgGenImage.vec( + this._assetName, { + this.size, + this.flavors = const {}, + }) : _isVecFormat = true; + + final String _assetName; + final Size? size; + final Set flavors; + final bool _isVecFormat; + + _svg.SvgPicture svg({ + Key? key, + bool matchTextDirection = false, + AssetBundle? bundle, + String? package, + double? width, + double? height, + BoxFit fit = BoxFit.contain, + AlignmentGeometry alignment = Alignment.center, + bool allowDrawingOutsideViewBox = false, + WidgetBuilder? placeholderBuilder, + String? semanticsLabel, + bool excludeFromSemantics = false, + _svg.SvgTheme? theme, + ColorFilter? colorFilter, + Clip clipBehavior = Clip.hardEdge, + @deprecated Color? color, + @deprecated BlendMode colorBlendMode = BlendMode.srcIn, + @deprecated bool cacheColorFilter = false, + }) { + final _svg.BytesLoader loader; + if (_isVecFormat) { + loader = _vg.AssetBytesLoader( + _assetName, + assetBundle: bundle, + packageName: package, + ); + } else { + loader = _svg.SvgAssetLoader( + _assetName, + assetBundle: bundle, + packageName: package, + theme: theme, + ); + } + return _svg.SvgPicture( + loader, + key: key, + matchTextDirection: matchTextDirection, + width: width, + height: height, + fit: fit, + alignment: alignment, + allowDrawingOutsideViewBox: allowDrawingOutsideViewBox, + placeholderBuilder: placeholderBuilder, + semanticsLabel: semanticsLabel, + excludeFromSemantics: excludeFromSemantics, + colorFilter: colorFilter ?? + (color == null ? null : ColorFilter.mode(color, colorBlendMode)), + clipBehavior: clipBehavior, + cacheColorFilter: cacheColorFilter, + ); + } + + String get path => _assetName; + + String get keyName => _assetName; +} diff --git a/lib/core/components/buttons.dart b/lib/core/components/buttons.dart new file mode 100644 index 0000000..2301468 --- /dev/null +++ b/lib/core/components/buttons.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; + +import '../constants/colors.dart'; + +enum ButtonStyle { filled, outlined } + +class Button extends StatelessWidget { + const Button.filled({ + super.key, + required this.onPressed, + required this.label, + this.style = ButtonStyle.filled, + this.color = AppColors.primary, + this.textColor = Colors.white, + this.width, + this.height = 50.0, + this.borderRadius = 16.0, + this.icon, + this.disabled = false, + this.fontSize = 16.0, + }); + + const Button.outlined({ + super.key, + required this.onPressed, + required this.label, + this.style = ButtonStyle.outlined, + this.color = Colors.transparent, + this.textColor = AppColors.primary, + this.width, + this.height = 50.0, + this.borderRadius = 16.0, + this.icon, + this.disabled = false, + this.fontSize = 16.0, + }); + + final Function() onPressed; + final String label; + final ButtonStyle style; + final Color color; + final Color textColor; + final double? width; + final double height; + final double borderRadius; + final Widget? icon; + final bool disabled; + final double fontSize; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: height, + width: width, + child: style == ButtonStyle.filled + ? ElevatedButton( + onPressed: disabled ? null : onPressed, + style: ElevatedButton.styleFrom( + backgroundColor: color, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(borderRadius), + ), + padding: const EdgeInsets.symmetric(horizontal: 16.0), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + icon ?? const SizedBox.shrink(), + if (icon != null) const SizedBox(width: 10.0), + Flexible( + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + label, + style: TextStyle( + color: disabled ? Colors.grey : textColor, + fontSize: fontSize, + fontWeight: FontWeight.w600, + ), + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + ) + : OutlinedButton( + onPressed: disabled ? null : onPressed, + style: OutlinedButton.styleFrom( + backgroundColor: color, + side: const BorderSide(color: Colors.grey), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(borderRadius), + ), + padding: const EdgeInsets.symmetric(horizontal: 16.0), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + icon ?? const SizedBox.shrink(), + if (icon != null) const SizedBox(width: 10.0), + Flexible( + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + label, + style: TextStyle( + color: disabled ? Colors.grey : textColor, + fontSize: fontSize, + fontWeight: FontWeight.w600, + ), + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/core/components/components.dart b/lib/core/components/components.dart new file mode 100644 index 0000000..6118a3f --- /dev/null +++ b/lib/core/components/components.dart @@ -0,0 +1,9 @@ +export 'buttons.dart'; +export 'custom_dropdown.dart'; +export 'custom_screen_manager.dart'; +export 'custom_text_field.dart'; +export 'image_picker_widget.dart'; +export 'menu_button.dart'; +export 'search_input.dart'; +export 'spaces.dart'; +export 'tab_custom.dart'; diff --git a/lib/core/components/custom_date_picker.dart b/lib/core/components/custom_date_picker.dart new file mode 100644 index 0000000..823d052 --- /dev/null +++ b/lib/core/components/custom_date_picker.dart @@ -0,0 +1,96 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/assets/assets.gen.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; + +class CustomDatePicker extends StatefulWidget { + final void Function(DateTime selectedDate)? onDateSelected; + final DateTime initialDate; + final Widget? prefix; + + const CustomDatePicker({ + super.key, + required this.initialDate, + this.onDateSelected, + this.prefix, + }); + + @override + State createState() => _CustomDatePickerState(); +} + +class _CustomDatePickerState extends State { + late DateTime selectedDate; + + @override + void initState() { + selectedDate = widget.initialDate; + super.initState(); + } + + Future _selectDate(BuildContext context) async { + final DateTime? picked = await showDatePicker( + context: context, + initialDate: selectedDate, + firstDate: DateTime(2000), + lastDate: DateTime(2101), + ); + if (picked != null && picked != selectedDate) { + setState(() { + selectedDate = picked; + }); + if (widget.onDateSelected != null) { + widget.onDateSelected!(picked); + } + } + } + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 500, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Flexible( + child: GestureDetector( + onTap: () => _selectDate(context), + child: AbsorbPointer( + child: TextFormField( + style: const TextStyle( + color: AppColors.black, + fontWeight: FontWeight.bold, + ), + readOnly: true, + controller: TextEditingController( + text: selectedDate.toFormattedDate2(), + ), + decoration: InputDecoration( + suffixIcon: Padding( + padding: const EdgeInsets.all(16.0), + child: Assets.icons.calendar.svg(), + ), + prefix: widget.prefix, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(6.0), + borderSide: const BorderSide(color: AppColors.stroke), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(6.0), + borderSide: const BorderSide(color: AppColors.stroke), + ), + ), + ), + ), + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/core/components/custom_dropdown.dart b/lib/core/components/custom_dropdown.dart new file mode 100644 index 0000000..5436e42 --- /dev/null +++ b/lib/core/components/custom_dropdown.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; + +import 'spaces.dart'; + +class CustomDropdown extends StatelessWidget { + final String? value; + final List items; + final String label; + final Function(String? value)? onChanged; + + const CustomDropdown({ + super.key, + required this.value, + required this.items, + required this.label, + this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SpaceHeight(12.0), + DropdownButtonFormField( + value: value, + onChanged: onChanged, + items: items.map((String item) { + return DropdownMenuItem( + value: item, + child: Text(item), + ); + }).toList(), + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16.0), + borderSide: const BorderSide(color: Colors.grey), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16.0), + borderSide: const BorderSide(color: Colors.grey), + ), + ), + ), + ], + ); + } +} diff --git a/lib/core/components/custom_screen_manager.dart b/lib/core/components/custom_screen_manager.dart new file mode 100644 index 0000000..3cb6077 --- /dev/null +++ b/lib/core/components/custom_screen_manager.dart @@ -0,0 +1,22 @@ +import 'package:flutter/material.dart'; + +class CustomScreenManager extends StatelessWidget { + final Widget mobile; + final Widget desktop; + + const CustomScreenManager({ + super.key, + required this.mobile, + required this.desktop, + }); + + @override + Widget build(BuildContext context) { + final screenWidth = MediaQuery.of(context).size.width; + if (screenWidth < 1200) { + return mobile; + } else { + return desktop; + } + } +} diff --git a/lib/core/components/custom_text_field.dart b/lib/core/components/custom_text_field.dart new file mode 100644 index 0000000..cbc6828 --- /dev/null +++ b/lib/core/components/custom_text_field.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; + +import 'spaces.dart'; + +class CustomTextField extends StatelessWidget { + final TextEditingController controller; + final String label; + final Function(String value)? onChanged; + final bool obscureText; + final TextInputType? keyboardType; + final TextInputAction? textInputAction; + final TextCapitalization? textCapitalization; + final bool showLabel; + final Widget? prefixIcon; + final Widget? suffixIcon; + final bool readOnly; + + const CustomTextField({ + super.key, + required this.controller, + required this.label, + this.onChanged, + this.obscureText = false, + this.keyboardType, + this.textInputAction, + this.textCapitalization, + this.showLabel = true, + this.prefixIcon, + this.suffixIcon, + this.readOnly = false, + }); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (showLabel) ...[ + Text( + label, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SpaceHeight(12.0), + ], + TextFormField( + controller: controller, + onChanged: onChanged, + obscureText: obscureText, + keyboardType: keyboardType, + textInputAction: textInputAction, + textCapitalization: textCapitalization ?? TextCapitalization.none, + readOnly: readOnly, + decoration: InputDecoration( + prefixIcon: prefixIcon, + suffixIcon: suffixIcon, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16.0), + borderSide: const BorderSide(color: Colors.grey), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(16.0), + borderSide: const BorderSide(color: Colors.grey), + ), + hintText: label, + ), + ), + ], + ); + } +} diff --git a/lib/core/components/dashed_line.dart b/lib/core/components/dashed_line.dart new file mode 100644 index 0000000..c2af56f --- /dev/null +++ b/lib/core/components/dashed_line.dart @@ -0,0 +1,23 @@ +import 'package:flutter/material.dart'; + +class DashedLine extends StatelessWidget { + const DashedLine({super.key}); + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Row( + children: List.generate( + 400 ~/ 10, + (index) => Expanded( + child: Container( + color: index % 2 == 1 ? Colors.transparent : Colors.grey, + height: 1, + ), + ), + ), + ), + ); + } +} diff --git a/lib/core/components/image_picker_widget.dart b/lib/core/components/image_picker_widget.dart new file mode 100644 index 0000000..010fa6e --- /dev/null +++ b/lib/core/components/image_picker_widget.dart @@ -0,0 +1,130 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:image_picker/image_picker.dart'; +import 'package:cached_network_image/cached_network_image.dart'; + +import '../assets/assets.gen.dart'; +import '../constants/colors.dart'; +import '../constants/variables.dart'; +import 'buttons.dart'; +import 'spaces.dart'; + +class ImagePickerWidget extends StatefulWidget { + final String label; + final void Function(XFile? file) onChanged; + final bool showLabel; + final String? initialImageUrl; + + const ImagePickerWidget({ + super.key, + required this.label, + required this.onChanged, + this.showLabel = true, + this.initialImageUrl, + }); + + @override + State createState() => _ImagePickerWidgetState(); +} + +class _ImagePickerWidgetState extends State { + String? imagePath; + bool hasInitialImage = false; + + @override + void initState() { + super.initState(); + hasInitialImage = widget.initialImageUrl != null; + } + + Future _pickImage() async { + final pickedFile = await ImagePicker().pickImage( + source: ImageSource.gallery, + ); + + setState(() { + if (pickedFile != null) { + imagePath = pickedFile.path; + hasInitialImage = false; // Clear initial image when new image is picked + widget.onChanged(pickedFile); + } else { + debugPrint('No image selected.'); + widget.onChanged(null); + } + }); + } + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.showLabel) ...[ + Text( + widget.label, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SpaceHeight(12.0), + ], + Container( + padding: const EdgeInsets.all(6.0), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(16.0), + border: Border.all(color: AppColors.primary), + ), + child: Row( + children: [ + SizedBox( + width: 80.0, + height: 80.0, + child: ClipRRect( + borderRadius: BorderRadius.circular(10.0), + child: imagePath != null + ? Image.file( + File(imagePath!), + fit: BoxFit.cover, + ) + : hasInitialImage && widget.initialImageUrl != null + ? CachedNetworkImage( + imageUrl: widget.initialImageUrl!.contains('http') + ? widget.initialImageUrl! + : '${Variables.baseUrl}/${widget.initialImageUrl}', + placeholder: (context, url) => + const Center(child: CircularProgressIndicator()), + errorWidget: (context, url, error) => Container( + padding: const EdgeInsets.all(16.0), + color: AppColors.black.withOpacity(0.05), + child: Assets.icons.image.svg(), + ), + fit: BoxFit.cover, + ) + : Container( + padding: const EdgeInsets.all(16.0), + color: AppColors.black.withOpacity(0.05), + child: Assets.icons.image.svg(), + ), + ), + ), + const Spacer(), + Padding( + padding: const EdgeInsets.only(right: 10.0), + child: Button.filled( + height: 30.0, + width: 140.0, + onPressed: _pickImage, + label: 'Choose Photo', + fontSize: 12.0, + borderRadius: 5.0, + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/core/components/menu_button.dart b/lib/core/components/menu_button.dart new file mode 100644 index 0000000..0366ec9 --- /dev/null +++ b/lib/core/components/menu_button.dart @@ -0,0 +1,76 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + + +import '../constants/colors.dart'; +import 'components.dart'; + +class MenuButton extends StatelessWidget { + final String iconPath; + final String label; + final bool isActive; + final VoidCallback onPressed; + final bool isImage; + final double size; + + const MenuButton({ + super.key, + required this.iconPath, + required this.label, + this.isActive = false, + required this.onPressed, + this.isImage = false, + this.size = 90, + }); + + @override + Widget build(BuildContext context) { + return Flexible( + child: InkWell( + onTap: onPressed, + borderRadius: const BorderRadius.all(Radius.circular(6.0)), + child: Container( + width: context.deviceWidth, + padding: const EdgeInsets.all(15.0), + decoration: BoxDecoration( + color: isActive ? AppColors.primary : AppColors.white, + borderRadius: const BorderRadius.all(Radius.circular(6.0)), + boxShadow: [ + BoxShadow( + offset: const Offset(0, 4), + blurRadius: 20.0, + blurStyle: BlurStyle.outer, + spreadRadius: 0, + color: AppColors.black.withOpacity(0.1), + ), + ], + ), + child: Column( + children: [ + isImage + ? Image.asset(iconPath, + width: size, height: size, fit: BoxFit.contain) + : SvgPicture.asset( + iconPath, + colorFilter: ColorFilter.mode( + isActive ? AppColors.white : AppColors.primary, + BlendMode.srcIn, + ), + ), + const SpaceHeight(10.0), + Text( + label, + style: TextStyle( + color: isActive ? AppColors.white : AppColors.primary, + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/core/components/search_input.dart b/lib/core/components/search_input.dart new file mode 100644 index 0000000..0be828b --- /dev/null +++ b/lib/core/components/search_input.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; + +import '../constants/colors.dart'; + + + +class SearchInput extends StatelessWidget { + final TextEditingController controller; + final Function(String value)? onChanged; + final VoidCallback? onTap; + final String hintText; + + const SearchInput({ + super.key, + required this.controller, + this.onChanged, + this.onTap, + this.hintText = 'Cari di sini', + }); + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: AppColors.white, + borderRadius: BorderRadius.circular(8.0), + ), + child: TextFormField( + onTap: onTap, + readOnly: onTap != null, + controller: controller, + onChanged: onChanged, + decoration: InputDecoration( + hintText: hintText, + prefixIcon: const Icon( + Icons.search, + color: AppColors.primary, + ), + contentPadding: const EdgeInsets.all(16.0), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + borderSide: const BorderSide(color: Colors.grey), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + borderSide: const BorderSide(color: Colors.grey), + ), + ), + ), + ); + } +} diff --git a/lib/core/components/spaces.dart b/lib/core/components/spaces.dart new file mode 100644 index 0000000..7975925 --- /dev/null +++ b/lib/core/components/spaces.dart @@ -0,0 +1,17 @@ +import 'package:flutter/material.dart'; + +class SpaceHeight extends StatelessWidget { + final double height; + const SpaceHeight(this.height, {super.key}); + + @override + Widget build(BuildContext context) => SizedBox(height: height); +} + +class SpaceWidth extends StatelessWidget { + final double width; + const SpaceWidth(this.width, {super.key}); + + @override + Widget build(BuildContext context) => SizedBox(width: width); +} diff --git a/lib/core/components/tab_custom.dart b/lib/core/components/tab_custom.dart new file mode 100644 index 0000000..453d4d9 --- /dev/null +++ b/lib/core/components/tab_custom.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + +import '../constants/colors.dart'; + + + +class TabCustom extends StatelessWidget { + final List children; + final EdgeInsetsGeometry? padding; + + const TabCustom({ + super.key, + required this.children, + this.padding, + }); + + @override + Widget build(BuildContext context) { + return Container( + margin: padding, + decoration: BoxDecoration( + border: Border.all(color: AppColors.primary, width: 1.5), + borderRadius: const BorderRadius.all(Radius.circular(9.0)), + ), + child: Row( + children: children, + ), + ); + } +} + +class TabMenu extends StatelessWidget { + final String label; + final VoidCallback onTap; + final bool isActive; + + const TabMenu({ + super.key, + required this.label, + required this.onTap, + this.isActive = false, + }); + + @override + Widget build(BuildContext context) { + return Flexible( + child: InkWell( + onTap: onTap, + child: Container( + width: context.deviceWidth, + padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 15.0), + decoration: BoxDecoration( + borderRadius: const BorderRadius.all(Radius.circular(6.0)), + color: isActive ? AppColors.primary : AppColors.white, + ), + child: Center( + child: Text( + label, + style: TextStyle( + color: isActive ? AppColors.white : AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w700, + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/core/constants/colors.dart b/lib/core/constants/colors.dart new file mode 100644 index 0000000..3bfc2c3 --- /dev/null +++ b/lib/core/constants/colors.dart @@ -0,0 +1,39 @@ +import 'package:flutter/material.dart'; + +class AppColors { + /// primary = #3949AB + static const Color primary = Color(0xff6466f1); + + /// grey = #B7B7B7 + static const Color grey = Color(0xffB7B7B7); + + /// light = #F8F5FF + static const Color light = Color(0xffF8F5FF); + + /// blueLight = #C7D0EB + static const Color blueLight = Color(0xffC7D0EB); + + /// black = #000000 + static const Color black = Color(0xff000000); + + /// white = #FFFFFF + static const Color white = Color(0xffFFFFFF); + + /// green = #50C474 + static const Color green = Color(0xff50C474); + + /// red = #F4261A + static const Color red = Color(0xffF4261A); + + /// card = #E5E5E5 + static const Color card = Color(0xffE5E5E5); + + /// disabled = #C8D1E1 + static const Color disabled = Color(0xffC8D1E1); + + /// subtitle = #7890CD + static const Color subtitle = Color(0xff7890CD); + + /// stroke = #EFF0F6 + static const Color stroke = Color(0xffEFF0F6); +} diff --git a/lib/core/constants/variables.dart b/lib/core/constants/variables.dart new file mode 100644 index 0000000..d0717c9 --- /dev/null +++ b/lib/core/constants/variables.dart @@ -0,0 +1,6 @@ +class Variables { + static const String appName = 'POS Kasir Resto App'; + static const String apiVersion = 'v1'; + // static const String baseUrl = 'http://192.168.1.202:8000'; + static const String baseUrl = 'https://pos-app-tablet.enaklo.co.id'; +} diff --git a/lib/core/extensions/build_context_ext.dart b/lib/core/extensions/build_context_ext.dart new file mode 100644 index 0000000..313c912 --- /dev/null +++ b/lib/core/extensions/build_context_ext.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; + +extension BuildContextExt on BuildContext { + double get deviceHeight => MediaQuery.of(this).size.height; + + double get deviceWidth => MediaQuery.of(this).size.width; +} + +extension NavigatorExt on BuildContext { + void pop([T? result]) { + Navigator.pop(this, result); + } + + void popToRoot() { + Navigator.popUntil(this, (route) => route.isFirst); + } + + Future push(Widget widget, [String? name]) async { + return Navigator.push( + this, + MaterialPageRoute( + builder: (context) => widget, + settings: RouteSettings(name: name), + ), + ); + } + + Future pushReplacement( + Widget widget) async { + return Navigator.pushReplacement( + this, + MaterialPageRoute(builder: (context) => widget), + ); + } + + Future pushAndRemoveUntil( + Widget widget, bool Function(Route route) predicate) async { + return Navigator.pushAndRemoveUntil( + this, + MaterialPageRoute(builder: (context) => widget), + predicate, + ); + } +} diff --git a/lib/core/extensions/date_time_ext.dart b/lib/core/extensions/date_time_ext.dart new file mode 100644 index 0000000..0bb397d --- /dev/null +++ b/lib/core/extensions/date_time_ext.dart @@ -0,0 +1,66 @@ +const List _dayNames = [ + 'Senin', + 'Selasa', + 'Rabu', + 'Kamis', + 'Jumat', + 'Sabtu', + 'Minggu', +]; + +const List _monthNames = [ + 'Januari', + 'Februari', + 'Maret', + 'April', + 'Mei', + 'Juni', + 'Juli', + 'Agustus', + 'September', + 'Oktober', + 'November', + 'Desember' +]; + +extension DateTimeExt on DateTime { + String toFormattedTime() { + final int hour12 = hour % 12; + final String monthName = _monthNames[month - 1]; + + return '$day $monthName, ${hour12.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}'; + } + + String toFormattedDate() { + String dayName = _dayNames[weekday - 1]; + String day = this.day.toString(); + String month = _monthNames[this.month - 1]; + String year = this.year.toString(); + + return '$dayName, $day $month $year'; + } + + String toFormattedDate2() { + String day = this.day.toString(); + String month = _monthNames[this.month - 1]; + String year = this.year.toString(); + + return '$day $month $year'; + } + + String toFormattedDate3() { + String day = this.day.toString(); + String month = _monthNames[this.month - 1]; + String year = this.year.toString(); + String hour = this + .hour + .toString() + .padLeft(2, '0'); // Menambahkan nol di depan jika jam hanya satu digit + String minute = this.minute.toString().padLeft( + 2, '0'); // Menambahkan nol di depan jika menit hanya satu digit + String second = this.second.toString().padLeft( + 2, '0'); // Menambahkan nol di depan jika detik hanya satu digit + + return '$day $month $year, $hour:$minute:$second'; + } +} diff --git a/lib/core/extensions/int_ext.dart b/lib/core/extensions/int_ext.dart new file mode 100644 index 0000000..016f561 --- /dev/null +++ b/lib/core/extensions/int_ext.dart @@ -0,0 +1,15 @@ +import 'package:intl/intl.dart'; + +extension IntegerExt on int { + String get currencyFormatRp => NumberFormat.currency( + locale: 'id', + symbol: 'Rp. ', + decimalDigits: 0, + ).format(this); + + String get currencyFormatRpV2 => NumberFormat.currency( + locale: 'id', + symbol: 'Rp ', + decimalDigits: 0, + ).format(this); +} diff --git a/lib/core/extensions/string_ext.dart b/lib/core/extensions/string_ext.dart new file mode 100644 index 0000000..4ed973a --- /dev/null +++ b/lib/core/extensions/string_ext.dart @@ -0,0 +1,18 @@ +import 'package:intl/intl.dart'; + +extension StringExt on String { + int get toIntegerFromText { + final cleanedText = replaceAll(RegExp(r'[^0-9]'), ''); + final parsedValue = int.tryParse(cleanedText) ?? 0; + return parsedValue; + } + + String get currencyFormatRpV2 { + final parsedValue = int.tryParse(this) ?? 0; + return NumberFormat.currency( + locale: 'id', + symbol: 'Rp ', + decimalDigits: 0, + ).format(parsedValue); + } +} diff --git a/lib/core/utils/app_icon_generator.dart b/lib/core/utils/app_icon_generator.dart new file mode 100644 index 0000000..ae273f0 --- /dev/null +++ b/lib/core/utils/app_icon_generator.dart @@ -0,0 +1,132 @@ +import 'dart:ui' as ui; +import 'dart:typed_data'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class AppIconGenerator { + static Future generateAppIcon() async { + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + const size = Size(1024, 1024); + + // Create a white background + final paint = Paint()..color = Colors.white; + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); + + // Create a blue circle background + paint.color = const Color(0xFF2196F3); // Material Blue + canvas.drawCircle( + Offset(size.width / 2, size.height / 2), + size.width * 0.4, + paint, + ); + + // Draw the gift box icon + _drawGiftBox(canvas, size); + + // Draw the text + _drawText(canvas, size); + + final picture = recorder.endRecording(); + final image = await picture.toImage(1024, 1024); + final byteData = await image.toByteData(format: ui.ImageByteFormat.png); + return byteData!.buffer.asUint8List(); + } + + static void _drawGiftBox(Canvas canvas, Size size) { + final paint = Paint() + ..color = Colors.white + ..style = PaintingStyle.stroke + ..strokeWidth = size.width * 0.02; + + final centerX = size.width / 2; + final centerY = size.height / 2 - size.height * 0.1; + final boxSize = size.width * 0.15; + + // Draw gift box + final boxRect = Rect.fromCenter( + center: Offset(centerX, centerY), + width: boxSize, + height: boxSize, + ); + canvas.drawRect(boxRect, paint); + + // Draw bow + final bowWidth = boxSize * 0.8; + final bowHeight = boxSize * 0.3; + final bowRect = Rect.fromCenter( + center: Offset(centerX, centerY - boxSize / 2), + width: bowWidth, + height: bowHeight, + ); + canvas.drawRRect( + RRect.fromRectAndRadius(bowRect, Radius.circular(bowHeight / 2)), + paint, + ); + + // Draw 'e' inside the box + final textPainter = TextPainter( + text: TextSpan( + text: 'e', + style: TextStyle( + color: Colors.white, + fontSize: boxSize * 0.4, + fontWeight: FontWeight.bold, + ), + ), + textDirection: TextDirection.ltr, + ); + textPainter.layout(); + textPainter.paint( + canvas, + Offset( + centerX - textPainter.width / 2, + centerY - textPainter.height / 2, + ), + ); + } + + static void _drawText(Canvas canvas, Size size) { + // Draw "ENAKLO" + final enakloPainter = TextPainter( + text: TextSpan( + text: 'ENAKLO', + style: TextStyle( + color: Colors.white, + fontSize: size.width * 0.08, + fontWeight: FontWeight.bold, + ), + ), + textDirection: TextDirection.ltr, + ); + enakloPainter.layout(); + enakloPainter.paint( + canvas, + Offset( + size.width / 2 - enakloPainter.width / 2, + size.height / 2 + size.height * 0.05, + ), + ); + + // Draw "POS" + final posPainter = TextPainter( + text: TextSpan( + text: 'POS', + style: TextStyle( + color: Colors.white, + fontSize: size.width * 0.06, + fontWeight: FontWeight.w500, + ), + ), + textDirection: TextDirection.ltr, + ); + posPainter.layout(); + posPainter.paint( + canvas, + Offset( + size.width / 2 - posPainter.width / 2, + size.height / 2 + size.height * 0.15, + ), + ); + } +} \ No newline at end of file diff --git a/lib/core/utils/date_formatter.dart b/lib/core/utils/date_formatter.dart new file mode 100644 index 0000000..49c722d --- /dev/null +++ b/lib/core/utils/date_formatter.dart @@ -0,0 +1,19 @@ +import 'package:intl/intl.dart'; + +class DateFormatter { + static String formatDateTime(DateTime dateTime) { + return '${dateTime.year}-${_addZeroPrefix(dateTime.month)}-${_addZeroPrefix(dateTime.day)}'; + } + + static String _addZeroPrefix(int value) { + return value.toString().padLeft(2, '0'); + } + + static String formatDateTime2(String dateTimeString) { + final dateTime = DateTime.parse(dateTimeString); + final formatter = DateFormat( + 'dd MMMM yyyy, HH:mm', + ); + return formatter.format(dateTime); + } +} diff --git a/lib/core/utils/helper_pdf_service.dart b/lib/core/utils/helper_pdf_service.dart new file mode 100644 index 0000000..b8c8a89 --- /dev/null +++ b/lib/core/utils/helper_pdf_service.dart @@ -0,0 +1,79 @@ +import 'dart:developer'; +import 'dart:io'; + +import 'package:open_file/open_file.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:pdf/widgets.dart'; + +class HelperPdfService { + static Future saveDocument({ + required String name, + required Document pdf, + }) async { + try { + log("Starting PDF save process for: $name"); + log("PDF document object: $pdf"); + + final bytes = await pdf.save(); + log("PDF bytes generated successfully, size: ${bytes.length} bytes"); + + if (bytes.isEmpty) { + log("WARNING: PDF bytes are empty!"); + return Future.error("PDF bytes are empty"); + } + + final dir = await getApplicationDocumentsDirectory(); + log("Documents directory: ${dir.path}"); + + final file = File('${dir.path}/$name'); + log("Saving PDF to: ${file.path}"); + + await file.writeAsBytes(bytes); + log("PDF saved successfully to: ${file.path}"); + + // Verify file was created + if (await file.exists()) { + final fileSize = await file.length(); + log("File exists and size is: $fileSize bytes"); + } else { + log("ERROR: File was not created!"); + return Future.error("File was not created"); + } + + return file; + } catch (e) { + log("Failed to save document: $e"); + log("Error stack trace: ${StackTrace.current}"); + return Future.error("Failed to save document: $e"); + } + } + + static Future openFile(File file) async { + try { + final url = file.path; + log("Attempting to open file: $url"); + + if (!await file.exists()) { + log("ERROR: File does not exist: $url"); + return; + } + + final fileSize = await file.length(); + log("File exists and size is: $fileSize bytes"); + + log("Calling OpenFile.open..."); + final result = await OpenFile.open(url, type: "application/pdf"); + log("OpenFile result: $result"); + + if (result.type == ResultType.done) { + log("File opened successfully"); + } else { + log("File opening failed with result: ${result.type}"); + log("Error message: ${result.message}"); + } + } catch (e) { + log("Failed to open file: $e"); + log("Error stack trace: ${StackTrace.current}"); + } + } +} diff --git a/lib/core/utils/item_sales_invoice.dart b/lib/core/utils/item_sales_invoice.dart new file mode 100644 index 0000000..4b46c87 --- /dev/null +++ b/lib/core/utils/item_sales_invoice.dart @@ -0,0 +1,154 @@ +import 'dart:io'; + +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:flutter/services.dart'; + +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:enaklo_pos/data/models/response/item_sales_response_model.dart'; +import 'package:pdf/widgets.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; + +class ItemSalesInvoice { + static late Font ttf; + static Future generate( + List itemSales, String searchDateFormatted) async { + final pdf = Document(); + // var data = await rootBundle.load("assets/fonts/noto-sans.ttf"); + // ttf = Font.ttf(data); + final ByteData dataImage = await rootBundle.load('assets/images/logo.png'); + final Uint8List bytes = dataImage.buffer.asUint8List(); + + // Membuat objek Image dari gambar + final image = pw.MemoryImage(bytes); + + pdf.addPage( + MultiPage( + build: (context) => [ + buildHeader(image, searchDateFormatted), + SizedBox(height: 1 * PdfPageFormat.cm), + buildInvoice(itemSales), + Divider(), + SizedBox(height: 0.25 * PdfPageFormat.cm), + ], + footer: (context) => buildFooter(), + ), + ); + + return HelperPdfService.saveDocument( + name: + 'Enaklo POS | Item Sales Report | ${DateTime.now().millisecondsSinceEpoch}.pdf', + pdf: pdf); + } + + static Widget buildHeader(MemoryImage image, String searchDateFormatted) => + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 1 * PdfPageFormat.cm), + Text('Enaklo POS | Item Sales Report', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + )), + SizedBox(height: 0.2 * PdfPageFormat.cm), + Text( + "Data: $searchDateFormatted", + ), + Text( + 'Created At: ${DateTime.now().toFormattedDate3()}', + ), + ], + ), + Image( + image, + width: 80.0, + height: 80.0, + fit: BoxFit.fill, + ), + ]); + + static Widget buildInvoice(List itemSales) { + final headers = ['Id', 'Order', 'Product', 'Qty', 'Price', 'Total']; + final data = itemSales.map((item) { + return [ + item.id!, + item.orderId, + item.productName, + item.price!.currencyFormatRp, + item.quantity, + (item.price! * item.quantity!).currencyFormatRp + ]; + }).toList(); + + return Table.fromTextArray( + headers: headers, + data: data, + border: null, + headerStyle: TextStyle( + fontWeight: FontWeight.bold, color: PdfColor.fromHex('FFFFFF')), + headerDecoration: BoxDecoration(color: PdfColors.blue), + cellHeight: 30, + cellAlignments: { + 0: Alignment.centerLeft, + 1: Alignment.center, + 2: Alignment.center, + 3: Alignment.centerLeft, + 4: Alignment.centerLeft, + 5: Alignment.centerLeft, + }, + ); + } + + static Widget buildFooter() => Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Divider(), + SizedBox(height: 2 * PdfPageFormat.mm), + buildSimpleText( + title: 'Address', + value: + 'Jalan Melati No. 12, Mranggen, Demak, Central Java, 89568'), + SizedBox(height: 1 * PdfPageFormat.mm), + ], + ); + + static buildSimpleText({ + required String title, + required String value, + }) { + final style = TextStyle(fontWeight: FontWeight.bold); + + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: pw.CrossAxisAlignment.end, + children: [ + Text(title, style: style), + SizedBox(width: 2 * PdfPageFormat.mm), + Text(value), + ], + ); + } + + static buildText({ + required String title, + required String value, + double width = double.infinity, + TextStyle? titleStyle, + bool unite = false, + }) { + final style = titleStyle ?? TextStyle(fontWeight: FontWeight.bold); + + return Container( + width: width, + child: Row( + children: [ + Expanded(child: Text(title, style: style)), + Text(value, style: unite ? style : null), + ], + ), + ); + } +} diff --git a/lib/core/utils/permession_handler.dart b/lib/core/utils/permession_handler.dart new file mode 100644 index 0000000..cc33817 --- /dev/null +++ b/lib/core/utils/permession_handler.dart @@ -0,0 +1,43 @@ +import 'dart:developer'; + +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:permission_handler/permission_handler.dart'; + +class PermessionHelper { + Future checkPermission() async { + final deviceInfo = await DeviceInfoPlugin().androidInfo; + bool permissionStatus; + if (deviceInfo.version.sdkInt > 32) { + permissionStatus = await Permission.photos.request().isGranted; + } else { + permissionStatus = await Permission.storage.request().isGranted; + } + + if (permissionStatus) { + log('Izin penyimpanan sudah diberikan.'); + } else { + if (deviceInfo.version.sdkInt > 32) { + log('deviceInfo.version.sdkInt > 32.'); + permissionStatus = await Permission.photos.request().isGranted; + } else { + permissionStatus = await Permission.storage.request().isGranted; + } + // } else { + // openAppSettings(); + // } + } + log('permissionStatus: $permissionStatus'); + return permissionStatus; + } + + void permessionPrinter() async { + Map statuses = await [ + Permission.bluetooth, + Permission.bluetoothScan, + Permission.bluetoothAdvertise, + Permission.bluetoothConnect, + ].request(); + + log("statuses: $statuses"); + } +} diff --git a/lib/core/utils/printer_service.dart b/lib/core/utils/printer_service.dart new file mode 100644 index 0000000..5f01355 --- /dev/null +++ b/lib/core/utils/printer_service.dart @@ -0,0 +1,157 @@ +import 'dart:developer'; +import 'package:flutter/material.dart'; +import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; + +class PrinterService { + static final PrinterService _instance = PrinterService._internal(); + factory PrinterService() => _instance; + PrinterService._internal(); + + /// Connect to Bluetooth printer + Future connectBluetoothPrinter(String macAddress) async { + try { + // Check if already connected + bool isConnected = await PrintBluetoothThermal.connectionStatus; + if (isConnected) { + log("Already connected to Bluetooth printer"); + return true; + } + + // Connect to the printer + bool connected = await PrintBluetoothThermal.connect( + macPrinterAddress: macAddress); + + if (connected) { + log("Successfully connected to Bluetooth printer: $macAddress"); + } else { + log("Failed to connect to Bluetooth printer: $macAddress"); + } + + return connected; + } catch (e) { + log("Error connecting to Bluetooth printer: $e"); + return false; + } + } + + /// Print using Bluetooth printer + Future printBluetooth(List printData) async { + try { + bool isConnected = await PrintBluetoothThermal.connectionStatus; + if (!isConnected) { + log("Not connected to Bluetooth printer"); + return false; + } + + bool printResult = await PrintBluetoothThermal.writeBytes(printData); + if (printResult) { + log("Successfully printed via Bluetooth"); + } else { + log("Failed to print via Bluetooth"); + } + + return printResult; + } catch (e) { + log("Error printing via Bluetooth: $e"); + return false; + } + } + + /// Print using Network printer + Future printNetwork(String ipAddress, List printData) async { + try { + final printer = PrinterNetworkManager(ipAddress); + PosPrintResult connect = await printer.connect(); + + if (connect == PosPrintResult.success) { + PosPrintResult printing = await printer.printTicket(printData); + printer.disconnect(); + + if (printing == PosPrintResult.success) { + log("Successfully printed via Network printer: $ipAddress"); + return true; + } else { + log("Failed to print via Network printer: ${printing.msg}"); + return false; + } + } else { + log("Failed to connect to Network printer: ${connect.msg}"); + return false; + } + } catch (e) { + log("Error printing via Network: $e"); + return false; + } + } + + /// Print with automatic printer type detection + Future printWithPrinter(PrintModel printer, List printData, BuildContext context) async { + try { + if (printer.type == 'Bluetooth') { + bool connected = await connectBluetoothPrinter(printer.address); + if (!connected) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to connect to ${printer.name}')), + ); + return false; + } + + bool printResult = await printBluetooth(printData); + if (!printResult) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to print to ${printer.name}')), + ); + } + return printResult; + } else { + bool printResult = await printNetwork(printer.address, printData); + if (!printResult) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to print to ${printer.name}')), + ); + } + return printResult; + } + } catch (e) { + log("Error printing with printer ${printer.name}: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing to ${printer.name}: $e')), + ); + return false; + } + } + + /// Disconnect from Bluetooth printer + Future disconnectBluetooth() async { + try { + bool result = await PrintBluetoothThermal.disconnect; + log("Bluetooth printer disconnected: $result"); + return result; + } catch (e) { + log("Error disconnecting Bluetooth printer: $e"); + return false; + } + } + + /// Check if Bluetooth is enabled + Future isBluetoothEnabled() async { + try { + return await PrintBluetoothThermal.bluetoothEnabled; + } catch (e) { + log("Error checking Bluetooth status: $e"); + return false; + } + } + + /// Get paired Bluetooth devices + Future> getPairedBluetoothDevices() async { + try { + return await PrintBluetoothThermal.pairedBluetooths; + } catch (e) { + log("Error getting paired Bluetooth devices: $e"); + return []; + } + } +} \ No newline at end of file diff --git a/lib/core/utils/revenue_invoice.dart b/lib/core/utils/revenue_invoice.dart new file mode 100644 index 0000000..4471e9a --- /dev/null +++ b/lib/core/utils/revenue_invoice.dart @@ -0,0 +1,223 @@ +import 'dart:io'; +import 'dart:developer'; + +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/data/models/response/summary_response_model.dart'; +import 'package:flutter/services.dart'; + +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:pdf/widgets.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:flutter/foundation.dart'; + +class RevenueInvoice { + static late Font ttf; + static Future generate( + SummaryModel summaryModel, + String searchDateFormatted, + ) async { + try { + log("Starting PDF generation for summary report"); + log("Summary model: ${summaryModel.toMap()}"); + log("Search date formatted: $searchDateFormatted"); + + final pdf = Document(); + log("PDF document created"); + + // Load logo image + log("Loading logo image..."); + final ByteData dataImage = await rootBundle.load('assets/images/logo.png'); + final Uint8List bytes = dataImage.buffer.asUint8List(); + final image = pw.MemoryImage(bytes); + log("Logo image loaded successfully, size: ${bytes.length} bytes"); + + log("Adding page to PDF..."); + pdf.addPage( + MultiPage( + build: (context) => [ + buildHeader(summaryModel, image, searchDateFormatted), + SizedBox(height: 1 * PdfPageFormat.cm), + buildTotal(summaryModel), + ], + footer: (context) => buildFooter(summaryModel), + ), + ); + log("PDF page added successfully"); + + log("Saving PDF document..."); + return HelperPdfService.saveDocument( + name: + 'Enaklo POS | Summary Sales Report | ${DateTime.now().millisecondsSinceEpoch}.pdf', + pdf: pdf, + ); + } catch (e) { + log("Error generating PDF: $e"); + log("Error stack trace: ${StackTrace.current}"); + return Future.error("Failed to generate PDF: $e"); + } + } + + static Widget buildHeader( + SummaryModel invoice, + MemoryImage image, + String searchDateFormatted, + ) => + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 1 * PdfPageFormat.cm), + Text('Enaklo POS | Summary Sales Report', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + )), + SizedBox(height: 0.2 * PdfPageFormat.cm), + Text( + "Data: $searchDateFormatted", + ), + Text( + 'Created At: ${DateTime.now().toFormattedDate3()}', + ), + ], + ), + Image( + image, + width: 80.0, + height: 80.0, + fit: BoxFit.fill, + ), + ]); + + static Widget buildTotal(SummaryModel summaryModel) { + log("Building total section with summary model: ${summaryModel.toMap()}"); + + // Helper function to safely parse string to int + int safeParseInt(String? value) { + if (value == null || value.isEmpty) return 0; + try { + return int.parse(value.replaceAll('.00', '')); + } catch (e) { + log("Error parsing value '$value' to int: $e"); + return 0; + } + } + + return Container( + width: double.infinity, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + buildText( + title: 'Revenue', + value: safeParseInt(summaryModel.totalRevenue).currencyFormatRp, + unite: true, + ), + Divider(), + buildText( + title: 'Sub Total', + titleStyle: TextStyle(fontWeight: FontWeight.normal), + value: safeParseInt(summaryModel.totalSubtotal).currencyFormatRp, + unite: true, + ), + buildText( + title: 'Discount', + titleStyle: TextStyle(fontWeight: FontWeight.normal), + value: "- ${safeParseInt(summaryModel.totalDiscount).currencyFormatRp}", + unite: true, + textStyle: TextStyle( + color: PdfColor.fromHex('#FF0000'), + fontWeight: FontWeight.bold, + ), + ), + buildText( + title: 'Tax', + titleStyle: TextStyle(fontWeight: FontWeight.normal), + value: "- ${safeParseInt(summaryModel.totalTax).currencyFormatRp}", + textStyle: TextStyle( + color: PdfColor.fromHex('#FF0000'), + fontWeight: FontWeight.bold, + ), + unite: true, + ), + buildText( + title: 'Service Charge', + titleStyle: TextStyle( + fontWeight: FontWeight.normal, + ), + value: safeParseInt(summaryModel.totalServiceCharge).currencyFormatRp, + unite: true, + ), + Divider(), + buildText( + title: 'Total ', + titleStyle: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + ), + value: (summaryModel.total ?? 0).currencyFormatRp, + unite: true, + ), + SizedBox(height: 2 * PdfPageFormat.mm), + Container(height: 1, color: PdfColors.grey400), + SizedBox(height: 0.5 * PdfPageFormat.mm), + Container(height: 1, color: PdfColors.grey400), + ], + ), + ); + } + + static Widget buildFooter(SummaryModel summaryModel) => Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Divider(), + SizedBox(height: 2 * PdfPageFormat.mm), + buildSimpleText( + title: 'Address', + value: + 'Jalan Melati No. 12, Mranggen, Demak, Central Java, 89568'), + SizedBox(height: 1 * PdfPageFormat.mm), + ], + ); + + static buildSimpleText({ + required String title, + required String value, + }) { + final style = TextStyle(fontWeight: FontWeight.bold); + + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: pw.CrossAxisAlignment.end, + children: [ + Text(title, style: style), + SizedBox(width: 2 * PdfPageFormat.mm), + Text(value), + ], + ); + } + + static buildText({ + required String title, + required String value, + double width = double.infinity, + TextStyle? titleStyle, + TextStyle? textStyle, + bool unite = false, + }) { + final style = titleStyle ?? TextStyle(fontWeight: FontWeight.bold); + final style2 = textStyle ?? TextStyle(fontWeight: FontWeight.bold); + + return Container( + width: width, + child: Row( + children: [ + Expanded(child: Text(title, style: style)), + Text(value, style: style2), + ], + ), + ); + } +} diff --git a/lib/core/utils/transaction_sales_invoice.dart b/lib/core/utils/transaction_sales_invoice.dart new file mode 100644 index 0000000..f7a7b70 --- /dev/null +++ b/lib/core/utils/transaction_sales_invoice.dart @@ -0,0 +1,161 @@ +import 'dart:io'; + +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:flutter/services.dart'; + +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart'; +import 'package:pdf/widgets.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; + +class TransactionSalesInvoice { + static late Font ttf; + static Future generate( + List itemOrders, String searchDateFormatted) async { + final pdf = Document(); + // var data = await rootBundle.load("assets/fonts/noto-sans.ttf"); + // ttf = Font.ttf(data); + final ByteData dataImage = await rootBundle.load('assets/images/logo.png'); + final Uint8List bytes = dataImage.buffer.asUint8List(); + + // Membuat objek Image dari gambar + final image = pw.MemoryImage(bytes); + + pdf.addPage( + MultiPage( + build: (context) => [ + buildHeader(image, searchDateFormatted), + SizedBox(height: 1 * PdfPageFormat.cm), + buildInvoice(itemOrders), + Divider(), + SizedBox(height: 0.25 * PdfPageFormat.cm), + ], + footer: (context) => buildFooter(), + ), + ); + + return HelperPdfService.saveDocument( + name: + 'Enaklo POS | Transaction Sales Report | ${DateTime.now().millisecondsSinceEpoch}.pdf', + pdf: pdf); + } + + static Widget buildHeader(MemoryImage image, String searchDateFormatted) => + Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(height: 1 * PdfPageFormat.cm), + Text('Enaklo POS | Transaction Sales Report', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + )), + SizedBox(height: 0.2 * PdfPageFormat.cm), + Text( + "Data: $searchDateFormatted", + ), + Text( + 'Created At: ${DateTime.now().toFormattedDate3()}', + ), + ], + ), + Image( + image, + width: 80.0, + height: 80.0, + fit: BoxFit.fill, + ), + ]); + + static Widget buildInvoice(List itemOrders) { + final headers = [ + 'Total', + 'Sub Total', + 'Tax', + 'Discount', + 'Service', + 'Time' + ]; + final data = itemOrders.map((item) { + return [ + item.total!.currencyFormatRp, + item.subTotal!.currencyFormatRp, + item.tax!.currencyFormatRp, + int.parse(item.discountAmount!.replaceAll('.00', '')).currencyFormatRp, + item.serviceCharge!.currencyFormatRp, + item.transactionTime!.toFormattedDate2(), + ]; + }).toList(); + + return Table.fromTextArray( + headers: headers, + data: data, + border: null, + headerStyle: TextStyle( + fontWeight: FontWeight.bold, color: PdfColor.fromHex('FFFFFF')), + headerDecoration: BoxDecoration(color: PdfColors.blue), + cellHeight: 30, + cellAlignments: { + 0: Alignment.center, + 1: Alignment.center, + 2: Alignment.center, + 3: Alignment.center, + 4: Alignment.center, + 5: Alignment.center, + }, + ); + } + + static Widget buildFooter() => Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Divider(), + SizedBox(height: 2 * PdfPageFormat.mm), + buildSimpleText( + title: 'Address', + value: + 'Jalan Melati No. 12, Mranggen, Demak, Central Java, 89568'), + SizedBox(height: 1 * PdfPageFormat.mm), + ], + ); + + static buildSimpleText({ + required String title, + required String value, + }) { + final style = TextStyle(fontWeight: FontWeight.bold); + + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: pw.CrossAxisAlignment.end, + children: [ + Text(title, style: style), + SizedBox(width: 2 * PdfPageFormat.mm), + Text(value), + ], + ); + } + + static buildText({ + required String title, + required String value, + double width = double.infinity, + TextStyle? titleStyle, + bool unite = false, + }) { + final style = titleStyle ?? TextStyle(fontWeight: FontWeight.bold); + + return Container( + width: width, + child: Row( + children: [ + Expanded(child: Text(title, style: style)), + Text(value, style: unite ? style : null), + ], + ), + ); + } +} diff --git a/lib/data/dataoutputs/laman_print.dart b/lib/data/dataoutputs/laman_print.dart new file mode 100644 index 0000000..5f5447f --- /dev/null +++ b/lib/data/dataoutputs/laman_print.dart @@ -0,0 +1,259 @@ +// import 'package:enaklo_pos/core/extensions/int_ext.dart'; +// import 'package:enaklo_pos/core/extensions/string_ext.dart'; +// import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +// import 'package:imin_printer/column_maker.dart'; +// import 'package:imin_printer/enums.dart'; +// import 'package:imin_printer/imin_printer.dart'; +// import 'package:imin_printer/imin_style.dart'; +// import 'package:intl/intl.dart'; + +// class LamanPrint { +// LamanPrint._init(); + +// static final LamanPrint instance = LamanPrint._init(); +// static IminPrinter? _iminPrinter; + +// static Future init() async { +// _iminPrinter = IminPrinter(); +// await _iminPrinter!.initPrinter(); +// } + +// Future printOrderV3( +// List products, +// int totalQuantity, +// int totalPrice, +// String paymentMethod, +// int nominalBayar, +// int kembalian, +// int subTotal, +// int discount, +// int pajak, +// int serviceCharge, +// String namaKasir, +// String customerName, +// int paper, +// ) async { +// final iminPrinter = _iminPrinter!; + +// await iminPrinter.printText( +// 'Jago Resto', +// style: IminTextStyle(align: IminPrintAlign.center, fontSize: 24), +// ); + +// await iminPrinter.printText( +// 'Jl. Kebun Raya No. 1, Sinduhadi, Ngaglik, Sleman', +// style: IminTextStyle(align: IminPrintAlign.center, fontSize: 20), +// ); + +// await iminPrinter.printText( +// '------------------------------------------------------', +// style: IminTextStyle(align: IminPrintAlign.center, fontSize: 20), +// ); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: DateFormat('dd MMM yyyy').format(DateTime.now()), +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: DateFormat('HH:mm').format(DateTime.now()), +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Receipt Number', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: 'JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Kasir', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: namaKasir, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// for (final product in products) { +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: '${product.quantity} x ${product.product.name}', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: +// '${product.product.price!.toIntegerFromText * product.quantity}' +// .currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); +// } + +// // await iminPrinter.printText( +// // '--------------------------------', +// // style: IminTextStyle(align: IminPrintAlign.center, fontSize: 20), +// // ); + +// final subTotalPrice = products.fold( +// 0, +// (previousValue, element) => +// previousValue + +// (element.product.price!.toIntegerFromText * element.quantity)); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Subtotal $totalQuantity Product', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: subTotalPrice.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Discount', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: discount.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Tax PB1 (10%)', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: '${(totalPrice * 0.1).ceil()}'.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Service Charge(5%)', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: '${(totalPrice * 0.05).ceil()}'.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Total', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: totalPrice.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Bayar', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: nominalBayar.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); +// await iminPrinter.printColumnsText( +// cols: [ +// ColumnMaker( +// text: 'Kembali', +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.left, +// ), +// ColumnMaker( +// text: kembalian.currencyFormatRpV2, +// width: 2, +// fontSize: 20, +// align: IminPrintAlign.right, +// ), +// ], +// ); + +// await iminPrinter.printText( +// 'Terima Kasih', +// style: IminTextStyle(align: IminPrintAlign.center, fontSize: 20), +// ); + +// await iminPrinter.printAndFeedPaper(100); +// await iminPrinter.partialCut(); +// } +// } diff --git a/lib/data/dataoutputs/print_dataoutputs.dart b/lib/data/dataoutputs/print_dataoutputs.dart new file mode 100644 index 0000000..c071a1f --- /dev/null +++ b/lib/data/dataoutputs/print_dataoutputs.dart @@ -0,0 +1,1137 @@ +import 'dart:math'; + +import 'package:esc_pos_utils_plus/esc_pos_utils_plus.dart'; +import 'package:flutter/services.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:intl/intl.dart'; +import 'package:image/image.dart' as img; + +class PrintDataoutputs { + PrintDataoutputs._init(); + + static final PrintDataoutputs instance = PrintDataoutputs._init(); + + Future> printOrder( + List products, + int totalQuantity, + int totalPrice, + String paymentMethod, + int nominalBayar, + String namaKasir, + int discount, + int tax, + int subTotal, + int normalPrice, + int sizeReceipt) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(sizeReceipt == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + final pajak = totalPrice * 0.11; + final total = totalPrice + pajak; + + bytes += generator.reset(); + bytes += generator.text('Enaklo POS', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size1, + width: PosTextSize.size1, + )); + + bytes += generator.text('Jalan Nanasa No. 1', + styles: const PosStyles(bold: true, align: PosAlign.center)); + bytes += generator.text( + 'Date : ${DateFormat('dd/MM/yyyy HH:mm').format(DateTime.now())}', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + bytes += generator.feed(1); + bytes += generator.text('Pesanan:', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + for (final product in products) { + bytes += generator.text(product.product.name!, + styles: const PosStyles(align: PosAlign.left)); + + bytes += generator.row([ + PosColumn( + text: + '${product.product.price!.toIntegerFromText.currencyFormatRp} x ${product.quantity}', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: '${product.product.price!.toIntegerFromText * product.quantity}' + .toIntegerFromText + .currencyFormatRp, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + } + + bytes += generator.feed(1); + + bytes += generator.row([ + PosColumn( + text: 'Normal price', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: normalPrice.currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Diskon', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: discount.currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Sub total', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: subTotal.currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Pajak PB1 (10%)', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: tax.ceil().currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Final total', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: totalPrice.currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Bayar', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: total.ceil().currencyFormatRp, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Pembayaran', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: paymentMethod, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.feed(1); + bytes += generator.text('Terima kasih', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(3); + + return bytes; + } + + Future> printOrderV2( + List products, int orderId, int paper + // OrderModel order, + // Uint8List logo, + // StoreModel store, + // TemplateReceiptModel? template, + ) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + // final ByteData data = await rootBundle.load('assets/logo/mylogo.png'); + // final Uint8List bytesData = data.buffer.asUint8List(); + // final img.Image? orginalImage = img.decodeImage(logo); + + bytes += generator.reset(); + + // if (orginalImage != null) { + // final img.Image grayscalledImage = img.grayscale(orginalImage); + // final img.Image resizedImage = + // img.copyResize(grayscalledImage, width: 240); + // bytes += generator.imageRaster(resizedImage, align: PosAlign.center); + // bytes += generator.feed(3); + // } + + bytes += generator.text('Enaklo POS', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + + bytes += generator.text('Jalan Nanasa No. 1', + styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('Kab. Sleman, DI Yogyakarta', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('coffeewithbahri@gmail.com', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('085640899224', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + + bytes += generator.feed(1); + + bytes += generator.text( + paper == 80 + ? '================================================' + : '================================', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + // if (template.receiptType == 'Default') { + // bytes += generator.row([ + // PosColumn( + // text: 'Antrian', + // width: 5, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: ':', + // width: 1, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: order.noQueue.toString(), + // width: 6, + // styles: const PosStyles(align: PosAlign.left), + // ), + // ]); + // } + bytes += generator.row([ + PosColumn( + text: 'ID Transaksi', + width: 5, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: ':', + width: 1, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: orderId.toString(), + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Waktu', + width: 5, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: ':', + width: 1, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: DateFormat('dd MMM yy HH:mm').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Order By', + width: 5, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: ':', + width: 1, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'Sarah', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Kasir', + width: 5, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: ':', + width: 1, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'Susan', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + ]); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + for (final product in products) { + bytes += generator.row([ + PosColumn( + text: '${product.quantity} ${product.product.name}', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: (product.product.price!.toIntegerFromText * product.quantity) + .currencyFormatRp, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + } + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + // bytes += generator.row([ + // PosColumn( + // text: 'Subtotal Produk', + // width: 8, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: order.subTotal.currencyFormatRpV2, + // width: 4, + // styles: const PosStyles(align: PosAlign.right), + // ), + // ]); + + // bytes += generator.row([ + // PosColumn( + // text: 'Diskon', + // width: 8, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: order.discountAmount.currencyFormatRpV2, + // width: 4, + // styles: const PosStyles(align: PosAlign.right), + // ), + // ]); + // bytes += generator.row([ + // PosColumn( + // text: 'PPN', + // width: 8, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: order.tax.currencyFormatRpV2, + // width: 4, + // styles: const PosStyles(align: PosAlign.right), + // ), + // ]); + // bytes += generator.row([ + // PosColumn( + // text: 'Service', + // width: 8, + // styles: const PosStyles(align: PosAlign.left), + // ), + // PosColumn( + // text: order.serviceCharge.currencyFormatRpV2, + // width: 4, + // styles: const PosStyles(align: PosAlign.right), + // ), + // ]); + + bytes += generator.row([ + PosColumn( + text: 'Total Tagihan', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: (products[0].product.price!.toIntegerFromText * + products[0].quantity) + .currencyFormatRp, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.row([ + PosColumn( + text: 'Metode Pembayaran', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'Tunai', + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Total Bayar', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: (products[0].product.price!.toIntegerFromText * + products[0].quantity) + .currencyFormatRp, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Kembalian', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'Rp 0', + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.text( + paper == 80 + ? '================================================' + : '================================', + styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('Password: fic11jilid2', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.feed(1); + // bytes += generator.text('instagram: @codewithbahri', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(1); + bytes += generator.text( + 'Terbayar: ${DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now())}', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.text('dicetak oleh: Susan', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(1); + bytes += generator.text('Terima kasih', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(3); + bytes += generator.cut(); + return bytes; + } + + Future> printOrderV3( + List products, + int totalQuantity, + int totalPrice, + String paymentMethod, + int nominalBayar, + int kembalian, + int subTotal, + int discount, + int pajak, + int serviceCharge, + String namaKasir, + String customerName, + int paper, + {int taxPercentage = 11, int serviceChargePercentage = 5} + ) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + bytes += generator.reset(); + + bytes += generator.text('Guapatlu Khas Bakmi Jambi', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size1, + width: PosTextSize.size1, + )); + + bytes += generator.text('Gading Boulevard w2, No 25, Jakarta', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.text('085-77777-3839', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + bytes += generator.row([ + PosColumn( + text: DateFormat('dd MMM yyyy').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: DateFormat('HH:mm').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Receipt Number', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Order ID', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: Random().nextInt(100000).toString(), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Bill Name', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: customerName, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Collected By', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: namaKasir, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Pembayaran', + width: 8, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: paymentMethod, + width: 4, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.text('Dine In', + styles: const PosStyles(bold: true, align: PosAlign.center)); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + for (final product in products) { + bytes += generator.row([ + PosColumn( + text: '${product.quantity} x ${product.product.name}', + width: 8, + styles: const PosStyles(bold: true, align: PosAlign.left), + ), + PosColumn( + text: '${product.product.price!.toIntegerFromText * product.quantity}' + .currencyFormatRpV2, + width: 4, + styles: const PosStyles(bold: true, align: PosAlign.right), + ), + ]); + } + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + final subTotalPrice = products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price!.toIntegerFromText * element.quantity)); + bytes += generator.row([ + PosColumn( + text: 'Subtotal $totalQuantity Product', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: subTotalPrice.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + bytes += generator.row([ + PosColumn( + text: 'Discount', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: discount.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + + // Only show tax if it's greater than 0 + if (pajak > 0) { + bytes += generator.row([ + PosColumn( + text: 'Tax PB1 ($taxPercentage%)', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: pajak.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + } + + // Only show service charge if it's greater than 0 + if (serviceCharge > 0) { + bytes += generator.row([ + PosColumn( + text: 'Service Charge($serviceChargePercentage%)', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: serviceCharge.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + } + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.row([ + PosColumn( + text: 'Total', + width: 6, + styles: const PosStyles(bold: true, align: PosAlign.left), + ), + PosColumn( + text: '$totalPrice'.currencyFormatRpV2, + width: 6, + styles: const PosStyles(bold: true, align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Dibayar', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: nominalBayar.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Kembali', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: kembalian.currencyFormatRpV2, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('Notes', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + // bytes += generator.text('Pass Wifi: fic14jilid2', + // styles: const PosStyles(bold: false, align: PosAlign.center)); + // //terima kasih + // bytes += generator.text('Terima Kasih', + // styles: const PosStyles(bold: true, align: PosAlign.center)); + paper == 80 ? bytes += generator.feed(3) : bytes += generator.feed(1); + bytes += generator.cut(); + return bytes; + } + + Future> printQRIS( + int totalPrice, Uint8List imageQris, int paper) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + final img.Image? orginalImage = img.decodeImage(imageQris); + bytes += generator.reset(); + + // final Uint8List bytesData = data.buffer.asUint8List(); + // final img.Image? orginalImage = img.decodeImage(bytesData); + // bytes += generator.reset(); + + bytes += generator.text('Scan QRIS Below for Payment', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(2); + if (orginalImage != null) { + final img.Image grayscalledImage = img.grayscale(orginalImage); + final img.Image resizedImage = + img.copyResize(grayscalledImage, width: 240); + bytes += generator.imageRaster(resizedImage, align: PosAlign.center); + bytes += generator.feed(1); + } + + bytes += generator.text('Price : ${totalPrice.currencyFormatRp}', + styles: const PosStyles(bold: false, align: PosAlign.center)); + + bytes += generator.feed(4); + bytes += generator.cut(); + + return bytes; + } + + Future> printChecker(List products, + String tableName, String draftName, String cashierName, int paper, String orderType) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + bytes += generator.reset(); + + bytes += generator.text('Table Checker', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + bytes += generator.text(tableName, + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + + bytes += generator.row([ + PosColumn( + text: 'Date', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + // bytes += generator.text( + // 'Date: ${DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now())}', + // styles: const PosStyles(bold: false, align: PosAlign.left)); + //reciept number + bytes += generator.row([ + PosColumn( + text: 'Receipt', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + // bytes += generator.text( + // 'Receipt: JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', + // styles: const PosStyles(bold: false, align: PosAlign.left)); +//cashier name + bytes += generator.row([ + PosColumn( + text: 'Cashier', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: cashierName, + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + // bytes += generator.text('Cashier: $cashierName', + // styles: const PosStyles(bold: false, align: PosAlign.left)); + //customer name + //column 2 + bytes += generator.row([ + PosColumn( + text: 'Customer - $draftName', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: orderType, + width: 6, + styles: const PosStyles(align: PosAlign.right, bold: true), + ), + ]); + + //---- + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(1); + for (final product in products) { + bytes += generator.text('${product.quantity} x ${product.product.name}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size2, + width: PosTextSize.size1, + )); + if (product.notes.isNotEmpty) { + bytes += generator.text(' Notes: ${product.notes}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size1, + width: PosTextSize.size1, + fontType: PosFontType.fontA, + )); + } + } + + bytes += generator.feed(1); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + paper == 80 ? bytes += generator.feed(3) : bytes += generator.feed(1); + //cut + if (paper == 80) { + bytes += generator.cut(); + } + + return bytes; + } + + Future> printKitchen(List products, + String tableNumber, String draftName, String cashierName, int paper, String orderType) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + bytes += generator.reset(); + + bytes += generator.text('Table Kitchen', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + if (tableNumber.isNotEmpty) { + bytes += generator.text(tableNumber, + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + } + + bytes += generator.row([ + PosColumn( + text: 'Date', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + // bytes += generator.text( + // 'Date: ${DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now())}', + // styles: const PosStyles(bold: false, align: PosAlign.left)); + //reciept number + bytes += generator.row([ + PosColumn( + text: 'Receipt', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Customer - $draftName', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: orderType, + width: 6, + styles: const PosStyles(align: PosAlign.right, bold: true), + ), + ]); + + //---- + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(1); + final kitchenProducts = + products.where((p) => p.product.printerType == 'kitchen'); + for (final product in kitchenProducts) { + bytes += generator.text('${product.quantity} x ${product.product.name}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size2, + width: PosTextSize.size1, + )); + if (product.notes.isNotEmpty) { + bytes += generator.text(' Notes: ${product.notes}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size1, + width: PosTextSize.size1, + fontType: PosFontType.fontA, + )); + } + } + + bytes += generator.feed(1); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + paper == 80 ? bytes += generator.feed(3) : bytes += generator.feed(1); + //cut + if (paper == 80) { + bytes += generator.cut(); + } + + return bytes; + } + + Future> printBar(List products, String tableNumber, + String draftName, String cashierName, int paper, String orderType) async { + List bytes = []; + + final profile = await CapabilityProfile.load(); + final generator = + Generator(paper == 58 ? PaperSize.mm58 : PaperSize.mm80, profile); + + bytes += generator.reset(); + + bytes += generator.text('Table Bar', + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + if (tableNumber.isNotEmpty) { + bytes += generator.text(tableNumber.toString(), + styles: const PosStyles( + bold: true, + align: PosAlign.center, + height: PosTextSize.size2, + width: PosTextSize.size2, + )); + bytes += generator.feed(1); + } + + bytes += generator.row([ + PosColumn( + text: 'Date', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now()), + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + // bytes += generator.text( + // 'Date: ${DateFormat('dd-MM-yyyy HH:mm').format(DateTime.now())}', + // styles: const PosStyles(bold: false, align: PosAlign.left)); + //reciept number + bytes += generator.row([ + PosColumn( + text: 'Receipt', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: 'JF-${DateFormat('yyyyMMddhhmm').format(DateTime.now())}', + width: 6, + styles: const PosStyles(align: PosAlign.right), + ), + ]); + bytes += generator.row([ + PosColumn( + text: 'Customer - $draftName', + width: 6, + styles: const PosStyles(align: PosAlign.left), + ), + PosColumn( + text: orderType, + width: 6, + styles: const PosStyles(align: PosAlign.right, bold: true), + ), + ]); + + //---- + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + bytes += generator.feed(1); + final barProducts = products.where((p) => p.product.printerType == 'bar'); + for (final product in barProducts) { + bytes += generator.text('${product.quantity} x ${product.product.name}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size2, + width: PosTextSize.size1, + )); + if (product.notes.isNotEmpty) { + bytes += generator.text(' Notes: ${product.notes}', + styles: const PosStyles( + align: PosAlign.left, + bold: false, + height: PosTextSize.size1, + width: PosTextSize.size1, + fontType: PosFontType.fontA, + )); + } + } + + bytes += generator.feed(1); + bytes += generator.text( + paper == 80 + ? '------------------------------------------------' + : '--------------------------------', + styles: const PosStyles(bold: false, align: PosAlign.center)); + paper == 80 ? bytes += generator.feed(3) : bytes += generator.feed(1); + //cut + if (paper == 80) { + bytes += generator.cut(); + } + + return bytes; + } +} diff --git a/lib/data/datasources/auth_local_datasource.dart b/lib/data/datasources/auth_local_datasource.dart new file mode 100644 index 0000000..bf123d4 --- /dev/null +++ b/lib/data/datasources/auth_local_datasource.dart @@ -0,0 +1,51 @@ +import 'package:enaklo_pos/data/models/response/auth_response_model.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class AuthLocalDataSource { + Future saveAuthData(AuthResponseModel authResponseModel) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('auth_data', authResponseModel.toJson()); + } + + Future removeAuthData() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('auth_data'); + } + + Future getAuthData() async { + final prefs = await SharedPreferences.getInstance(); + final authData = prefs.getString('auth_data'); + + return AuthResponseModel.fromJson(authData!); + } + + Future isAuthDataExists() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.containsKey('auth_data'); + } + + Future saveMidtransServerKey(String serverKey) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('server_key', serverKey); + } + + //get midtrans server key + Future getMitransServerKey() async { + final prefs = await SharedPreferences.getInstance(); + final serverKey = prefs.getString('server_key'); + return serverKey ?? ''; + } + + // save size receipt + Future saveSizeReceipt(String sizeReceipt) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('size_receipt', sizeReceipt); + } + + // get size receipt + Future getSizeReceipt() async { + final prefs = await SharedPreferences.getInstance(); + final sizeReceipt = prefs.getString('size_receipt'); + return sizeReceipt ?? ''; + } +} diff --git a/lib/data/datasources/auth_remote_datasource.dart b/lib/data/datasources/auth_remote_datasource.dart new file mode 100644 index 0000000..5f34461 --- /dev/null +++ b/lib/data/datasources/auth_remote_datasource.dart @@ -0,0 +1,44 @@ +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/auth_response_model.dart'; +import 'package:http/http.dart' as http; + +class AuthRemoteDatasource { + Future> login( + String email, String password) async { + final url = Uri.parse('${Variables.baseUrl}/api/login'); + final response = await http.post( + url, + body: { + 'email': email, + 'password': password, + }, + ); + + if (response.statusCode == 200) { + return Right(AuthResponseModel.fromJson(response.body)); + } else { + return const Left('Failed to login'); + } + } + + //logout + Future> logout() async { + final authData = await AuthLocalDataSource().getAuthData(); + final url = Uri.parse('${Variables.baseUrl}/api/logout'); + final response = await http.post( + url, + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }, + ); + + if (response.statusCode == 200) { + return const Right(true); + } else { + return const Left('Failed to logout'); + } + } +} diff --git a/lib/data/datasources/category_remote_datasource.dart b/lib/data/datasources/category_remote_datasource.dart new file mode 100644 index 0000000..d81071a --- /dev/null +++ b/lib/data/datasources/category_remote_datasource.dart @@ -0,0 +1,27 @@ +import 'dart:developer'; + +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/category_response_model.dart'; +import 'package:http/http.dart' as http; + +class CategoryRemoteDatasource { + Future> getCategories() async { + final authData = await AuthLocalDataSource().getAuthData(); + final Map headers = { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }; + final response = await http.get( + Uri.parse('${Variables.baseUrl}/api/api-categories'), + headers: headers); + log(response.statusCode.toString()); + log(response.body); + if (response.statusCode == 200) { + return right(CategroyResponseModel.fromJson(response.body)); + } else { + return left(response.body); + } + } +} diff --git a/lib/data/datasources/discount_remote_datasource.dart b/lib/data/datasources/discount_remote_datasource.dart new file mode 100644 index 0000000..c099851 --- /dev/null +++ b/lib/data/datasources/discount_remote_datasource.dart @@ -0,0 +1,46 @@ +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/discount_response_model.dart'; +import 'package:http/http.dart' as http; + +class DiscountRemoteDatasource { + Future> getDiscounts() async { + final url = Uri.parse('${Variables.baseUrl}/api/api-discounts'); + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get(url, headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }); + + if (response.statusCode == 200) { + return Right(DiscountResponseModel.fromJson(response.body)); + } else { + return const Left('Failed to get discounts'); + } + } + + Future> addDiscount( + String name, + String description, + int value, + ) async { + final url = Uri.parse('${Variables.baseUrl}/api/api-discounts'); + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.post(url, headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }, body: { + 'name': name, + 'description': description, + 'value': value.toString(), + 'type': 'percentage', + }); + + if (response.statusCode == 201) { + return const Right(true); + } else { + return const Left('Failed to add discount'); + } + } +} diff --git a/lib/data/datasources/midtrans_remote_datasource.dart b/lib/data/datasources/midtrans_remote_datasource.dart new file mode 100644 index 0000000..0b06d7f --- /dev/null +++ b/lib/data/datasources/midtrans_remote_datasource.dart @@ -0,0 +1,73 @@ +import 'dart:convert'; +import 'dart:developer'; + +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/qris_response_model.dart'; +import 'package:enaklo_pos/data/models/response/qris_status_response_model.dart'; +import 'package:http/http.dart' as http; + +class MidtransRemoteDatasource { + String generateBasicAuthHeader(String serverKey) { + final base64Credentials = base64Encode(utf8.encode('$serverKey:')); + final authHeader = 'Basic $base64Credentials'; + + return authHeader; + } + + Future generateQRCode( + String orderId, int grossAmount) async { + final serverKey = await AuthLocalDataSource().getMitransServerKey(); + final headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Authorization': generateBasicAuthHeader(serverKey), + }; + + final body = jsonEncode({ + 'payment_type': 'gopay', + 'transaction_details': { + 'gross_amount': grossAmount, + 'order_id': orderId, + }, + }); + + final response = await http.post( + Uri.parse('https://api.midtrans.com/v2/charge'), + // Uri.parse('https://api.sandbox.midtrans.com/v2/charge'), + + headers: headers, + body: body, + ); + + log("StatusCode: ${response.statusCode}"); + log("Body: ${response.body}"); + + if (response.statusCode == 200 || response.statusCode == 201) { + return QrisResponseModel.fromJson(response.body); + } else { + throw Exception('Failed to generate QR Code'); + } + } + + Future checkPaymentStatus(String orderId) async { + final serverKey = await AuthLocalDataSource().getMitransServerKey(); + final headers = { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'Authorization': generateBasicAuthHeader(serverKey), + }; + + final response = await http.get( + Uri.parse('https://api.midtrans.com/v2/$orderId/status'), + // Uri.parse('https://api.sandbox.midtrans.com/v2/$orderId/status'), + headers: headers, + ); + log("StatusCode: ${response.statusCode}"); + log("Body: ${response.body}"); + if (response.statusCode == 200 || response.statusCode == 201) { + return QrisStatusResponseModel.fromJson(response.body); + } else { + throw Exception('Failed to check payment status'); + } + } +} diff --git a/lib/data/datasources/order_item_remote_datasource.dart b/lib/data/datasources/order_item_remote_datasource.dart new file mode 100644 index 0000000..ba59afc --- /dev/null +++ b/lib/data/datasources/order_item_remote_datasource.dart @@ -0,0 +1,65 @@ +import 'dart:developer'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/item_sales_response_model.dart'; +import 'package:enaklo_pos/data/models/response/product_sales_response_model.dart'; +import 'package:http/http.dart' as http; +import 'package:dartz/dartz.dart'; + +class OrderItemRemoteDatasource { + Future> getItemSalesByRangeDate( + String stratDate, + String endDate, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse( + '${Variables.baseUrl}/api/order-item?start_date=$stratDate&end_date=$endDate'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + log("Response: ${response.statusCode}"); + log("Response: ${response.body}"); + if (response.statusCode == 200) { + return Right(ItemSalesResponseModel.fromJson(response.body)); + } else { + return const Left("Failed Load Data"); + } + } catch (e) { + log("Error: $e"); + return Left("Failed: $e"); + } + } + + Future> getProductSalesByRangeDate( + String stratDate, + String endDate, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse( + '${Variables.baseUrl}/api/order-sales?start_date=$stratDate&end_date=$endDate'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + log("Response: ${response.statusCode}"); + log("Response: ${response.body}"); + if (response.statusCode == 200) { + return Right(ProductSalesResponseModel.fromJson(response.body)); + } else { + return const Left("Failed Load Data"); + } + } catch (e) { + log("Error: $e"); + return Left("Failed: $e"); + } + } +} diff --git a/lib/data/datasources/order_remote_datasource.dart b/lib/data/datasources/order_remote_datasource.dart new file mode 100644 index 0000000..22a85d7 --- /dev/null +++ b/lib/data/datasources/order_remote_datasource.dart @@ -0,0 +1,183 @@ +import 'dart:developer'; + +import 'dart:convert'; + +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart'; +import 'package:enaklo_pos/data/models/response/summary_response_model.dart'; +import 'package:enaklo_pos/presentation/home/models/order_model.dart'; +import 'package:http/http.dart' as http; + +class OrderRemoteDatasource { + //save order to remote server + Future saveOrder(OrderModel orderModel) async { + final authData = await AuthLocalDataSource().getAuthData(); + print("🌐 API CALL: saveOrder"); + print("📡 URL: ${Variables.baseUrl}/api/save-order"); + print("🔑 Token: ${authData.token?.substring(0, 20)}..."); + try { + final response = await http.post( + Uri.parse('${Variables.baseUrl}/api/save-order'), + body: orderModel.toJson(), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + + print("📥 HTTP Status Code: ${response.statusCode}"); + print("📥 Response Body: ${response.body}"); + print("📥 Response Headers: ${response.headers}"); + + if (response.statusCode == 200) { + print("✅ API call successful - Order saved to server"); + return true; + } else { + print("❌ API call failed - Status: ${response.statusCode}"); + print("❌ Error Response: ${response.body}"); + return false; + } + } catch (e) { + print("💥 API call error: $e"); + return false; + } + } + + Future> getOrderByRangeDate( + String stratDate, + String endDate, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse( + '${Variables.baseUrl}/api/orders?start_date=$stratDate&end_date=$endDate'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + print("📥 HTTP Status Code: ${response.statusCode}"); + print("📥 Response Body: ${response.body}"); + print("📥 Response Headers: ${response.headers}"); + if (response.statusCode == 200) { + print("✅ getOrderByRangeDate API call successful"); + return Right(OrderResponseModel.fromJson(response.body)); + } else { + print("❌ getOrderByRangeDate API call failed - Status: ${response.statusCode}"); + print("❌ Error Response: ${response.body}"); + return const Left("Failed Load Data"); + } + } catch (e) { + print("💥 getOrderByRangeDate API call error: $e"); + return Left("Failed: $e"); + } + } + + Future> getSummaryByRangeDate( + String stratDate, + String endDate, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse( + '${Variables.baseUrl}/api/summary?start_date=$stratDate&end_date=$endDate'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + print("📡 URL: ${response.request!.url}"); + print("📥 HTTP Status Code: ${response.statusCode}"); + print("📥 Response Body: ${response.body}"); + print("📥 Response Headers: ${response.headers}"); + if (response.statusCode == 200) { + print("✅ getSummaryByRangeDate API call successful"); + return Right(SummaryResponseModel.fromJson(response.body)); + } else { + print("❌ getSummaryByRangeDate API call failed - Status: ${response.statusCode}"); + print("❌ Error Response: ${response.body}"); + return const Left("Failed Load Data"); + } + } catch (e) { + print("💥 getSummaryByRangeDate API call error: $e"); + return Left("Failed: $e"); + } + } + + Future> getPaymentMethodByRangeDate( + String startDate, + String endDate, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse( + '${Variables.baseUrl}/api/order-paymentmethod?start_date=$startDate&end_date=$endDate'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + ); + print("📥 Payment Method HTTP Status Code: ${response.statusCode}"); + print("📥 Payment Method Response Body: ${response.body}"); + print("📥 Payment Method Response Headers: ${response.headers}"); + if (response.statusCode == 200) { + print("✅ getPaymentMethodByRangeDate API call successful"); + return Right(PaymentMethodResponseModel.fromJson(response.body)); + } else { + print("❌ getPaymentMethodByRangeDate API call failed - Status: ${response.statusCode}"); + print("❌ Error Response: ${response.body}"); + return const Left("Failed Load Payment Method Data"); + } + } catch (e) { + print("💥 getPaymentMethodByRangeDate API call error: $e"); + return Left("Failed: $e"); + } + } + + Future> addOrderItems( + int orderId, + List> orderItems, + ) async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.post( + Uri.parse('${Variables.baseUrl}/api/orders/add-items'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + 'Content-Type': 'application/json', + }, + body: jsonEncode({ + 'order_id': orderId, + 'order_items': orderItems, + }), + ); + + print("📥 Add Order Items HTTP Status Code: ${response.statusCode}"); + print("📥 Add Order Items Response Body: ${response.body}"); + print("📥 Add Order Items Response Headers: ${response.headers}"); + + if (response.statusCode == 200) { + print("✅ addOrderItems API call successful"); + return const Right(true); + } else { + print("❌ addOrderItems API call failed - Status: ${response.statusCode}"); + print("❌ Error Response: ${response.body}"); + return Left("Failed to add order items: ${response.body}"); + } + } catch (e) { + print("💥 addOrderItems API call error: $e"); + return Left("Failed: $e"); + } + } +} diff --git a/lib/data/datasources/payment_methods_remote_datasource.dart b/lib/data/datasources/payment_methods_remote_datasource.dart new file mode 100644 index 0000000..4ca105e --- /dev/null +++ b/lib/data/datasources/payment_methods_remote_datasource.dart @@ -0,0 +1,34 @@ +import 'dart:developer'; + +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart'; +import 'package:http/http.dart' as http; + +class PaymentMethodsRemoteDatasource { + Future> getPaymentMethods() async { + try { + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get( + Uri.parse('${Variables.baseUrl}/api/payment-methods'), + headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }, + ); + + log("Payment Methods Response Status: ${response.statusCode}"); + log("Payment Methods Response Body: ${response.body}"); + + if (response.statusCode == 200) { + return Right(PaymentMethodsResponseModel.fromJson(response.body)); + } else { + return const Left('Failed to get payment methods'); + } + } catch (e) { + log("Error getting payment methods: $e"); + return Left('Error: $e'); + } + } +} \ No newline at end of file diff --git a/lib/data/datasources/product_local_datasource.dart b/lib/data/datasources/product_local_datasource.dart new file mode 100644 index 0000000..a7b63e9 --- /dev/null +++ b/lib/data/datasources/product_local_datasource.dart @@ -0,0 +1,613 @@ +import 'dart:developer'; +import 'dart:ui'; + +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/models/order_model.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart'; +import 'package:intl/intl.dart'; +import 'package:sqflite/sqflite.dart'; + +import '../../presentation/home/models/product_quantity.dart'; + +class ProductLocalDatasource { + ProductLocalDatasource._init(); + + static final ProductLocalDatasource instance = ProductLocalDatasource._init(); + + final String tableProduct = 'products'; + final String tableOrder = 'orders'; + final String tableOrderItem = 'order_items'; + final String tableManagement = 'table_management'; + final String tablePrint = 'prints'; + static Database? _database; + + // "id": 1, + // "category_id": 1, + // "name": "Mie Ayam", + // "description": "Ipsa dolorem impedit dolor. Libero nisi quidem expedita quod mollitia ad. Voluptas ut quia nemo nisi odit fuga. Fugit autem qui ratione laborum eum.", + // "image": "https://via.placeholder.com/640x480.png/002200?text=nihil", + // "price": "2000.44", + // "stock": 94, + // "status": 1, + // "is_favorite": 1, + // "created_at": "2024-02-08T14:30:22.000000Z", + // "updated_at": "2024-02-08T15:14:22.000000Z" + + Future _createDb(Database db, int version) async { + await db.execute(''' + CREATE TABLE $tableProduct ( + id INTEGER PRIMARY KEY, + product_id INTEGER, + name TEXT, + printer_type TEXT, + categoryId INTEGER, + categoryName TEXT, + description TEXT, + image TEXT, + price TEXT, + stock INTEGER, + status INTEGER, + isFavorite INTEGER, + createdAt TEXT, + updatedAt TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE $tableOrder ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + payment_amount INTEGER, + sub_total INTEGER, + tax INTEGER, + discount INTEGER, + discount_amount INTEGER, + service_charge INTEGER, + total INTEGER, + payment_method TEXT, + total_item INTEGER, + id_kasir INTEGER, + nama_kasir TEXT, + transaction_time TEXT, + table_number INTEGER, + customer_name TEXT, + status TEXT, + payment_status TEXT, + order_type TEXT DEFAULT 'DINE IN', + is_sync INTEGER DEFAULT 0 + ) + '''); + + await db.execute(''' + CREATE TABLE $tableOrderItem ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + id_order INTEGER, + id_product INTEGER, + quantity INTEGER, + price INTEGER, + notes TEXT DEFAULT '' + ) + '''); + + await db.execute(''' + CREATE TABLE $tableManagement ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + table_name Text, + start_time Text, + order_id INTEGER, + payment_amount INTEGER, + x_position REAL NOT NULL, + y_position REAL NOT NULL, + status TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE draft_orders ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + total_item INTEGER, + subtotal INTEGER, + tax INTEGER, + discount INTEGER, + discount_amount INTEGER, + service_charge INTEGER, + total INTEGER, + transaction_time TEXT, + table_number INTEGER, + draft_name TEXT + ) + '''); + + await db.execute(''' + CREATE TABLE draft_order_items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + id_draft_order INTEGER, + id_product INTEGER, + quantity INTEGER, + price INTEGER + ) + '''); + + await db.execute(''' + CREATE TABLE $tablePrint ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code TEXT, + name TEXT, + address TEXT, + paper TEXT, + type TEXT + ) + '''); + } + + Future _initDB(String filePath) async { + final dbPath = await getDatabasesPath(); + final path = dbPath + filePath; + + // Force delete existing database to ensure new schema + try { + final dbExists = await databaseExists(path); + if (dbExists) { + log("Deleting existing database to ensure new schema with order_type column"); + await deleteDatabase(path); + } + } catch (e) { + log("Error deleting database: $e"); + } + + return await openDatabase( + path, + version: 2, + onCreate: _createDb, + onUpgrade: _onUpgrade, + ); + } + + Future _onUpgrade(Database db, int oldVersion, int newVersion) async { + if (oldVersion < 2) { + // Add order_type column to orders table if it doesn't exist + try { + await db.execute('ALTER TABLE $tableOrder ADD COLUMN order_type TEXT DEFAULT "DINE IN"'); + log("Added order_type column to orders table"); + } catch (e) { + log("order_type column might already exist: $e"); + } + } + } + + Future get database async { + if (_database != null) return _database!; + _database = await _initDB('dbresto36.db'); + return _database!; + } + + //save order + Future saveOrder(OrderModel order) async { + final db = await instance.database; + + // Since we're forcing database recreation, order_type column should exist + final orderMap = order.toMap(includeOrderType: true); + log("Final orderMap for insertion: $orderMap"); + + int id = await db.insert(tableOrder, orderMap, + conflictAlgorithm: ConflictAlgorithm.replace); + + for (var item in order.orderItems) { + log("Item: ${item.toLocalMap(id)}"); + await db.insert(tableOrderItem, item.toLocalMap(id), + conflictAlgorithm: ConflictAlgorithm.replace); + } + log("Success Order: ${order.toMap()}"); + return id; + } + + //get data order + Future> getOrderByIsNotSync() async { + final db = await instance.database; + final List> maps = + await db.query(tableOrder, where: 'is_sync = ?', whereArgs: [0]); + return List.generate(maps.length, (i) { + return OrderModel.fromMap(maps[i]); + }); + } + + Future> getAllOrder( + DateTime date, + ) async { + final db = await instance.database; + //date to iso8601 + final dateIso = date.toIso8601String(); + //get yyyy-MM-dd + final dateYYYYMMDD = dateIso.substring(0, 10); + // final formattedDate = DateFormat('yyyy-MM-dd').format(date); + final List> maps = await db.query( + tableOrder, + where: 'transaction_time like ?', + whereArgs: ['$dateYYYYMMDD%'], + // where: 'transaction_time BETWEEN ? AND ?', + // whereArgs: [ + // DateFormat.yMd().format(start), + // DateFormat.yMd().format(end) + // ], + ); + return List.generate(maps.length, (i) { + log("Save save OrderModel: ${OrderModel.fromMap(maps[i])}"); + return OrderModel.fromMap(maps[i]); + }); + } + + //get order item by order id + Future> getOrderItemByOrderId(int orderId) async { + final db = await instance.database; + final List> maps = await db + .query(tableOrderItem, where: 'id_order = ?', whereArgs: [orderId]); + return List.generate(maps.length, (i) { + log("ProductQuantity: ${ProductQuantity.fromLocalMap(maps[i])}"); + return ProductQuantity.fromLocalMap(maps[i]); + }); + } + + //update payment status by order id + Future updatePaymentStatus( + int orderId, String paymentStatus, String status) async { + final db = await instance.database; + await db.update( + tableOrder, {'payment_status': paymentStatus, 'status': status}, + where: 'id = ?', whereArgs: [orderId]); + log('update payment status success | order id: $orderId | payment status: $paymentStatus | status: $status'); + } + + //update order is sync + Future updateOrderIsSync(int orderId) async { + final db = await instance.database; + await db.update(tableOrder, {'is_sync': 1}, + where: 'id = ?', whereArgs: [orderId]); + } + + //insert data product + + Future insertProduct(Product product) async { + log("Product: ${product.toMap()}"); + final db = await instance.database; + await db.insert(tableProduct, product.toMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + } + + //update product + Future updateProduct(Product product) async { + log("Update Product: ${product.toMap()}"); + final db = await instance.database; + await db.update( + tableProduct, + product.toLocalMap(), + where: 'product_id = ?', + whereArgs: [product.productId], + ); + } + + //insert list of product + Future insertProducts(List products) async { + final db = await instance.database; + log("Save Products to Local"); + for (var product in products) { + await db.insert(tableProduct, product.toLocalMap(), + conflictAlgorithm: ConflictAlgorithm.replace); + log('inserted success id: ${product.productId} | name: ${product.name} | price: ${product.price} | Printer Type ${product.printerType}'); + } + } + + //get all products + Future> getProducts() async { + final db = await instance.database; + final List> maps = await db.query(tableProduct); + return List.generate(maps.length, (i) { + return Product.fromLocalMap(maps[i]); + }); + } + + Future getProductById(int id) async { + final db = await instance.database; + final result = + await db.query(tableProduct, where: 'product_id = ?', whereArgs: [id]); + + if (result.isEmpty) { + return null; + } + + return Product.fromMap(result.first); + } + + // get Last Table Management + + Future getLastTableManagement() async { + final db = await instance.database; + final List> maps = + await db.query(tableManagement, orderBy: 'id DESC', limit: 1); + if (maps.isEmpty) { + return null; + } + return TableModel.fromMap(maps[0]); + } + + // generate table managent with count + Future createTableManagement(String tableName, Offset position) async { + final db = await instance.database; + TableModel newTable = TableModel( + tableName: tableName, + status: 'available', + orderId: 0, + paymentAmount: 0, + startTime: DateTime.now().toIso8601String(), + position: position, + ); + await db.insert( + tableManagement, + newTable.toMap(), + ); + } + + // change position table + Future changePositionTable(int id, Offset position) async { + final db = await instance.database; + await db.update( + tableManagement, + {'x_position': position.dx, 'y_position': position.dy}, + where: 'id = ?', + whereArgs: [id], + ); + } + + // update table + Future updateTable(TableModel table) async { + final db = await instance.database; + await db.update( + tableManagement, + table.toMap(), + where: 'id = ?', + whereArgs: [table.id], + ); + } + + // get all table + Future> getAllTable() async { + final db = await instance.database; + final List> maps = await db.query(tableManagement); + log("Table Management: $maps"); + return List.generate(maps.length, (i) { + return TableModel.fromMap(maps[i]); + }); + } + + // get last order where table number + Future getLastOrderTable(int tableNumber) async { + final db = await instance.database; + final List> maps = await db.query( + tableOrder, + where: 'table_number = ?', + whereArgs: [tableNumber], + orderBy: 'id DESC', // Urutkan berdasarkan id dari yang terbesar (terbaru) + limit: 1, // Ambil hanya satu data terakhir + ); + + if (maps.isEmpty) { + return null; + } + + return OrderModel.fromMap(maps[0]); + } + + // get table by status + Future> getTableByStatus(String status) async { + final db = await instance.database; + List> maps; + + if (status == 'all') { + // Get all tables + maps = await db.query(tableManagement); + log("Getting all tables, found: ${maps.length}"); + + // If no tables exist, create some default tables + if (maps.isEmpty) { + log("No tables found, creating default tables..."); + await _createDefaultTables(); + maps = await db.query(tableManagement); + log("After creating default tables, found: ${maps.length}"); + } + } else { + // Get tables by specific status + maps = await db.query( + tableManagement, + where: 'status = ?', + whereArgs: [status], + ); + log("Getting tables with status '$status', found: ${maps.length}"); + } + + final tables = List.generate(maps.length, (i) { + return TableModel.fromMap(maps[i]); + }); + + log("Returning ${tables.length} tables"); + tables.forEach((table) { + log("Table: ${table.tableName} (ID: ${table.id}, Status: ${table.status})"); + }); + + return tables; + } + + // Create default tables if none exist + Future _createDefaultTables() async { + final db = await instance.database; + + // Create 5 default tables + for (int i = 1; i <= 5; i++) { + await db.insert(tableManagement, { + 'table_name': 'Table $i', + 'start_time': DateTime.now().toIso8601String(), + 'order_id': 0, + 'payment_amount': 0, + 'x_position': 100.0 + (i * 50.0), + 'y_position': 100.0 + (i * 50.0), + 'status': 'available', + }); + log("Created default table: Table $i"); + } + } + + // update status tabel + Future updateStatusTable(TableModel table) async { + log("Updating table status: ${table.toMap()}"); + final db = await instance.database; + await db.update(tableManagement, table.toMap(), + where: 'id = ?', whereArgs: [table.id]); + log("Success Update Status Table: ${table.toMap()}"); + + // Verify the update + final updatedTable = await db.query( + tableManagement, + where: 'id = ?', + whereArgs: [table.id], + ); + if (updatedTable.isNotEmpty) { + log("Verified table update: ${updatedTable.first}"); + } + } + + // Debug method to reset all tables to available status + Future resetAllTablesToAvailable() async { + log("Resetting all tables to available status..."); + final db = await instance.database; + await db.update( + tableManagement, + { + 'status': 'available', + 'order_id': 0, + 'payment_amount': 0, + 'start_time': DateTime.now().toIso8601String(), + }, + ); + log("All tables reset to available status"); + } + + //delete all products + Future deleteAllProducts() async { + final db = await instance.database; + await db.delete(tableProduct); + } + + Future saveDraftOrder(DraftOrderModel order) async { + log("save draft order: ${order.toMapForLocal()}"); + final db = await instance.database; + int id = await db.insert('draft_orders', order.toMapForLocal()); + log("draft order id: $id | ${order.discountAmount}"); + for (var orderItem in order.orders) { + await db.insert('draft_order_items', orderItem.toMapForLocal(id)); + log("draft order item ${orderItem.toMapForLocal(id)}"); + } + + return id; + } + + //get all draft order + Future> getAllDraftOrder() async { + final db = await instance.database; + final result = await db.query('draft_orders', orderBy: 'id ASC'); + + List results = await Future.wait(result.map((item) async { + // Your asynchronous operation here + final draftOrderItem = + await getDraftOrderItemByOrderId(item['id'] as int); + return DraftOrderModel.newFromLocalMap(item, draftOrderItem); + })); + return results; + } + + // get Darft Order by id + Future getDraftOrderById(int id) async { + final db = await instance.database; + final result = + await db.query('draft_orders', where: 'id = ?', whereArgs: [id]); + if (result.isEmpty) { + return null; + } + final draftOrderItem = + await getDraftOrderItemByOrderId(result.first['id'] as int); + log("draft order item: $draftOrderItem | ${result.first.toString()}"); + return DraftOrderModel.newFromLocalMap(result.first, draftOrderItem); + } + + //get draft order item by id order + Future> getDraftOrderItemByOrderId(int idOrder) async { + final db = await instance.database; + final result = + await db.query('draft_order_items', where: 'id_draft_order = $idOrder'); + + List results = await Future.wait(result.map((item) async { + // Your asynchronous operation here + final product = await getProductById(item['id_product'] as int); + return DraftOrderItem( + product: product!, quantity: item['quantity'] as int); + })); + return results; + } + + //remove draft order by id + Future removeDraftOrderById(int id) async { + final db = await instance.database; + await db.delete('draft_orders', where: 'id = ?', whereArgs: [id]); + await db.delete('draft_order_items', + where: 'id_draft_order = ?', whereArgs: [id]); + } + + //update draft order + Future updateDraftOrder(DraftOrderModel draftOrder) async { + final db = await instance.database; + + // Update the draft order + await db.update( + 'draft_orders', + draftOrder.toMapForLocal(), + where: 'id = ?', + whereArgs: [draftOrder.id], + ); + + // Remove existing items and add new ones + await db.delete('draft_order_items', + where: 'id_draft_order = ?', whereArgs: [draftOrder.id]); + + for (var orderItem in draftOrder.orders) { + await db.insert('draft_order_items', orderItem.toMapForLocal(draftOrder.id!)); + } + } + + /// create printer + Future createPrinter(PrintModel print) async { + final db = await instance.database; + await db.insert(tablePrint, print.toMap()); + } + + Future updatePrinter(PrintModel print, int id) async { + final db = await instance.database; + log("Update Printer: ${print.toMap()} | id: $id"); + await db + .update(tablePrint, print.toMap(), where: 'id = ?', whereArgs: [id]); + } + + Future deletePrinter(int id) async { + final db = await instance.database; + await db.delete(tablePrint, where: 'id = ?', whereArgs: [id]); + } + + // get printer by code + Future getPrinterByCode(String code) async { + final db = await instance.database; + final result = + await db.query(tablePrint, where: 'code = ?', whereArgs: [code]); + if (result.isEmpty) { + return null; + } + return PrintModel.fromMap(result.first); + } +} diff --git a/lib/data/datasources/product_remote_datasource.dart b/lib/data/datasources/product_remote_datasource.dart new file mode 100644 index 0000000..dfc543d --- /dev/null +++ b/lib/data/datasources/product_remote_datasource.dart @@ -0,0 +1,94 @@ +import 'dart:developer'; + +import 'package:dartz/dartz.dart'; +import 'package:enaklo_pos/data/models/request/product_request_model.dart'; +import 'package:enaklo_pos/data/models/response/add_product_response_model.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:http/http.dart' as http; + +import '../../core/constants/variables.dart'; +import 'auth_local_datasource.dart'; + +class ProductRemoteDatasource { + Future> getProducts() async { + final url = Uri.parse('${Variables.baseUrl}/api/products'); + final authData = await AuthLocalDataSource().getAuthData(); + final response = await http.get(url, headers: { + 'Authorization': 'Bearer ${authData.token}', + 'Accept': 'application/json', + }); + log("Status Code: ${response.statusCode}"); + log("Body: ${response.body}"); + if (response.statusCode == 200) { + return Right(ProductResponseModel.fromJson(response.body)); + } else { + return const Left('Failed to get products'); + } + } + + Future> addProduct( + ProductRequestModel productRequestModel) async { + final authData = await AuthLocalDataSource().getAuthData(); + final Map headers = { + 'Authorization': 'Bearer ${authData.token}', + }; + var request = http.MultipartRequest( + 'POST', Uri.parse('${Variables.baseUrl}/api/products')); + request.fields.addAll(productRequestModel.toMap()); + request.files.add(await http.MultipartFile.fromPath( + 'image', productRequestModel.image!.path)); + request.headers.addAll(headers); + + http.StreamedResponse response = await request.send(); + + final String body = await response.stream.bytesToString(); + log(response.stream.toString()); + log(response.statusCode.toString()); + if (response.statusCode == 201) { + return right(AddProductResponseModel.fromJson(body)); + } else { + return left(body); + } + } + + Future> updateProduct( + ProductRequestModel productRequestModel) async { + final authData = await AuthLocalDataSource().getAuthData(); + final Map headers = { + 'Authorization': 'Bearer ${authData.token}', + }; + + log("Update Product Request Data: ${productRequestModel.toMap()}"); + log("Update Product ID: ${productRequestModel.id}"); + log("Update Product Name: ${productRequestModel.name}"); + log("Update Product Price: ${productRequestModel.price}"); + log("Update Product Stock: ${productRequestModel.stock}"); + log("Update Product Category ID: ${productRequestModel.categoryId}"); + log("Update Product Is Best Seller: ${productRequestModel.isBestSeller}"); + log("Update Product Printer Type: ${productRequestModel.printerType}"); + log("Update Product Has Image: ${productRequestModel.image != null}"); + + var request = http.MultipartRequest( + 'POST', Uri.parse('${Variables.baseUrl}/api/products/edit')); + request.fields.addAll(productRequestModel.toMap()); + if (productRequestModel.image != null) { + request.files.add(await http.MultipartFile.fromPath( + 'image', productRequestModel.image!.path)); + } + request.headers.addAll(headers); + + log("Update Product Request Fields: ${request.fields}"); + log("Update Product Request Files: ${request.files.length}"); + + http.StreamedResponse response = await request.send(); + + final String body = await response.stream.bytesToString(); + log("Update Product Status Code: ${response.statusCode}"); + log("Update Product Body: $body"); + if (response.statusCode == 200) { + return right(AddProductResponseModel.fromJson(body)); + } else { + return left(body); + } + } +} diff --git a/lib/data/datasources/settings_local_datasource.dart b/lib/data/datasources/settings_local_datasource.dart new file mode 100644 index 0000000..3ff7fed --- /dev/null +++ b/lib/data/datasources/settings_local_datasource.dart @@ -0,0 +1,38 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../presentation/setting/models/tax_model.dart'; + +class SettingsLocalDatasource { + // save tax to shared preferences + Future saveTax(TaxModel taxModel) async { + final prefs = await SharedPreferences.getInstance(); + return prefs.setString('tax', taxModel.toJson()); + } + + // get tax from shared preferences + Future getTax() async { + final prefs = await SharedPreferences.getInstance(); + final tax = prefs.getString('tax'); + if (tax != null) { + return TaxModel.fromJson(tax); + } else { + return TaxModel( + name: 'Tax', + type: TaxType.pajak, + value: 11, + ); + } + } + + // save service charge to shared preferences + Future saveServiceCharge(int serviceCharge) async { + final prefs = await SharedPreferences.getInstance(); + return prefs.setInt('serviceCharge', serviceCharge); + } + + // get service charge from shared preferences + Future getServiceCharge() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getInt('serviceCharge') ?? 0; + } +} diff --git a/lib/data/models/request/product_request_model.dart b/lib/data/models/request/product_request_model.dart new file mode 100644 index 0000000..1ea57dd --- /dev/null +++ b/lib/data/models/request/product_request_model.dart @@ -0,0 +1,42 @@ +import 'dart:developer'; + +import 'package:image_picker/image_picker.dart'; + +class ProductRequestModel { + final int? id; + final String name; + final int price; + final int stock; + final int categoryId; + final int isBestSeller; + final XFile? image; + final String? printerType; + ProductRequestModel({ + this.id, + required this.name, + required this.price, + required this.stock, + required this.categoryId, + required this.isBestSeller, + this.image, + this.printerType, + }); + + Map toMap() { + log("toMap: $isBestSeller"); + final map = { + 'name': name, + 'price': price.toString(), + 'stock': stock.toString(), + 'category_id': categoryId.toString(), + 'is_best_seller': isBestSeller.toString(), + 'printer_type': printerType ?? '', + }; + + if (id != null) { + map['id'] = id.toString(); + } + + return map; + } +} diff --git a/lib/data/models/response/add_product_response_model.dart b/lib/data/models/response/add_product_response_model.dart new file mode 100644 index 0000000..99e8af9 --- /dev/null +++ b/lib/data/models/response/add_product_response_model.dart @@ -0,0 +1,33 @@ +import 'dart:convert'; + +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +class AddProductResponseModel { + final bool success; + final String message; + final Product data; + + AddProductResponseModel({ + required this.success, + required this.message, + required this.data, + }); + + factory AddProductResponseModel.fromJson(String str) => + AddProductResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory AddProductResponseModel.fromMap(Map json) => + AddProductResponseModel( + success: json["success"], + message: json["message"], + data: Product.fromMap(json["data"]), + ); + + Map toMap() => { + "success": success, + "message": message, + "data": data.toMap(), + }; +} diff --git a/lib/data/models/response/auth_response_model.dart b/lib/data/models/response/auth_response_model.dart new file mode 100644 index 0000000..56eb5f6 --- /dev/null +++ b/lib/data/models/response/auth_response_model.dart @@ -0,0 +1,85 @@ +import 'dart:convert'; + +class AuthResponseModel { + final String? status; + final String? token; + final User? user; + + AuthResponseModel({ + this.status, + this.token, + this.user, + }); + + factory AuthResponseModel.fromJson(String str) => AuthResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory AuthResponseModel.fromMap(Map json) => AuthResponseModel( + status: json["status"], + token: json["token"], + user: json["user"] == null ? null : User.fromMap(json["user"]), + ); + + Map toMap() => { + "status": status, + "token": token, + "user": user?.toMap(), + }; +} + +class User { + final int? id; + final String? name; + final String? email; + final DateTime? emailVerifiedAt; + final dynamic twoFactorSecret; + final dynamic twoFactorRecoveryCodes; + final dynamic twoFactorConfirmedAt; + final DateTime? createdAt; + final DateTime? updatedAt; + final String? role; + + User({ + this.id, + this.name, + this.email, + this.emailVerifiedAt, + this.twoFactorSecret, + this.twoFactorRecoveryCodes, + this.twoFactorConfirmedAt, + this.createdAt, + this.updatedAt, + this.role, + }); + + factory User.fromJson(String str) => User.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory User.fromMap(Map json) => User( + id: json["id"], + name: json["name"], + email: json["email"], + emailVerifiedAt: json["email_verified_at"] == null ? null : DateTime.parse(json["email_verified_at"]), + twoFactorSecret: json["two_factor_secret"], + twoFactorRecoveryCodes: json["two_factor_recovery_codes"], + twoFactorConfirmedAt: json["two_factor_confirmed_at"], + createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]), + role: json["role"], + ); + + Map toMap() => { + "id": id, + "name": name, + "email": email, + "email_verified_at": emailVerifiedAt?.toIso8601String(), + "two_factor_secret": twoFactorSecret, + "two_factor_recovery_codes": twoFactorRecoveryCodes, + "two_factor_confirmed_at": twoFactorConfirmedAt, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "role": role, + }; +} diff --git a/lib/data/models/response/category_response_model.dart b/lib/data/models/response/category_response_model.dart new file mode 100644 index 0000000..d50ea51 --- /dev/null +++ b/lib/data/models/response/category_response_model.dart @@ -0,0 +1,91 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:convert'; + +class CategroyResponseModel { + final String status; + final List data; + + CategroyResponseModel({ + required this.status, + required this.data, + }); + + Map toMap() { + return { + 'status': status, + 'data': data.map((x) => x.toMap()).toList(), + }; + } + + factory CategroyResponseModel.fromMap(Map map) { + return CategroyResponseModel( + status: map['status'] as String, + data: List.from( + (map['data']).map( + (x) => CategoryModel.fromMap(x as Map), + ), + ), + ); + } + + factory CategroyResponseModel.fromJson(String str) => + CategroyResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); +} + +class CategoryModel { + int? id; + String? name; + int? categoryId; + int? isSync; + String? image; + // DateTime createdAt; + // DateTime updatedAt; + + CategoryModel({this.id, this.name, this.categoryId, this.isSync, this.image}); + + Map toMap() { + return { + // 'id': id, + 'name': name, + 'is_sync': isSync ?? 1, + 'category_id': id, + 'image': image + }; + } + + factory CategoryModel.fromMap(Map map) { + return CategoryModel( + id: map['id'] as int?, + name: map['name'] as String?, + isSync: map['is_sync'] as int?, + categoryId: map['id'], + image: map['image']); + } + + factory CategoryModel.fromJson(String str) => + CategoryModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + @override + bool operator ==(covariant CategoryModel other) { + if (identical(this, other)) return true; + + return other.id == id && + other.name == name && + other.categoryId == categoryId && + other.isSync == isSync && + other.image == image; + } + + @override + int get hashCode { + return id.hashCode ^ + name.hashCode ^ + categoryId.hashCode ^ + isSync.hashCode ^ + image.hashCode; + } +} diff --git a/lib/data/models/response/discount_response_model.dart b/lib/data/models/response/discount_response_model.dart new file mode 100644 index 0000000..0020132 --- /dev/null +++ b/lib/data/models/response/discount_response_model.dart @@ -0,0 +1,90 @@ +import 'dart:convert'; + +class DiscountResponseModel { + final String? status; + final List? data; + + DiscountResponseModel({ + this.status, + this.data, + }); + + factory DiscountResponseModel.fromJson(String str) => + DiscountResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory DiscountResponseModel.fromMap(Map json) => + DiscountResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => Discount.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": + data == null ? [] : List.from(data!.map((x) => x.toMap())), + }; +} + +class Discount { + final int? id; + final String? name; + final String? description; + final String? type; + final String? value; + final String? status; + final DateTime? expiredDate; + final DateTime? createdAt; + final DateTime? updatedAt; + + Discount({ + this.id, + this.name, + this.description, + this.type, + this.value, + this.status, + this.expiredDate, + this.createdAt, + this.updatedAt, + }); + + factory Discount.fromJson(String str) => Discount.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory Discount.fromMap(Map json) => Discount( + id: json["id"], + name: json["name"], + description: json["description"], + type: json["type"], + value: json["value"], + status: json["status"], + expiredDate: json["expired_date"] == null + ? null + : DateTime.parse(json["expired_date"]), + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + ); + + Map toMap() => { + "id": id, + "name": name, + "description": description, + "type": type, + "value": value, + "status": status, + "expired_date": + "${expiredDate!.year.toString().padLeft(4, '0')}-${expiredDate!.month.toString().padLeft(2, '0')}-${expiredDate!.day.toString().padLeft(2, '0')}", + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + }; +} diff --git a/lib/data/models/response/item_sales_response_model.dart b/lib/data/models/response/item_sales_response_model.dart new file mode 100644 index 0000000..ebaf285 --- /dev/null +++ b/lib/data/models/response/item_sales_response_model.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +class ItemSalesResponseModel { + String? status; + List? data; + + ItemSalesResponseModel({ + this.status, + this.data, + }); + + factory ItemSalesResponseModel.fromJson(String str) => + ItemSalesResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ItemSalesResponseModel.fromMap(Map json) => + ItemSalesResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => ItemSales.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": + data == null ? [] : List.from(data!.map((x) => x.toMap())), + }; +} + +class ItemSales { + int? id; + int? orderId; + int? productId; + int? quantity; + int? price; + DateTime? createdAt; + DateTime? updatedAt; + String? productName; + + ItemSales({ + this.id, + this.orderId, + this.productId, + this.quantity, + this.price, + this.createdAt, + this.updatedAt, + this.productName, + }); + + factory ItemSales.fromJson(String str) => ItemSales.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ItemSales.fromMap(Map json) => ItemSales( + id: json["id"], + orderId: json["order_id"], + productId: json["product_id"], + quantity: json["quantity"], + price: json["price"], + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + productName: json["product_name"]!, + ); + + Map toMap() => { + "id": id, + "order_id": orderId, + "product_id": productId, + "quantity": quantity, + "price": price, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "product_name": productName, + }; +} diff --git a/lib/data/models/response/order_remote_datasource.dart b/lib/data/models/response/order_remote_datasource.dart new file mode 100644 index 0000000..411da5d --- /dev/null +++ b/lib/data/models/response/order_remote_datasource.dart @@ -0,0 +1,113 @@ +import 'dart:convert'; + +class OrderResponseModel { + String? status; + List? data; + + OrderResponseModel({ + this.status, + this.data, + }); + + factory OrderResponseModel.fromJson(String str) => + OrderResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory OrderResponseModel.fromMap(Map json) => + OrderResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => ItemOrder.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": + data == null ? [] : List.from(data!.map((x) => x.toMap())), + }; +} + +class ItemOrder { + int? id; + int? paymentAmount; + int? subTotal; + int? tax; + int? discount; + String? discountAmount; + int? serviceCharge; + int? total; + String? paymentMethod; + int? totalItem; + int? idKasir; + String? namaKasir; + DateTime? transactionTime; + DateTime? createdAt; + DateTime? updatedAt; + + ItemOrder({ + this.id, + this.paymentAmount, + this.subTotal, + this.tax, + this.discount, + this.discountAmount, + this.serviceCharge, + this.total, + this.paymentMethod, + this.totalItem, + this.idKasir, + this.namaKasir, + this.transactionTime, + this.createdAt, + this.updatedAt, + }); + + factory ItemOrder.fromJson(String str) => ItemOrder.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ItemOrder.fromMap(Map json) => ItemOrder( + id: json["id"], + paymentAmount: json["payment_amount"], + subTotal: json["sub_total"], + tax: json["tax"], + discount: json["discount"], + discountAmount: json["discount_amount"], + serviceCharge: json["service_charge"], + total: json["total"], + paymentMethod: json["payment_method"]!, + totalItem: json["total_item"], + idKasir: json["id_kasir"], + namaKasir: json["nama_kasir"], + transactionTime: json["transaction_time"] == null + ? null + : DateTime.parse(json["transaction_time"]), + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + ); + + Map toMap() => { + "id": id, + "payment_amount": paymentAmount, + "sub_total": subTotal, + "tax": tax, + "discount": discount, + "discount_amount": discountAmount, + "service_charge": serviceCharge, + "total": total, + "payment_method": paymentMethod, + "total_item": totalItem, + "id_kasir": idKasir, + "nama_kasir": namaKasir, + "transaction_time": transactionTime?.toIso8601String(), + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + }; +} diff --git a/lib/data/models/response/payment_method_response_model.dart b/lib/data/models/response/payment_method_response_model.dart new file mode 100644 index 0000000..d2616e6 --- /dev/null +++ b/lib/data/models/response/payment_method_response_model.dart @@ -0,0 +1,90 @@ +import 'dart:convert'; + +class PaymentMethodResponseModel { + final String? status; + final PaymentMethodData? data; + + PaymentMethodResponseModel({ + this.status, + this.data, + }); + + factory PaymentMethodResponseModel.fromJson(String str) => + PaymentMethodResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory PaymentMethodResponseModel.fromMap(Map json) => + PaymentMethodResponseModel( + status: json["status"], + data: json["data"] == null + ? null + : PaymentMethodData.fromMap(json["data"]), + ); + + Map toMap() => { + "status": status, + "data": data?.toMap(), + }; +} + +class PaymentMethodData { + final String? total; + final List? paymentMethods; + + PaymentMethodData({ + this.total, + this.paymentMethods, + }); + + factory PaymentMethodData.fromJson(String str) => + PaymentMethodData.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory PaymentMethodData.fromMap(Map json) => + PaymentMethodData( + total: json["total"], + paymentMethods: json["payment_methods"] == null + ? [] + : List.from( + json["payment_methods"]!.map((x) => PaymentMethodItem.fromMap(x))), + ); + + Map toMap() => { + "total": total, + "payment_methods": paymentMethods == null + ? [] + : List.from(paymentMethods!.map((x) => x.toMap())), + }; +} + +class PaymentMethodItem { + final String? paymentMethod; + final String? totalAmount; + final int? transactionCount; + + PaymentMethodItem({ + this.paymentMethod, + this.totalAmount, + this.transactionCount, + }); + + factory PaymentMethodItem.fromJson(String str) => + PaymentMethodItem.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory PaymentMethodItem.fromMap(Map json) => + PaymentMethodItem( + paymentMethod: json["payment_method"], + totalAmount: json["total_amount"], + transactionCount: json["transaction_count"], + ); + + Map toMap() => { + "payment_method": paymentMethod, + "total_amount": totalAmount, + "transaction_count": transactionCount, + }; +} \ No newline at end of file diff --git a/lib/data/models/response/payment_methods_response_model.dart b/lib/data/models/response/payment_methods_response_model.dart new file mode 100644 index 0000000..ff08cb9 --- /dev/null +++ b/lib/data/models/response/payment_methods_response_model.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; + +class PaymentMethodsResponseModel { + final String? status; + final List? data; + + PaymentMethodsResponseModel({ + this.status, + this.data, + }); + + factory PaymentMethodsResponseModel.fromJson(String str) => + PaymentMethodsResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory PaymentMethodsResponseModel.fromMap(Map json) => + PaymentMethodsResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => PaymentMethod.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": data == null + ? [] + : List.from(data!.map((x) => x.toMap())), + }; +} + +class PaymentMethod { + final int? id; + final String? name; + final String? description; + final bool? isActive; + final int? sortOrder; + final DateTime? createdAt; + final DateTime? updatedAt; + + PaymentMethod({ + this.id, + this.name, + this.description, + this.isActive, + this.sortOrder, + this.createdAt, + this.updatedAt, + }); + + factory PaymentMethod.fromJson(String str) => + PaymentMethod.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory PaymentMethod.fromMap(Map json) => PaymentMethod( + id: json["id"], + name: json["name"], + description: json["description"], + isActive: json["is_active"], + sortOrder: json["sort_order"], + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + ); + + Map toMap() => { + "id": id, + "name": name, + "description": description, + "is_active": isActive, + "sort_order": sortOrder, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + }; +} \ No newline at end of file diff --git a/lib/data/models/response/print_model.dart b/lib/data/models/response/print_model.dart new file mode 100644 index 0000000..7bdee3b --- /dev/null +++ b/lib/data/models/response/print_model.dart @@ -0,0 +1,38 @@ +class PrintModel { + int? id; + final String code; + final String name; + final String address; + final String paper; + final String type; + + PrintModel({ + this.id, + required this.code, + required this.name, + required this.address, + required this.paper, + required this.type, + }); + + // from map + factory PrintModel.fromMap(Map map) { + return PrintModel( + id: map['id'], + code: map['code'], + name: map['name'], + address: map['address'], + paper: map['paper'], + type: map['type'], + ); + } + + // to map + Map toMap() => { + "code": code, + "name": name, + "address": address, + "paper": paper, + "type": type, + }; +} diff --git a/lib/data/models/response/product_response_model.dart b/lib/data/models/response/product_response_model.dart new file mode 100644 index 0000000..07330d6 --- /dev/null +++ b/lib/data/models/response/product_response_model.dart @@ -0,0 +1,299 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; + +import 'package:enaklo_pos/presentation/home/pages/confirm_payment_page.dart'; + +class ProductResponseModel { + final String? status; + final List? data; + + ProductResponseModel({ + this.status, + this.data, + }); + + factory ProductResponseModel.fromJson(String str) => + ProductResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ProductResponseModel.fromMap(Map json) => + ProductResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from(json["data"]!.map((x) => Product.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": + data == null ? [] : List.from(data!.map((x) => x.toMap())), + }; +} + +class Product { + final int? id; + final int? productId; + final int? categoryId; + final String? name; + final String? description; + final String? image; + final String? price; + final int? stock; + final int? status; + final int? isFavorite; + final DateTime? createdAt; + final DateTime? updatedAt; + final Category? category; + final String? printerType; + + Product({ + this.id, + this.productId, + this.categoryId, + this.name, + this.description, + this.image, + this.price, + this.stock, + this.status, + this.isFavorite, + this.createdAt, + this.updatedAt, + this.category, + this.printerType, + }); + + factory Product.fromJson(String str) => Product.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory Product.fromMap(Map json) => Product( + id: json["id"] is String ? int.tryParse(json["id"]) : json["id"], + productId: json["product_id"] is String ? int.tryParse(json["product_id"]) : json["product_id"], + categoryId: json["category_id"] is String + ? int.tryParse(json["category_id"]) + : json["category_id"], + name: json["name"], + description: json["description"], + image: json["image"], + // price: json["price"].substring(0, json["price"].length - 3), + price: json["price"].toString().replaceAll('.00', ''), + stock: json["stock"] is String ? int.tryParse(json["stock"]) : json["stock"], + status: json["status"] is String ? int.tryParse(json["status"]) : json["status"], + isFavorite: json["is_favorite"] is String ? int.tryParse(json["is_favorite"]) : json["is_favorite"], + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + category: json["category"] == null + ? null + : Category.fromMap(json["category"]), + printerType: json["printer_type"] ?? 'bar', + ); + + factory Product.fromOrderMap(Map json) => Product( + id: json["id_product"], + price: json["price"].toString(), + ); + + factory Product.fromLocalMap(Map json) => Product( + id: json["id"], + productId: json["product_id"], + categoryId: json["categoryId"], + category: Category( + id: json["categoryId"], + name: json["categoryName"], + ), + name: json["name"], + description: json["description"], + image: json["image"], + price: json["price"], + stock: json["stock"], + status: json["status"], + isFavorite: json["isFavorite"], + createdAt: json["createdAt"] == null + ? null + : DateTime.parse(json["createdAt"]), + updatedAt: json["updatedAt"] == null + ? null + : DateTime.parse(json["updatedAt"]), + printerType: json["printer_type"] ?? 'bar', + ); + + Map toLocalMap() => { + "product_id": id, + "categoryId": categoryId, + "categoryName": category?.name, + "name": name, + "description": description, + "image": image, + "price": price?.replaceAll(RegExp(r'\.0+$'), ''), + "stock": stock, + "status": status, + "isFavorite": isFavorite, + "createdAt": createdAt?.toIso8601String(), + "updatedAt": updatedAt?.toIso8601String(), + "printer_type": printerType, + }; + + Map toMap() => { + "id": id, + "product_id": productId, + "category_id": categoryId, + "name": name, + "description": description, + "image": image, + "price": price, + "stock": stock, + "status": status, + "is_favorite": isFavorite, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + "category": category?.toMap(), + "printer_type": printerType, + }; + + @override + bool operator ==(covariant Product other) { + if (identical(this, other)) return true; + + return other.id == id && + other.productId == productId && + other.categoryId == categoryId && + other.name == name && + other.description == description && + other.image == image && + other.price == price && + other.stock == stock && + other.status == status && + other.isFavorite == isFavorite && + other.createdAt == createdAt && + other.updatedAt == updatedAt && + other.category == category && + other.printerType == printerType; + } + + @override + int get hashCode { + return id.hashCode ^ + productId.hashCode ^ + categoryId.hashCode ^ + name.hashCode ^ + description.hashCode ^ + image.hashCode ^ + price.hashCode ^ + stock.hashCode ^ + status.hashCode ^ + isFavorite.hashCode ^ + createdAt.hashCode ^ + updatedAt.hashCode ^ + category.hashCode ^ + printerType.hashCode; + } + + Product copyWith({ + int? id, + int? productId, + int? categoryId, + String? name, + String? description, + String? image, + String? price, + int? stock, + int? status, + int? isFavorite, + DateTime? createdAt, + DateTime? updatedAt, + Category? category, + String? printerType, + }) { + return Product( + id: id ?? this.id, + productId: productId ?? this.productId, + categoryId: categoryId ?? this.categoryId, + name: name ?? this.name, + description: description ?? this.description, + image: image ?? this.image, + price: price ?? this.price, + stock: stock ?? this.stock, + status: status ?? this.status, + isFavorite: isFavorite ?? this.isFavorite, + createdAt: createdAt ?? this.createdAt, + updatedAt: updatedAt ?? this.updatedAt, + category: category ?? this.category, + printerType: printerType ?? this.printerType, + ); + } +} + +class Category { + final int? id; + final String? name; + final String? description; + final String? image; + final DateTime? createdAt; + final DateTime? updatedAt; + + Category({ + this.id, + this.name, + this.description, + this.image, + this.createdAt, + this.updatedAt, + }); + + factory Category.fromJson(String str) => Category.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory Category.fromMap(Map json) => Category( + id: json["id"] is String ? int.tryParse(json["id"]) : json["id"], + name: json["name"], + description: json["description"], + image: json["image"], + createdAt: json["created_at"] == null + ? null + : DateTime.parse(json["created_at"]), + updatedAt: json["updated_at"] == null + ? null + : DateTime.parse(json["updated_at"]), + ); + + Map toMap() => { + "id": id, + "name": name, + "description": description, + "image": image, + "created_at": createdAt?.toIso8601String(), + "updated_at": updatedAt?.toIso8601String(), + }; + + @override + bool operator ==(covariant Category other) { + if (identical(this, other)) return true; + + return other.id == id && + other.name == name && + other.description == description && + other.image == image && + other.createdAt == createdAt && + other.updatedAt == updatedAt; + } + + @override + int get hashCode { + return id.hashCode ^ + name.hashCode ^ + description.hashCode ^ + image.hashCode ^ + createdAt.hashCode ^ + updatedAt.hashCode; + } +} diff --git a/lib/data/models/response/product_sales_response_model.dart b/lib/data/models/response/product_sales_response_model.dart new file mode 100644 index 0000000..8189a6c --- /dev/null +++ b/lib/data/models/response/product_sales_response_model.dart @@ -0,0 +1,60 @@ +import 'dart:convert'; + +class ProductSalesResponseModel { + String? status; + List? data; + + ProductSalesResponseModel({ + this.status, + this.data, + }); + + factory ProductSalesResponseModel.fromJson(String str) => + ProductSalesResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ProductSalesResponseModel.fromMap(Map json) => + ProductSalesResponseModel( + status: json["status"], + data: json["data"] == null + ? [] + : List.from( + json["data"]!.map((x) => ProductSales.fromMap(x))), + ); + + Map toMap() => { + "status": status, + "data": + data == null ? [] : List.from(data!.map((x) => x.toMap())), + }; +} + +class ProductSales { + int? productId; + String? productName; + String? totalQuantity; + + ProductSales({ + this.productId, + this.productName, + this.totalQuantity, + }); + + factory ProductSales.fromJson(String str) => + ProductSales.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory ProductSales.fromMap(Map json) => ProductSales( + productId: json["product_id"], + productName: json["product_name"], + totalQuantity: json["total_quantity"], + ); + + Map toMap() => { + "product_id": productId, + "product_name": productName, + "total_quantity": totalQuantity, + }; +} diff --git a/lib/data/models/response/qris_response_model.dart b/lib/data/models/response/qris_response_model.dart new file mode 100644 index 0000000..006d4fc --- /dev/null +++ b/lib/data/models/response/qris_response_model.dart @@ -0,0 +1,107 @@ +import 'dart:convert'; + +class QrisResponseModel { + final String? statusCode; + final String? statusMessage; + final String? transactionId; + final String? orderId; + final String? merchantId; + final String? grossAmount; + final String? currency; + final String? paymentType; + final DateTime? transactionTime; + final String? transactionStatus; + final String? fraudStatus; + final List? actions; + final DateTime? expiryTime; + + QrisResponseModel({ + this.statusCode, + this.statusMessage, + this.transactionId, + this.orderId, + this.merchantId, + this.grossAmount, + this.currency, + this.paymentType, + this.transactionTime, + this.transactionStatus, + this.fraudStatus, + this.actions, + this.expiryTime, + }); + + factory QrisResponseModel.fromJson(String str) => + QrisResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory QrisResponseModel.fromMap(Map json) => + QrisResponseModel( + statusCode: json["status_code"], + statusMessage: json["status_message"], + transactionId: json["transaction_id"], + orderId: json["order_id"], + merchantId: json["merchant_id"], + grossAmount: json["gross_amount"], + currency: json["currency"], + paymentType: json["payment_type"], + transactionTime: json["transaction_time"] == null + ? null + : DateTime.parse(json["transaction_time"]), + transactionStatus: json["transaction_status"], + fraudStatus: json["fraud_status"], + actions: json["actions"] == null + ? [] + : List.from(json["actions"]!.map((x) => Action.fromMap(x))), + expiryTime: json["expiry_time"] == null + ? null + : DateTime.parse(json["expiry_time"]), + ); + + Map toMap() => { + "status_code": statusCode, + "status_message": statusMessage, + "transaction_id": transactionId, + "order_id": orderId, + "merchant_id": merchantId, + "gross_amount": grossAmount, + "currency": currency, + "payment_type": paymentType, + "transaction_time": transactionTime?.toIso8601String(), + "transaction_status": transactionStatus, + "fraud_status": fraudStatus, + "actions": actions == null + ? [] + : List.from(actions!.map((x) => x.toMap())), + "expiry_time": expiryTime?.toIso8601String(), + }; +} + +class Action { + final String? name; + final String? method; + final String? url; + + Action({ + this.name, + this.method, + this.url, + }); + + factory Action.fromJson(String str) => Action.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory Action.fromMap(Map json) => Action( + name: json["name"], + method: json["method"], + url: json["url"], + ); + + Map toMap() => { + "name": name, + "method": method, + "url": url, + }; +} diff --git a/lib/data/models/response/qris_status_response_model.dart b/lib/data/models/response/qris_status_response_model.dart new file mode 100644 index 0000000..4db3aa2 --- /dev/null +++ b/lib/data/models/response/qris_status_response_model.dart @@ -0,0 +1,111 @@ +import 'dart:convert'; + +class QrisStatusResponseModel { + final String? maskedCard; + final String? approvalCode; + final String? bank; + final String? eci; + final String? channelResponseCode; + final String? channelResponseMessage; + final DateTime? transactionTime; + final String? grossAmount; + final String? currency; + final String? orderId; + final String? paymentType; + final String? signatureKey; + final String? statusCode; + final String? transactionId; + final String? transactionStatus; + final String? fraudStatus; + final DateTime? settlementTime; + final String? statusMessage; + final String? merchantId; + final String? cardType; + final String? threeDsVersion; + final bool? challengeCompletion; + + QrisStatusResponseModel({ + this.maskedCard, + this.approvalCode, + this.bank, + this.eci, + this.channelResponseCode, + this.channelResponseMessage, + this.transactionTime, + this.grossAmount, + this.currency, + this.orderId, + this.paymentType, + this.signatureKey, + this.statusCode, + this.transactionId, + this.transactionStatus, + this.fraudStatus, + this.settlementTime, + this.statusMessage, + this.merchantId, + this.cardType, + this.threeDsVersion, + this.challengeCompletion, + }); + + factory QrisStatusResponseModel.fromJson(String str) => + QrisStatusResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory QrisStatusResponseModel.fromMap(Map json) => + QrisStatusResponseModel( + maskedCard: json["masked_card"], + approvalCode: json["approval_code"], + bank: json["bank"], + eci: json["eci"], + channelResponseCode: json["channel_response_code"], + channelResponseMessage: json["channel_response_message"], + transactionTime: json["transaction_time"] == null + ? null + : DateTime.parse(json["transaction_time"]), + grossAmount: json["gross_amount"], + currency: json["currency"], + orderId: json["order_id"], + paymentType: json["payment_type"], + signatureKey: json["signature_key"], + statusCode: json["status_code"], + transactionId: json["transaction_id"], + transactionStatus: json["transaction_status"], + fraudStatus: json["fraud_status"], + settlementTime: json["settlement_time"] == null + ? null + : DateTime.parse(json["settlement_time"]), + statusMessage: json["status_message"], + merchantId: json["merchant_id"], + cardType: json["card_type"], + threeDsVersion: json["three_ds_version"], + challengeCompletion: json["challenge_completion"], + ); + + Map toMap() => { + "masked_card": maskedCard, + "approval_code": approvalCode, + "bank": bank, + "eci": eci, + "channel_response_code": channelResponseCode, + "channel_response_message": channelResponseMessage, + "transaction_time": transactionTime?.toIso8601String(), + "gross_amount": grossAmount, + "currency": currency, + "order_id": orderId, + "payment_type": paymentType, + "signature_key": signatureKey, + "status_code": statusCode, + "transaction_id": transactionId, + "transaction_status": transactionStatus, + "fraud_status": fraudStatus, + "settlement_time": settlementTime?.toIso8601String(), + "status_message": statusMessage, + "merchant_id": merchantId, + "card_type": cardType, + "three_ds_version": threeDsVersion, + "challenge_completion": challengeCompletion, + }; +} diff --git a/lib/data/models/response/summary_response_model.dart b/lib/data/models/response/summary_response_model.dart new file mode 100644 index 0000000..5f50178 --- /dev/null +++ b/lib/data/models/response/summary_response_model.dart @@ -0,0 +1,78 @@ +import 'dart:convert'; + +class SummaryResponseModel { + String? status; + SummaryModel? data; + + SummaryResponseModel({ + this.status, + this.data, + }); + + factory SummaryResponseModel.fromJson(String str) => + SummaryResponseModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory SummaryResponseModel.fromMap(Map json) => + SummaryResponseModel( + status: json["status"], + data: json["data"] == null ? null : SummaryModel.fromMap(json["data"]), + ); + + Map toMap() => { + "status": status, + "data": data?.toMap(), + }; +} + +class SummaryModel { + String? totalRevenue; + String? totalDiscount; + String? totalTax; + String? totalSubtotal; + String? totalServiceCharge; + int? total; + + SummaryModel({ + this.totalRevenue, + this.totalDiscount, + this.totalTax, + this.totalSubtotal, + this.totalServiceCharge, + this.total, + }); + + factory SummaryModel.fromJson(String str) => + SummaryModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory SummaryModel.fromMap(Map json) => SummaryModel( + totalRevenue: json["total_revenue"] is int + ? json["total_revenue"].toString() + : json["total_revenue"], + totalDiscount: json["total_discount"] is int + ? json["total_discount"].toString() + : json["total_discount"], + totalTax: json["total_tax"] is int + ? json["total_tax"].toString() + : json["total_tax"], + totalSubtotal: json["total_subtotal"] is int + ? json["total_subtotal"].toString() + : json["total_subtotal"], + totalServiceCharge: json["total_service_charge"] is int + ? json["total_service_charge"].toString() + : json["total_service_charge"], + total: json["total"], + ); + + Map toMap() => { + "total_revenue": totalRevenue, + "total_discount": totalDiscount, + "total_tax": totalTax, + "total_subtotal": totalSubtotal, + "total_service_charge": totalServiceCharge, + "total": total, + }; +} diff --git a/lib/data/models/response/table_model.dart b/lib/data/models/response/table_model.dart new file mode 100644 index 0000000..85e81d3 --- /dev/null +++ b/lib/data/models/response/table_model.dart @@ -0,0 +1,74 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:ui'; + +class TableModel { + int? id; + final String tableName; + final String startTime; + final String status; + final int orderId; + final int paymentAmount; + final Offset position; + + TableModel({ + this.id, + required this.tableName, + required this.startTime, + required this.status, + required this.orderId, + required this.paymentAmount, + required this.position, + }); + + @override + + // from map + factory TableModel.fromMap(Map map) { + return TableModel( + id: map['id'], + tableName: map['table_name'], + startTime: map['start_time'], + status: map['status'], + orderId: map['order_id'], + paymentAmount: map['payment_amount'], + position: Offset(map['x_position'], map['y_position']), + ); + } + + // to map + Map toMap() { + return { + 'table_name': tableName, + 'status': status, + 'start_time': startTime, + 'order_id': orderId, + 'payment_amount': paymentAmount, + 'x_position': position.dx, + 'y_position': position.dy, + }; + } + + @override + bool operator ==(covariant TableModel other) { + if (identical(this, other)) return true; + + return other.id == id && + other.tableName == tableName && + other.startTime == startTime && + other.status == status && + other.orderId == orderId && + other.paymentAmount == paymentAmount && + other.position == position; + } + + @override + int get hashCode { + return id.hashCode ^ + tableName.hashCode ^ + startTime.hashCode ^ + status.hashCode ^ + orderId.hashCode ^ + paymentAmount.hashCode ^ + position.hashCode; + } +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..e3017be --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,270 @@ +import 'dart:developer'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:enaklo_pos/data/dataoutputs/laman_print.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/auth_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/category_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/discount_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/midtrans_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/order_item_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/payment_methods_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart'; +import 'package:enaklo_pos/presentation/auth/bloc/logout/logout_bloc.dart'; +import 'package:enaklo_pos/presentation/auth/login_page.dart'; +import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/online_checker/online_checker_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/payment_methods/payment_methods_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/qris/qris_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/product_sales/product_sales_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/summary/summary_bloc.dart'; +import 'package:enaklo_pos/presentation/sales/blocs/bloc/last_order_table_bloc.dart'; +import 'package:enaklo_pos/presentation/sales/blocs/day_sales/day_sales_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/add_product/add_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_categories/get_categories_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_products/get_products_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_product/update_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/change_position_table/change_position_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/generate_table/generate_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/local_product/local_product_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/order/order_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/transaction_report/transaction_report_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/add_discount/add_discount_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/discount/discount_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_order/sync_order_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/tax_settings/tax_settings_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/update_table/update_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/add_order_items/add_order_items_bloc.dart'; +import 'package:enaklo_pos/presentation/table/pages/new_table_management_page.dart'; +import 'package:google_fonts/google_fonts.dart'; +// import 'package:imin_printer/imin_printer.dart'; + +import 'core/constants/colors.dart'; +import 'presentation/auth/bloc/login/login_bloc.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'presentation/home/pages/dashboard_page.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:hive/hive.dart'; +import 'package:path_provider/path_provider.dart'; + +void main() async { + WidgetsFlutterBinding.ensureInitialized(); + // await LamanPrint.init(); + // final dir = await getApplicationDocumentsDirectory(); + // Hive.init(dir.path); + // Hive.registerAdapter(TableDataAdapter()); + runApp(ProviderScope(child: MyApp())); +} + +class MyApp extends StatefulWidget { + const MyApp({super.key}); + + @override + State createState() => _MyAppState(); +} + +class _MyAppState extends State { + // This widget is the root of your application. + // final iminPrinter = IminPrinter(); + String version = '1.0.0'; + @override + void initState() { + super.initState(); + getSdkVersion(); + } + + Future getSdkVersion() async { + // final sdkVersion = await iminPrinter.getSdkVersion(); + if (!mounted) return; + // setState(() { + // version = sdkVersion!; + // }); + } + + @override + Widget build(BuildContext context) { + return MultiBlocProvider( + providers: [ + BlocProvider( + create: (context) => LoginBloc(AuthRemoteDatasource()), + ), + BlocProvider( + create: (context) => LogoutBloc(AuthRemoteDatasource()), + ), + BlocProvider( + create: (context) => SyncProductBloc(ProductRemoteDatasource()), + ), + BlocProvider( + create: (context) => + LocalProductBloc(ProductLocalDatasource.instance), + ), + BlocProvider( + create: (context) => CheckoutBloc(settingsLocalDatasource: SettingsLocalDatasource()), + ), + BlocProvider( + create: (context) => TaxSettingsBloc(SettingsLocalDatasource()), + ), + BlocProvider( + create: (context) { + log("🔧 main.dart: Creating OrderBloc instance"); + return OrderBloc(OrderRemoteDatasource()); + }, + ), + BlocProvider( + create: (context) => SyncOrderBloc(OrderRemoteDatasource()), + ), + BlocProvider( + create: (context) => DiscountBloc(DiscountRemoteDatasource()), + ), + BlocProvider( + create: (context) => AddDiscountBloc(DiscountRemoteDatasource()), + ), + BlocProvider( + create: (context) => TransactionReportBloc(OrderRemoteDatasource()), + ), + BlocProvider( + create: (context) => CreateTableBloc(), + ), + BlocProvider( + create: (context) => ChangePositionTableBloc(), + ), + BlocProvider( + create: (context) => GetTableBloc(), + ), + BlocProvider( + create: (context) => UpdateTableBloc(), + ), + BlocProvider( + create: (context) => StatusTableBloc(ProductLocalDatasource.instance), + ), + BlocProvider( + create: (context) => + LastOrderTableBloc(ProductLocalDatasource.instance), + ), + BlocProvider( + create: (context) => GetTableStatusBloc(), + ), + BlocProvider( + create: (context) => AddProductBloc(ProductRemoteDatasource()), + ), + BlocProvider( + create: (context) => UpdateProductBloc(ProductRemoteDatasource()), + ), + BlocProvider( + create: (context) => GetProductsBloc(ProductRemoteDatasource()), + ), + BlocProvider( + create: (context) => GetCategoriesBloc(CategoryRemoteDatasource()), + ), + BlocProvider( + create: (context) => SummaryBloc(OrderRemoteDatasource()), + ), + BlocProvider( + create: (context) => ProductSalesBloc(OrderItemRemoteDatasource()), + ), + BlocProvider( + create: (context) => ItemSalesReportBloc(OrderItemRemoteDatasource()), + ), + BlocProvider( + create: (context) => PaymentMethodReportBloc(OrderRemoteDatasource()), + ), + BlocProvider( + create: (context) => DaySalesBloc(ProductLocalDatasource.instance), + ), + BlocProvider( + create: (context) => QrisBloc(MidtransRemoteDatasource()), + ), + BlocProvider( + create: (context) => PaymentMethodsBloc(PaymentMethodsRemoteDatasource()), + ), + BlocProvider( + create: (context) => OnlineCheckerBloc(), + ), + BlocProvider( + create: (context) => CreatePrinterBloc(), + ), + BlocProvider( + create: (context) => UpdatePrinterBloc(), + ), + BlocProvider( + create: (context) => GetPrinterReceiptBloc(), + ), + BlocProvider( + create: (context) => GetPrinterCheckerBloc(), + ), + BlocProvider( + create: (context) => GetPrinterKitchenBloc(), + ), + BlocProvider( + create: (context) => GetPrinterBarBloc(), + ), + BlocProvider( + create: (context) => AddOrderItemsBloc(OrderRemoteDatasource()), + ), + ], + child: MaterialApp( + debugShowCheckedModeBanner: false, + title: 'POS Resto App', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: AppColors.primary), + useMaterial3: true, + textTheme: GoogleFonts.quicksandTextTheme( + Theme.of(context).textTheme, + ), + appBarTheme: AppBarTheme( + color: AppColors.white, + elevation: 0, + titleTextStyle: GoogleFonts.quicksand( + color: AppColors.primary, + fontSize: 16.0, + fontWeight: FontWeight.w500, + ), + iconTheme: const IconThemeData( + color: AppColors.primary, + ), + ), + ), + home: FutureBuilder( + future: AuthLocalDataSource().isAuthDataExists(), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Scaffold( + body: Center( + child: CircularProgressIndicator(), + ), + ); + } + if (snapshot.hasData) { + if (snapshot.data!) { + return const DashboardPage(); + } else { + return const LoginPage(); + } + } + return const Scaffold( + body: Center( + child: Text('Error'), + ), + ); + }), + ), + ); + } +} diff --git a/lib/presentation/auth/bloc/login/login_bloc.dart b/lib/presentation/auth/bloc/login/login_bloc.dart new file mode 100644 index 0000000..f09cf26 --- /dev/null +++ b/lib/presentation/auth/bloc/login/login_bloc.dart @@ -0,0 +1,29 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/auth_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/auth_response_model.dart'; + +part 'login_bloc.freezed.dart'; +part 'login_event.dart'; +part 'login_state.dart'; + +class LoginBloc extends Bloc { + final AuthRemoteDatasource authRemoteDatasource; + LoginBloc( + this.authRemoteDatasource, + ) : super(const _Initial()) { + on<_Login>((event, emit) async { + emit(const _Loading()); + + final result = await authRemoteDatasource.login( + event.email, + event.password, + ); + result.fold( + (error) => emit(_Error(error)), + (success) => emit(_Success(success)), + ); + }); + } +} diff --git a/lib/presentation/auth/bloc/login/login_bloc.freezed.dart b/lib/presentation/auth/bloc/login/login_bloc.freezed.dart new file mode 100644 index 0000000..04ae537 --- /dev/null +++ b/lib/presentation/auth/bloc/login/login_bloc.freezed.dart @@ -0,0 +1,950 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'login_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$LoginEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String email, String password) login, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String email, String password)? login, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String email, String password)? login, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Login value) login, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Login value)? login, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Login value)? login, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LoginEventCopyWith<$Res> { + factory $LoginEventCopyWith( + LoginEvent value, $Res Function(LoginEvent) then) = + _$LoginEventCopyWithImpl<$Res, LoginEvent>; +} + +/// @nodoc +class _$LoginEventCopyWithImpl<$Res, $Val extends LoginEvent> + implements $LoginEventCopyWith<$Res> { + _$LoginEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LoginEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$LoginEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'LoginEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String email, String password) login, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String email, String password)? login, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String email, String password)? login, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Login value) login, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Login value)? login, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Login value)? login, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements LoginEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$LoginImplCopyWith<$Res> { + factory _$$LoginImplCopyWith( + _$LoginImpl value, $Res Function(_$LoginImpl) then) = + __$$LoginImplCopyWithImpl<$Res>; + @useResult + $Res call({String email, String password}); +} + +/// @nodoc +class __$$LoginImplCopyWithImpl<$Res> + extends _$LoginEventCopyWithImpl<$Res, _$LoginImpl> + implements _$$LoginImplCopyWith<$Res> { + __$$LoginImplCopyWithImpl( + _$LoginImpl _value, $Res Function(_$LoginImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? email = null, + Object? password = null, + }) { + return _then(_$LoginImpl( + email: null == email + ? _value.email + : email // ignore: cast_nullable_to_non_nullable + as String, + password: null == password + ? _value.password + : password // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$LoginImpl implements _Login { + const _$LoginImpl({required this.email, required this.password}); + + @override + final String email; + @override + final String password; + + @override + String toString() { + return 'LoginEvent.login(email: $email, password: $password)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoginImpl && + (identical(other.email, email) || other.email == email) && + (identical(other.password, password) || + other.password == password)); + } + + @override + int get hashCode => Object.hash(runtimeType, email, password); + + /// Create a copy of LoginEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoginImplCopyWith<_$LoginImpl> get copyWith => + __$$LoginImplCopyWithImpl<_$LoginImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String email, String password) login, + }) { + return login(email, password); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String email, String password)? login, + }) { + return login?.call(email, password); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String email, String password)? login, + required TResult orElse(), + }) { + if (login != null) { + return login(email, password); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Login value) login, + }) { + return login(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Login value)? login, + }) { + return login?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Login value)? login, + required TResult orElse(), + }) { + if (login != null) { + return login(this); + } + return orElse(); + } +} + +abstract class _Login implements LoginEvent { + const factory _Login( + {required final String email, + required final String password}) = _$LoginImpl; + + String get email; + String get password; + + /// Create a copy of LoginEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoginImplCopyWith<_$LoginImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$LoginState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(AuthResponseModel authResponseModel) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(AuthResponseModel authResponseModel)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(AuthResponseModel authResponseModel)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LoginStateCopyWith<$Res> { + factory $LoginStateCopyWith( + LoginState value, $Res Function(LoginState) then) = + _$LoginStateCopyWithImpl<$Res, LoginState>; +} + +/// @nodoc +class _$LoginStateCopyWithImpl<$Res, $Val extends LoginState> + implements $LoginStateCopyWith<$Res> { + _$LoginStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$LoginStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'LoginState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(AuthResponseModel authResponseModel) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(AuthResponseModel authResponseModel)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(AuthResponseModel authResponseModel)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements LoginState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$LoginStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'LoginState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(AuthResponseModel authResponseModel) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(AuthResponseModel authResponseModel)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(AuthResponseModel authResponseModel)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements LoginState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({AuthResponseModel authResponseModel}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$LoginStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? authResponseModel = null, + }) { + return _then(_$SuccessImpl( + null == authResponseModel + ? _value.authResponseModel + : authResponseModel // ignore: cast_nullable_to_non_nullable + as AuthResponseModel, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.authResponseModel); + + @override + final AuthResponseModel authResponseModel; + + @override + String toString() { + return 'LoginState.success(authResponseModel: $authResponseModel)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.authResponseModel, authResponseModel) || + other.authResponseModel == authResponseModel)); + } + + @override + int get hashCode => Object.hash(runtimeType, authResponseModel); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(AuthResponseModel authResponseModel) success, + required TResult Function(String message) error, + }) { + return success(authResponseModel); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(AuthResponseModel authResponseModel)? success, + TResult? Function(String message)? error, + }) { + return success?.call(authResponseModel); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(AuthResponseModel authResponseModel)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(authResponseModel); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements LoginState { + const factory _Success(final AuthResponseModel authResponseModel) = + _$SuccessImpl; + + AuthResponseModel get authResponseModel; + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$LoginStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'LoginState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(AuthResponseModel authResponseModel) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(AuthResponseModel authResponseModel)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(AuthResponseModel authResponseModel)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements LoginState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of LoginState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/auth/bloc/login/login_event.dart b/lib/presentation/auth/bloc/login/login_event.dart new file mode 100644 index 0000000..b4ad5f6 --- /dev/null +++ b/lib/presentation/auth/bloc/login/login_event.dart @@ -0,0 +1,10 @@ +part of 'login_bloc.dart'; + +@freezed +class LoginEvent with _$LoginEvent { + const factory LoginEvent.started() = _Started; + const factory LoginEvent.login({ + required String email, + required String password, + }) = _Login; +} \ No newline at end of file diff --git a/lib/presentation/auth/bloc/login/login_state.dart b/lib/presentation/auth/bloc/login/login_state.dart new file mode 100644 index 0000000..8c1afba --- /dev/null +++ b/lib/presentation/auth/bloc/login/login_state.dart @@ -0,0 +1,9 @@ +part of 'login_bloc.dart'; + +@freezed +class LoginState with _$LoginState { + const factory LoginState.initial() = _Initial; + const factory LoginState.loading() = _Loading; + const factory LoginState.success(AuthResponseModel authResponseModel) = _Success; + const factory LoginState.error(String message) = _Error; +} diff --git a/lib/presentation/auth/bloc/logout/logout_bloc.dart b/lib/presentation/auth/bloc/logout/logout_bloc.dart new file mode 100644 index 0000000..065e6c7 --- /dev/null +++ b/lib/presentation/auth/bloc/logout/logout_bloc.dart @@ -0,0 +1,24 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../../../data/datasources/auth_remote_datasource.dart'; + +part 'logout_bloc.freezed.dart'; +part 'logout_event.dart'; +part 'logout_state.dart'; + +class LogoutBloc extends Bloc { + final AuthRemoteDatasource authRemoteDatasource; + LogoutBloc( + this.authRemoteDatasource, + ) : super(const _Initial()) { + on<_Logout>((event, emit) async{ + emit(const _Loading()); + final result = await authRemoteDatasource.logout(); + result.fold( + (error) => emit(_Error(error)), + (success) => emit(const _Success()), + ); + }); + } +} diff --git a/lib/presentation/auth/bloc/logout/logout_bloc.freezed.dart b/lib/presentation/auth/bloc/logout/logout_bloc.freezed.dart new file mode 100644 index 0000000..ad96a6b --- /dev/null +++ b/lib/presentation/auth/bloc/logout/logout_bloc.freezed.dart @@ -0,0 +1,866 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'logout_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$LogoutEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() logout, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? logout, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? logout, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Logout value) logout, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Logout value)? logout, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Logout value)? logout, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LogoutEventCopyWith<$Res> { + factory $LogoutEventCopyWith( + LogoutEvent value, $Res Function(LogoutEvent) then) = + _$LogoutEventCopyWithImpl<$Res, LogoutEvent>; +} + +/// @nodoc +class _$LogoutEventCopyWithImpl<$Res, $Val extends LogoutEvent> + implements $LogoutEventCopyWith<$Res> { + _$LogoutEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LogoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$LogoutEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'LogoutEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() logout, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? logout, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? logout, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Logout value) logout, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Logout value)? logout, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Logout value)? logout, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements LogoutEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$LogoutImplCopyWith<$Res> { + factory _$$LogoutImplCopyWith( + _$LogoutImpl value, $Res Function(_$LogoutImpl) then) = + __$$LogoutImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LogoutImplCopyWithImpl<$Res> + extends _$LogoutEventCopyWithImpl<$Res, _$LogoutImpl> + implements _$$LogoutImplCopyWith<$Res> { + __$$LogoutImplCopyWithImpl( + _$LogoutImpl _value, $Res Function(_$LogoutImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LogoutImpl implements _Logout { + const _$LogoutImpl(); + + @override + String toString() { + return 'LogoutEvent.logout()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LogoutImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() logout, + }) { + return logout(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? logout, + }) { + return logout?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? logout, + required TResult orElse(), + }) { + if (logout != null) { + return logout(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Logout value) logout, + }) { + return logout(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Logout value)? logout, + }) { + return logout?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Logout value)? logout, + required TResult orElse(), + }) { + if (logout != null) { + return logout(this); + } + return orElse(); + } +} + +abstract class _Logout implements LogoutEvent { + const factory _Logout() = _$LogoutImpl; +} + +/// @nodoc +mixin _$LogoutState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LogoutStateCopyWith<$Res> { + factory $LogoutStateCopyWith( + LogoutState value, $Res Function(LogoutState) then) = + _$LogoutStateCopyWithImpl<$Res, LogoutState>; +} + +/// @nodoc +class _$LogoutStateCopyWithImpl<$Res, $Val extends LogoutState> + implements $LogoutStateCopyWith<$Res> { + _$LogoutStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$LogoutStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'LogoutState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements LogoutState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$LogoutStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'LogoutState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements LogoutState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$LogoutStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(); + + @override + String toString() { + return 'LogoutState.success()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SuccessImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return success(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return success?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements LogoutState { + const factory _Success() = _$SuccessImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$LogoutStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'LogoutState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements LogoutState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of LogoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/auth/bloc/logout/logout_event.dart b/lib/presentation/auth/bloc/logout/logout_event.dart new file mode 100644 index 0000000..489ead6 --- /dev/null +++ b/lib/presentation/auth/bloc/logout/logout_event.dart @@ -0,0 +1,7 @@ +part of 'logout_bloc.dart'; + +@freezed +class LogoutEvent with _$LogoutEvent { + const factory LogoutEvent.started() = _Started; + const factory LogoutEvent.logout() = _Logout; +} \ No newline at end of file diff --git a/lib/presentation/auth/bloc/logout/logout_state.dart b/lib/presentation/auth/bloc/logout/logout_state.dart new file mode 100644 index 0000000..3ef7ee2 --- /dev/null +++ b/lib/presentation/auth/bloc/logout/logout_state.dart @@ -0,0 +1,9 @@ +part of 'logout_bloc.dart'; + +@freezed +class LogoutState with _$LogoutState { + const factory LogoutState.initial() = _Initial; + const factory LogoutState.loading() = _Loading; + const factory LogoutState.success() = _Success; + const factory LogoutState.error(String message) = _Error; +} diff --git a/lib/presentation/auth/login_page.dart b/lib/presentation/auth/login_page.dart new file mode 100644 index 0000000..db91d5d --- /dev/null +++ b/lib/presentation/auth/login_page.dart @@ -0,0 +1,150 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; + +import 'package:flutter_svg/flutter_svg.dart'; + +import '../../core/assets/assets.gen.dart'; +import '../../core/components/buttons.dart'; +import '../../core/components/custom_text_field.dart'; +import '../../core/components/spaces.dart'; +import '../../core/constants/colors.dart'; +import '../home/pages/dashboard_page.dart'; +import 'bloc/login/login_bloc.dart'; + +class LoginPage extends StatefulWidget { + const LoginPage({super.key}); + + @override + State createState() => _LoginPageState(); +} + +class _LoginPageState extends State { + final emailController = TextEditingController(); + final passwordController = TextEditingController(); + bool isPasswordVisible = false; + + @override + void dispose() { + emailController.dispose(); + passwordController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: ListView( + padding: const EdgeInsets.symmetric(horizontal: 260.0, vertical: 20.0), + children: [ + const SpaceHeight(80.0), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 130.0), + child: SvgPicture.asset( + Assets.icons.homeResto.path, + width: 100, + height: 100, + color: AppColors.primary, + )), + const SpaceHeight(24.0), + const Center( + child: Text( + 'Enaklo POS', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + color: Colors.black, + ), + ), + ), + const SpaceHeight(8.0), + const Center( + child: Text( + 'Akses Login Kasir Resto', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w400, + color: Colors.grey, + ), + ), + ), + const SpaceHeight(40.0), + CustomTextField( + controller: emailController, + label: 'Email', + keyboardType: TextInputType.emailAddress, + textInputAction: TextInputAction.next, + ), + const SpaceHeight(12.0), + CustomTextField( + controller: passwordController, + label: 'Password', + obscureText: !isPasswordVisible, + textInputAction: TextInputAction.done, + suffixIcon: InkWell( + onTap: () => setState(() { + isPasswordVisible = !isPasswordVisible; + }), + child: Icon( + isPasswordVisible + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + color: Colors.grey, + size: 20, + ), + ), + ), + const SpaceHeight(24.0), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (authResponseModel) { + AuthLocalDataSource().saveAuthData(authResponseModel); + Navigator.pushReplacement( + context, + MaterialPageRoute( + builder: (context) => const DashboardPage(), + ), + ); + }, + error: (message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(message), + backgroundColor: AppColors.red, + ), + ); + }, + ); + }, + child: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + context.read().add( + LoginEvent.login( + email: emailController.text, + password: passwordController.text, + ), + ); + }, + label: 'Masuk', + ); + }, + loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + ); + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.dart b/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.dart new file mode 100644 index 0000000..0b5c9ad --- /dev/null +++ b/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.dart @@ -0,0 +1,48 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'add_order_items_event.dart'; +part 'add_order_items_state.dart'; +part 'add_order_items_bloc.freezed.dart'; + +class AddOrderItemsBloc extends Bloc { + final OrderRemoteDatasource orderRemoteDatasource; + + AddOrderItemsBloc( + this.orderRemoteDatasource, + ) : super(const _Initial()) { + on<_AddOrderItems>((event, emit) async { + emit(const _Loading()); + + try { + // Convert ProductQuantity list to the format expected by the API + final orderItems = event.items.map((item) => { + 'id_product': item.product.productId, + 'quantity': item.quantity, + 'price': item.product.price!.toIntegerFromText, + 'notes': item.notes, + }).toList(); + + log("Adding order items: ${orderItems.toString()}"); + + final result = await orderRemoteDatasource.addOrderItems( + event.orderId, + orderItems, + ); + + result.fold( + (error) => emit(_Error(error)), + (success) => emit(const _Success()), + ); + } catch (e) { + log("Error in AddOrderItemsBloc: $e"); + emit(_Error("Failed to add order items: $e")); + } + }); + } +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.freezed.dart b/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.freezed.dart new file mode 100644 index 0000000..489dc03 --- /dev/null +++ b/lib/presentation/home/bloc/add_order_items/add_order_items_bloc.freezed.dart @@ -0,0 +1,836 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'add_order_items_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$AddOrderItemsEvent { + int get orderId => throw _privateConstructorUsedError; + List get items => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function(int orderId, List items) + addOrderItems, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(int orderId, List items)? addOrderItems, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(int orderId, List items)? addOrderItems, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_AddOrderItems value) addOrderItems, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_AddOrderItems value)? addOrderItems, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_AddOrderItems value)? addOrderItems, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + /// Create a copy of AddOrderItemsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $AddOrderItemsEventCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddOrderItemsEventCopyWith<$Res> { + factory $AddOrderItemsEventCopyWith( + AddOrderItemsEvent value, $Res Function(AddOrderItemsEvent) then) = + _$AddOrderItemsEventCopyWithImpl<$Res, AddOrderItemsEvent>; + @useResult + $Res call({int orderId, List items}); +} + +/// @nodoc +class _$AddOrderItemsEventCopyWithImpl<$Res, $Val extends AddOrderItemsEvent> + implements $AddOrderItemsEventCopyWith<$Res> { + _$AddOrderItemsEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddOrderItemsEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderId = null, + Object? items = null, + }) { + return _then(_value.copyWith( + orderId: null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as int, + items: null == items + ? _value.items + : items // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$AddOrderItemsImplCopyWith<$Res> + implements $AddOrderItemsEventCopyWith<$Res> { + factory _$$AddOrderItemsImplCopyWith( + _$AddOrderItemsImpl value, $Res Function(_$AddOrderItemsImpl) then) = + __$$AddOrderItemsImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({int orderId, List items}); +} + +/// @nodoc +class __$$AddOrderItemsImplCopyWithImpl<$Res> + extends _$AddOrderItemsEventCopyWithImpl<$Res, _$AddOrderItemsImpl> + implements _$$AddOrderItemsImplCopyWith<$Res> { + __$$AddOrderItemsImplCopyWithImpl( + _$AddOrderItemsImpl _value, $Res Function(_$AddOrderItemsImpl) _then) + : super(_value, _then); + + /// Create a copy of AddOrderItemsEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderId = null, + Object? items = null, + }) { + return _then(_$AddOrderItemsImpl( + null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as int, + null == items + ? _value._items + : items // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$AddOrderItemsImpl implements _AddOrderItems { + const _$AddOrderItemsImpl(this.orderId, final List items) + : _items = items; + + @override + final int orderId; + final List _items; + @override + List get items { + if (_items is EqualUnmodifiableListView) return _items; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_items); + } + + @override + String toString() { + return 'AddOrderItemsEvent.addOrderItems(orderId: $orderId, items: $items)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddOrderItemsImpl && + (identical(other.orderId, orderId) || other.orderId == orderId) && + const DeepCollectionEquality().equals(other._items, _items)); + } + + @override + int get hashCode => Object.hash( + runtimeType, orderId, const DeepCollectionEquality().hash(_items)); + + /// Create a copy of AddOrderItemsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddOrderItemsImplCopyWith<_$AddOrderItemsImpl> get copyWith => + __$$AddOrderItemsImplCopyWithImpl<_$AddOrderItemsImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(int orderId, List items) + addOrderItems, + }) { + return addOrderItems(orderId, items); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(int orderId, List items)? addOrderItems, + }) { + return addOrderItems?.call(orderId, items); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(int orderId, List items)? addOrderItems, + required TResult orElse(), + }) { + if (addOrderItems != null) { + return addOrderItems(orderId, items); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_AddOrderItems value) addOrderItems, + }) { + return addOrderItems(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_AddOrderItems value)? addOrderItems, + }) { + return addOrderItems?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_AddOrderItems value)? addOrderItems, + required TResult orElse(), + }) { + if (addOrderItems != null) { + return addOrderItems(this); + } + return orElse(); + } +} + +abstract class _AddOrderItems implements AddOrderItemsEvent { + const factory _AddOrderItems( + final int orderId, final List items) = + _$AddOrderItemsImpl; + + @override + int get orderId; + @override + List get items; + + /// Create a copy of AddOrderItemsEvent + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddOrderItemsImplCopyWith<_$AddOrderItemsImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$AddOrderItemsState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddOrderItemsStateCopyWith<$Res> { + factory $AddOrderItemsStateCopyWith( + AddOrderItemsState value, $Res Function(AddOrderItemsState) then) = + _$AddOrderItemsStateCopyWithImpl<$Res, AddOrderItemsState>; +} + +/// @nodoc +class _$AddOrderItemsStateCopyWithImpl<$Res, $Val extends AddOrderItemsState> + implements $AddOrderItemsStateCopyWith<$Res> { + _$AddOrderItemsStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$AddOrderItemsStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'AddOrderItemsState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements AddOrderItemsState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$AddOrderItemsStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'AddOrderItemsState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements AddOrderItemsState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$AddOrderItemsStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(); + + @override + String toString() { + return 'AddOrderItemsState.success()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SuccessImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return success(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return success?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements AddOrderItemsState { + const factory _Success() = _$SuccessImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$AddOrderItemsStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'AddOrderItemsState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements AddOrderItemsState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of AddOrderItemsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/add_order_items/add_order_items_event.dart b/lib/presentation/home/bloc/add_order_items/add_order_items_event.dart new file mode 100644 index 0000000..ff04b4e --- /dev/null +++ b/lib/presentation/home/bloc/add_order_items/add_order_items_event.dart @@ -0,0 +1,9 @@ +part of 'add_order_items_bloc.dart'; + +@freezed +class AddOrderItemsEvent with _$AddOrderItemsEvent { + const factory AddOrderItemsEvent.addOrderItems( + int orderId, + List items, + ) = _AddOrderItems; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/add_order_items/add_order_items_state.dart b/lib/presentation/home/bloc/add_order_items/add_order_items_state.dart new file mode 100644 index 0000000..4fc2b1b --- /dev/null +++ b/lib/presentation/home/bloc/add_order_items/add_order_items_state.dart @@ -0,0 +1,9 @@ +part of 'add_order_items_bloc.dart'; + +@freezed +class AddOrderItemsState with _$AddOrderItemsState { + const factory AddOrderItemsState.initial() = _Initial; + const factory AddOrderItemsState.loading() = _Loading; + const factory AddOrderItemsState.success() = _Success; + const factory AddOrderItemsState.error(String message) = _Error; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/checkout/checkout_bloc.dart b/lib/presentation/home/bloc/checkout/checkout_bloc.dart new file mode 100644 index 0000000..379be00 --- /dev/null +++ b/lib/presentation/home/bloc/checkout/checkout_bloc.dart @@ -0,0 +1,269 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/discount_response_model.dart'; +import 'package:enaklo_pos/presentation/home/models/order_item.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:intl/intl.dart'; + +import '../../../../data/models/response/product_response_model.dart'; +import '../../../../data/datasources/settings_local_datasource.dart'; +import '../../models/product_quantity.dart'; +import '../../models/order_type.dart'; + +part 'checkout_event.dart'; +part 'checkout_state.dart'; +part 'checkout_bloc.freezed.dart'; + +class CheckoutBloc extends Bloc { + final SettingsLocalDatasource settingsLocalDatasource; + + CheckoutBloc({required this.settingsLocalDatasource}) : super(const CheckoutState.initial()) { + on<_AddItem>((event, emit) { + var currentState = state as _Loaded; + List items = [...currentState.items]; + var index = + items.indexWhere((element) => element.product.id == event.product.id); + emit(const _Loading()); + if (index != -1) { + items[index] = ProductQuantity( + product: event.product, quantity: items[index].quantity + 1); + } else { + items.add(ProductQuantity(product: event.product, quantity: 1)); + } + emit(_Loaded( + items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_RemoveItem>((event, emit) { + var currentState = state as _Loaded; + List items = [...currentState.items]; + var index = + items.indexWhere((element) => element.product.id == event.product.id); + emit(const _Loading()); + if (index != -1) { + if (items[index].quantity > 1) { + items[index] = ProductQuantity( + product: event.product, quantity: items[index].quantity - 1); + } else { + items.removeAt(index); + } + } + emit(_Loaded( + items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_Started>((event, emit) async { + emit(const _Loading()); + try { + // Load tax and service charge from settings + final tax = await settingsLocalDatasource.getTax(); + final serviceCharge = await settingsLocalDatasource.getServiceCharge(); + + emit(_Loaded([], null, 0, 0, tax.value, serviceCharge, 0, 0, '', OrderType.dineIn)); + } catch (e) { + // If loading fails, use default values + log('Failed to load settings: $e'); + emit(const _Loaded([], null, 0, 0, 10, 5, 0, 0, '', OrderType.dineIn)); + } + }); + + on<_AddDiscount>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + event.discount, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType, + )); + }); + + on<_RemoveDiscount>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + null, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_AddTax>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + event.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_AddServiceCharge>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + event.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType, + )); + }); + + on<_RemoveTax>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + 0, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_RemoveServiceCharge>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + 0, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_UpdateOrderType>((event, emit) { + var currentState = state as _Loaded; + emit(_Loaded( + currentState.items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + event.orderType)); + }); + + on<_UpdateItemNotes>((event, emit) { + var currentState = state as _Loaded; + List items = [...currentState.items]; + var index = items.indexWhere((element) => element.product.id == event.product.id); + if (index != -1) { + items[index] = items[index].copyWith(notes: event.notes); + } + emit(_Loaded( + items, + currentState.discountModel, + currentState.discount, + currentState.discountAmount, + currentState.tax, + currentState.serviceCharge, + currentState.totalQuantity, + currentState.totalPrice, + currentState.draftName, + currentState.orderType)); + }); + + on<_SaveDraftOrder>((event, emit) async { + var currentStates = state as _Loaded; + emit(const _Loading()); + + final draftOrder = DraftOrderModel( + orders: currentStates.items + .map((e) => DraftOrderItem( + product: e.product, + quantity: e.quantity, + )) + .toList(), + totalQuantity: currentStates.totalQuantity, + totalPrice: currentStates.totalPrice, + discount: currentStates.discount, + discountAmount: event.discountAmount, + tax: currentStates.tax, + serviceCharge: currentStates.serviceCharge, + subTotal: currentStates.totalPrice, + tableNumber: event.tableNumber, + draftName: event.draftName, + transactionTime: + DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()), + ); + log("draftOrder12: ${draftOrder.toMapForLocal()}"); + final orderDraftId = + await ProductLocalDatasource.instance.saveDraftOrder(draftOrder); + emit(_SavedDraftOrder(orderDraftId)); + }); + + //load draft order + on<_LoadDraftOrder>((event, emit) async { + emit(const _Loading()); + final draftOrder = event.data; + log("draftOrder: ${draftOrder.toMap()}"); + emit(_Loaded( + draftOrder.orders + .map((e) => + ProductQuantity(product: e.product, quantity: e.quantity)) + .toList(), + null, + draftOrder.discount, + draftOrder.discountAmount, + draftOrder.tax, + draftOrder.serviceCharge, + draftOrder.totalQuantity, + draftOrder.totalPrice, + draftOrder.draftName, + OrderType.dineIn)); + }); + } +} diff --git a/lib/presentation/home/bloc/checkout/checkout_bloc.freezed.dart b/lib/presentation/home/bloc/checkout/checkout_bloc.freezed.dart new file mode 100644 index 0000000..30980f3 --- /dev/null +++ b/lib/presentation/home/bloc/checkout/checkout_bloc.freezed.dart @@ -0,0 +1,3924 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'checkout_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$CheckoutEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CheckoutEventCopyWith<$Res> { + factory $CheckoutEventCopyWith( + CheckoutEvent value, $Res Function(CheckoutEvent) then) = + _$CheckoutEventCopyWithImpl<$Res, CheckoutEvent>; +} + +/// @nodoc +class _$CheckoutEventCopyWithImpl<$Res, $Val extends CheckoutEvent> + implements $CheckoutEventCopyWith<$Res> { + _$CheckoutEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'CheckoutEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements CheckoutEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$AddItemImplCopyWith<$Res> { + factory _$$AddItemImplCopyWith( + _$AddItemImpl value, $Res Function(_$AddItemImpl) then) = + __$$AddItemImplCopyWithImpl<$Res>; + @useResult + $Res call({Product product}); +} + +/// @nodoc +class __$$AddItemImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$AddItemImpl> + implements _$$AddItemImplCopyWith<$Res> { + __$$AddItemImplCopyWithImpl( + _$AddItemImpl _value, $Res Function(_$AddItemImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + }) { + return _then(_$AddItemImpl( + null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + )); + } +} + +/// @nodoc + +class _$AddItemImpl implements _AddItem { + const _$AddItemImpl(this.product); + + @override + final Product product; + + @override + String toString() { + return 'CheckoutEvent.addItem(product: $product)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddItemImpl && + (identical(other.product, product) || other.product == product)); + } + + @override + int get hashCode => Object.hash(runtimeType, product); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddItemImplCopyWith<_$AddItemImpl> get copyWith => + __$$AddItemImplCopyWithImpl<_$AddItemImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return addItem(product); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return addItem?.call(product); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (addItem != null) { + return addItem(product); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return addItem(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return addItem?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (addItem != null) { + return addItem(this); + } + return orElse(); + } +} + +abstract class _AddItem implements CheckoutEvent { + const factory _AddItem(final Product product) = _$AddItemImpl; + + Product get product; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddItemImplCopyWith<_$AddItemImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$RemoveItemImplCopyWith<$Res> { + factory _$$RemoveItemImplCopyWith( + _$RemoveItemImpl value, $Res Function(_$RemoveItemImpl) then) = + __$$RemoveItemImplCopyWithImpl<$Res>; + @useResult + $Res call({Product product}); +} + +/// @nodoc +class __$$RemoveItemImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$RemoveItemImpl> + implements _$$RemoveItemImplCopyWith<$Res> { + __$$RemoveItemImplCopyWithImpl( + _$RemoveItemImpl _value, $Res Function(_$RemoveItemImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + }) { + return _then(_$RemoveItemImpl( + null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + )); + } +} + +/// @nodoc + +class _$RemoveItemImpl implements _RemoveItem { + const _$RemoveItemImpl(this.product); + + @override + final Product product; + + @override + String toString() { + return 'CheckoutEvent.removeItem(product: $product)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RemoveItemImpl && + (identical(other.product, product) || other.product == product)); + } + + @override + int get hashCode => Object.hash(runtimeType, product); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$RemoveItemImplCopyWith<_$RemoveItemImpl> get copyWith => + __$$RemoveItemImplCopyWithImpl<_$RemoveItemImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return removeItem(product); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return removeItem?.call(product); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeItem != null) { + return removeItem(product); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return removeItem(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return removeItem?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeItem != null) { + return removeItem(this); + } + return orElse(); + } +} + +abstract class _RemoveItem implements CheckoutEvent { + const factory _RemoveItem(final Product product) = _$RemoveItemImpl; + + Product get product; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$RemoveItemImplCopyWith<_$RemoveItemImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$AddDiscountImplCopyWith<$Res> { + factory _$$AddDiscountImplCopyWith( + _$AddDiscountImpl value, $Res Function(_$AddDiscountImpl) then) = + __$$AddDiscountImplCopyWithImpl<$Res>; + @useResult + $Res call({Discount discount}); +} + +/// @nodoc +class __$$AddDiscountImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$AddDiscountImpl> + implements _$$AddDiscountImplCopyWith<$Res> { + __$$AddDiscountImplCopyWithImpl( + _$AddDiscountImpl _value, $Res Function(_$AddDiscountImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? discount = null, + }) { + return _then(_$AddDiscountImpl( + null == discount + ? _value.discount + : discount // ignore: cast_nullable_to_non_nullable + as Discount, + )); + } +} + +/// @nodoc + +class _$AddDiscountImpl implements _AddDiscount { + const _$AddDiscountImpl(this.discount); + + @override + final Discount discount; + + @override + String toString() { + return 'CheckoutEvent.addDiscount(discount: $discount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddDiscountImpl && + (identical(other.discount, discount) || + other.discount == discount)); + } + + @override + int get hashCode => Object.hash(runtimeType, discount); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddDiscountImplCopyWith<_$AddDiscountImpl> get copyWith => + __$$AddDiscountImplCopyWithImpl<_$AddDiscountImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return addDiscount(discount); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return addDiscount?.call(discount); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (addDiscount != null) { + return addDiscount(discount); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return addDiscount(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return addDiscount?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (addDiscount != null) { + return addDiscount(this); + } + return orElse(); + } +} + +abstract class _AddDiscount implements CheckoutEvent { + const factory _AddDiscount(final Discount discount) = _$AddDiscountImpl; + + Discount get discount; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddDiscountImplCopyWith<_$AddDiscountImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$RemoveDiscountImplCopyWith<$Res> { + factory _$$RemoveDiscountImplCopyWith(_$RemoveDiscountImpl value, + $Res Function(_$RemoveDiscountImpl) then) = + __$$RemoveDiscountImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RemoveDiscountImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$RemoveDiscountImpl> + implements _$$RemoveDiscountImplCopyWith<$Res> { + __$$RemoveDiscountImplCopyWithImpl( + _$RemoveDiscountImpl _value, $Res Function(_$RemoveDiscountImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$RemoveDiscountImpl implements _RemoveDiscount { + const _$RemoveDiscountImpl(); + + @override + String toString() { + return 'CheckoutEvent.removeDiscount()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$RemoveDiscountImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return removeDiscount(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return removeDiscount?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeDiscount != null) { + return removeDiscount(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return removeDiscount(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return removeDiscount?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeDiscount != null) { + return removeDiscount(this); + } + return orElse(); + } +} + +abstract class _RemoveDiscount implements CheckoutEvent { + const factory _RemoveDiscount() = _$RemoveDiscountImpl; +} + +/// @nodoc +abstract class _$$AddTaxImplCopyWith<$Res> { + factory _$$AddTaxImplCopyWith( + _$AddTaxImpl value, $Res Function(_$AddTaxImpl) then) = + __$$AddTaxImplCopyWithImpl<$Res>; + @useResult + $Res call({int tax}); +} + +/// @nodoc +class __$$AddTaxImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$AddTaxImpl> + implements _$$AddTaxImplCopyWith<$Res> { + __$$AddTaxImplCopyWithImpl( + _$AddTaxImpl _value, $Res Function(_$AddTaxImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tax = null, + }) { + return _then(_$AddTaxImpl( + null == tax + ? _value.tax + : tax // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$AddTaxImpl implements _AddTax { + const _$AddTaxImpl(this.tax); + + @override + final int tax; + + @override + String toString() { + return 'CheckoutEvent.addTax(tax: $tax)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddTaxImpl && + (identical(other.tax, tax) || other.tax == tax)); + } + + @override + int get hashCode => Object.hash(runtimeType, tax); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddTaxImplCopyWith<_$AddTaxImpl> get copyWith => + __$$AddTaxImplCopyWithImpl<_$AddTaxImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return addTax(tax); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return addTax?.call(tax); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (addTax != null) { + return addTax(tax); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return addTax(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return addTax?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (addTax != null) { + return addTax(this); + } + return orElse(); + } +} + +abstract class _AddTax implements CheckoutEvent { + const factory _AddTax(final int tax) = _$AddTaxImpl; + + int get tax; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddTaxImplCopyWith<_$AddTaxImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$AddServiceChargeImplCopyWith<$Res> { + factory _$$AddServiceChargeImplCopyWith(_$AddServiceChargeImpl value, + $Res Function(_$AddServiceChargeImpl) then) = + __$$AddServiceChargeImplCopyWithImpl<$Res>; + @useResult + $Res call({int serviceCharge}); +} + +/// @nodoc +class __$$AddServiceChargeImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$AddServiceChargeImpl> + implements _$$AddServiceChargeImplCopyWith<$Res> { + __$$AddServiceChargeImplCopyWithImpl(_$AddServiceChargeImpl _value, + $Res Function(_$AddServiceChargeImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? serviceCharge = null, + }) { + return _then(_$AddServiceChargeImpl( + null == serviceCharge + ? _value.serviceCharge + : serviceCharge // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$AddServiceChargeImpl implements _AddServiceCharge { + const _$AddServiceChargeImpl(this.serviceCharge); + + @override + final int serviceCharge; + + @override + String toString() { + return 'CheckoutEvent.addServiceCharge(serviceCharge: $serviceCharge)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddServiceChargeImpl && + (identical(other.serviceCharge, serviceCharge) || + other.serviceCharge == serviceCharge)); + } + + @override + int get hashCode => Object.hash(runtimeType, serviceCharge); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddServiceChargeImplCopyWith<_$AddServiceChargeImpl> get copyWith => + __$$AddServiceChargeImplCopyWithImpl<_$AddServiceChargeImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return addServiceCharge(serviceCharge); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return addServiceCharge?.call(serviceCharge); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (addServiceCharge != null) { + return addServiceCharge(serviceCharge); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return addServiceCharge(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return addServiceCharge?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (addServiceCharge != null) { + return addServiceCharge(this); + } + return orElse(); + } +} + +abstract class _AddServiceCharge implements CheckoutEvent { + const factory _AddServiceCharge(final int serviceCharge) = + _$AddServiceChargeImpl; + + int get serviceCharge; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddServiceChargeImplCopyWith<_$AddServiceChargeImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$RemoveTaxImplCopyWith<$Res> { + factory _$$RemoveTaxImplCopyWith( + _$RemoveTaxImpl value, $Res Function(_$RemoveTaxImpl) then) = + __$$RemoveTaxImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RemoveTaxImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$RemoveTaxImpl> + implements _$$RemoveTaxImplCopyWith<$Res> { + __$$RemoveTaxImplCopyWithImpl( + _$RemoveTaxImpl _value, $Res Function(_$RemoveTaxImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$RemoveTaxImpl implements _RemoveTax { + const _$RemoveTaxImpl(); + + @override + String toString() { + return 'CheckoutEvent.removeTax()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$RemoveTaxImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return removeTax(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return removeTax?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeTax != null) { + return removeTax(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return removeTax(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return removeTax?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeTax != null) { + return removeTax(this); + } + return orElse(); + } +} + +abstract class _RemoveTax implements CheckoutEvent { + const factory _RemoveTax() = _$RemoveTaxImpl; +} + +/// @nodoc +abstract class _$$RemoveServiceChargeImplCopyWith<$Res> { + factory _$$RemoveServiceChargeImplCopyWith(_$RemoveServiceChargeImpl value, + $Res Function(_$RemoveServiceChargeImpl) then) = + __$$RemoveServiceChargeImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$RemoveServiceChargeImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$RemoveServiceChargeImpl> + implements _$$RemoveServiceChargeImplCopyWith<$Res> { + __$$RemoveServiceChargeImplCopyWithImpl(_$RemoveServiceChargeImpl _value, + $Res Function(_$RemoveServiceChargeImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$RemoveServiceChargeImpl implements _RemoveServiceCharge { + const _$RemoveServiceChargeImpl(); + + @override + String toString() { + return 'CheckoutEvent.removeServiceCharge()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$RemoveServiceChargeImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return removeServiceCharge(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return removeServiceCharge?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeServiceCharge != null) { + return removeServiceCharge(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return removeServiceCharge(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return removeServiceCharge?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (removeServiceCharge != null) { + return removeServiceCharge(this); + } + return orElse(); + } +} + +abstract class _RemoveServiceCharge implements CheckoutEvent { + const factory _RemoveServiceCharge() = _$RemoveServiceChargeImpl; +} + +/// @nodoc +abstract class _$$UpdateOrderTypeImplCopyWith<$Res> { + factory _$$UpdateOrderTypeImplCopyWith(_$UpdateOrderTypeImpl value, + $Res Function(_$UpdateOrderTypeImpl) then) = + __$$UpdateOrderTypeImplCopyWithImpl<$Res>; + @useResult + $Res call({OrderType orderType}); +} + +/// @nodoc +class __$$UpdateOrderTypeImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$UpdateOrderTypeImpl> + implements _$$UpdateOrderTypeImplCopyWith<$Res> { + __$$UpdateOrderTypeImplCopyWithImpl( + _$UpdateOrderTypeImpl _value, $Res Function(_$UpdateOrderTypeImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderType = null, + }) { + return _then(_$UpdateOrderTypeImpl( + null == orderType + ? _value.orderType + : orderType // ignore: cast_nullable_to_non_nullable + as OrderType, + )); + } +} + +/// @nodoc + +class _$UpdateOrderTypeImpl implements _UpdateOrderType { + const _$UpdateOrderTypeImpl(this.orderType); + + @override + final OrderType orderType; + + @override + String toString() { + return 'CheckoutEvent.updateOrderType(orderType: $orderType)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdateOrderTypeImpl && + (identical(other.orderType, orderType) || + other.orderType == orderType)); + } + + @override + int get hashCode => Object.hash(runtimeType, orderType); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdateOrderTypeImplCopyWith<_$UpdateOrderTypeImpl> get copyWith => + __$$UpdateOrderTypeImplCopyWithImpl<_$UpdateOrderTypeImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return updateOrderType(orderType); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return updateOrderType?.call(orderType); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (updateOrderType != null) { + return updateOrderType(orderType); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return updateOrderType(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return updateOrderType?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (updateOrderType != null) { + return updateOrderType(this); + } + return orElse(); + } +} + +abstract class _UpdateOrderType implements CheckoutEvent { + const factory _UpdateOrderType(final OrderType orderType) = + _$UpdateOrderTypeImpl; + + OrderType get orderType; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdateOrderTypeImplCopyWith<_$UpdateOrderTypeImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$UpdateItemNotesImplCopyWith<$Res> { + factory _$$UpdateItemNotesImplCopyWith(_$UpdateItemNotesImpl value, + $Res Function(_$UpdateItemNotesImpl) then) = + __$$UpdateItemNotesImplCopyWithImpl<$Res>; + @useResult + $Res call({Product product, String notes}); +} + +/// @nodoc +class __$$UpdateItemNotesImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$UpdateItemNotesImpl> + implements _$$UpdateItemNotesImplCopyWith<$Res> { + __$$UpdateItemNotesImplCopyWithImpl( + _$UpdateItemNotesImpl _value, $Res Function(_$UpdateItemNotesImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + Object? notes = null, + }) { + return _then(_$UpdateItemNotesImpl( + null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + null == notes + ? _value.notes + : notes // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$UpdateItemNotesImpl implements _UpdateItemNotes { + const _$UpdateItemNotesImpl(this.product, this.notes); + + @override + final Product product; + @override + final String notes; + + @override + String toString() { + return 'CheckoutEvent.updateItemNotes(product: $product, notes: $notes)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdateItemNotesImpl && + (identical(other.product, product) || other.product == product) && + (identical(other.notes, notes) || other.notes == notes)); + } + + @override + int get hashCode => Object.hash(runtimeType, product, notes); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdateItemNotesImplCopyWith<_$UpdateItemNotesImpl> get copyWith => + __$$UpdateItemNotesImplCopyWithImpl<_$UpdateItemNotesImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return updateItemNotes(product, notes); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return updateItemNotes?.call(product, notes); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (updateItemNotes != null) { + return updateItemNotes(product, notes); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return updateItemNotes(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return updateItemNotes?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (updateItemNotes != null) { + return updateItemNotes(this); + } + return orElse(); + } +} + +abstract class _UpdateItemNotes implements CheckoutEvent { + const factory _UpdateItemNotes(final Product product, final String notes) = + _$UpdateItemNotesImpl; + + Product get product; + String get notes; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdateItemNotesImplCopyWith<_$UpdateItemNotesImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SaveDraftOrderImplCopyWith<$Res> { + factory _$$SaveDraftOrderImplCopyWith(_$SaveDraftOrderImpl value, + $Res Function(_$SaveDraftOrderImpl) then) = + __$$SaveDraftOrderImplCopyWithImpl<$Res>; + @useResult + $Res call({int tableNumber, String draftName, int discountAmount}); +} + +/// @nodoc +class __$$SaveDraftOrderImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$SaveDraftOrderImpl> + implements _$$SaveDraftOrderImplCopyWith<$Res> { + __$$SaveDraftOrderImplCopyWithImpl( + _$SaveDraftOrderImpl _value, $Res Function(_$SaveDraftOrderImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tableNumber = null, + Object? draftName = null, + Object? discountAmount = null, + }) { + return _then(_$SaveDraftOrderImpl( + null == tableNumber + ? _value.tableNumber + : tableNumber // ignore: cast_nullable_to_non_nullable + as int, + null == draftName + ? _value.draftName + : draftName // ignore: cast_nullable_to_non_nullable + as String, + null == discountAmount + ? _value.discountAmount + : discountAmount // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$SaveDraftOrderImpl implements _SaveDraftOrder { + const _$SaveDraftOrderImpl( + this.tableNumber, this.draftName, this.discountAmount); + + @override + final int tableNumber; + @override + final String draftName; + @override + final int discountAmount; + + @override + String toString() { + return 'CheckoutEvent.saveDraftOrder(tableNumber: $tableNumber, draftName: $draftName, discountAmount: $discountAmount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SaveDraftOrderImpl && + (identical(other.tableNumber, tableNumber) || + other.tableNumber == tableNumber) && + (identical(other.draftName, draftName) || + other.draftName == draftName) && + (identical(other.discountAmount, discountAmount) || + other.discountAmount == discountAmount)); + } + + @override + int get hashCode => + Object.hash(runtimeType, tableNumber, draftName, discountAmount); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SaveDraftOrderImplCopyWith<_$SaveDraftOrderImpl> get copyWith => + __$$SaveDraftOrderImplCopyWithImpl<_$SaveDraftOrderImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return saveDraftOrder(tableNumber, draftName, discountAmount); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return saveDraftOrder?.call(tableNumber, draftName, discountAmount); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (saveDraftOrder != null) { + return saveDraftOrder(tableNumber, draftName, discountAmount); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return saveDraftOrder(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return saveDraftOrder?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (saveDraftOrder != null) { + return saveDraftOrder(this); + } + return orElse(); + } +} + +abstract class _SaveDraftOrder implements CheckoutEvent { + const factory _SaveDraftOrder(final int tableNumber, final String draftName, + final int discountAmount) = _$SaveDraftOrderImpl; + + int get tableNumber; + String get draftName; + int get discountAmount; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SaveDraftOrderImplCopyWith<_$SaveDraftOrderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$LoadDraftOrderImplCopyWith<$Res> { + factory _$$LoadDraftOrderImplCopyWith(_$LoadDraftOrderImpl value, + $Res Function(_$LoadDraftOrderImpl) then) = + __$$LoadDraftOrderImplCopyWithImpl<$Res>; + @useResult + $Res call({DraftOrderModel data}); +} + +/// @nodoc +class __$$LoadDraftOrderImplCopyWithImpl<$Res> + extends _$CheckoutEventCopyWithImpl<$Res, _$LoadDraftOrderImpl> + implements _$$LoadDraftOrderImplCopyWith<$Res> { + __$$LoadDraftOrderImplCopyWithImpl( + _$LoadDraftOrderImpl _value, $Res Function(_$LoadDraftOrderImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? data = null, + }) { + return _then(_$LoadDraftOrderImpl( + null == data + ? _value.data + : data // ignore: cast_nullable_to_non_nullable + as DraftOrderModel, + )); + } +} + +/// @nodoc + +class _$LoadDraftOrderImpl implements _LoadDraftOrder { + const _$LoadDraftOrderImpl(this.data); + + @override + final DraftOrderModel data; + + @override + String toString() { + return 'CheckoutEvent.loadDraftOrder(data: $data)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadDraftOrderImpl && + (identical(other.data, data) || other.data == data)); + } + + @override + int get hashCode => Object.hash(runtimeType, data); + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadDraftOrderImplCopyWith<_$LoadDraftOrderImpl> get copyWith => + __$$LoadDraftOrderImplCopyWithImpl<_$LoadDraftOrderImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product) addItem, + required TResult Function(Product product) removeItem, + required TResult Function(Discount discount) addDiscount, + required TResult Function() removeDiscount, + required TResult Function(int tax) addTax, + required TResult Function(int serviceCharge) addServiceCharge, + required TResult Function() removeTax, + required TResult Function() removeServiceCharge, + required TResult Function(OrderType orderType) updateOrderType, + required TResult Function(Product product, String notes) updateItemNotes, + required TResult Function( + int tableNumber, String draftName, int discountAmount) + saveDraftOrder, + required TResult Function(DraftOrderModel data) loadDraftOrder, + }) { + return loadDraftOrder(data); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product)? addItem, + TResult? Function(Product product)? removeItem, + TResult? Function(Discount discount)? addDiscount, + TResult? Function()? removeDiscount, + TResult? Function(int tax)? addTax, + TResult? Function(int serviceCharge)? addServiceCharge, + TResult? Function()? removeTax, + TResult? Function()? removeServiceCharge, + TResult? Function(OrderType orderType)? updateOrderType, + TResult? Function(Product product, String notes)? updateItemNotes, + TResult? Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult? Function(DraftOrderModel data)? loadDraftOrder, + }) { + return loadDraftOrder?.call(data); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product)? addItem, + TResult Function(Product product)? removeItem, + TResult Function(Discount discount)? addDiscount, + TResult Function()? removeDiscount, + TResult Function(int tax)? addTax, + TResult Function(int serviceCharge)? addServiceCharge, + TResult Function()? removeTax, + TResult Function()? removeServiceCharge, + TResult Function(OrderType orderType)? updateOrderType, + TResult Function(Product product, String notes)? updateItemNotes, + TResult Function(int tableNumber, String draftName, int discountAmount)? + saveDraftOrder, + TResult Function(DraftOrderModel data)? loadDraftOrder, + required TResult orElse(), + }) { + if (loadDraftOrder != null) { + return loadDraftOrder(data); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddItem value) addItem, + required TResult Function(_RemoveItem value) removeItem, + required TResult Function(_AddDiscount value) addDiscount, + required TResult Function(_RemoveDiscount value) removeDiscount, + required TResult Function(_AddTax value) addTax, + required TResult Function(_AddServiceCharge value) addServiceCharge, + required TResult Function(_RemoveTax value) removeTax, + required TResult Function(_RemoveServiceCharge value) removeServiceCharge, + required TResult Function(_UpdateOrderType value) updateOrderType, + required TResult Function(_UpdateItemNotes value) updateItemNotes, + required TResult Function(_SaveDraftOrder value) saveDraftOrder, + required TResult Function(_LoadDraftOrder value) loadDraftOrder, + }) { + return loadDraftOrder(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddItem value)? addItem, + TResult? Function(_RemoveItem value)? removeItem, + TResult? Function(_AddDiscount value)? addDiscount, + TResult? Function(_RemoveDiscount value)? removeDiscount, + TResult? Function(_AddTax value)? addTax, + TResult? Function(_AddServiceCharge value)? addServiceCharge, + TResult? Function(_RemoveTax value)? removeTax, + TResult? Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult? Function(_UpdateOrderType value)? updateOrderType, + TResult? Function(_UpdateItemNotes value)? updateItemNotes, + TResult? Function(_SaveDraftOrder value)? saveDraftOrder, + TResult? Function(_LoadDraftOrder value)? loadDraftOrder, + }) { + return loadDraftOrder?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddItem value)? addItem, + TResult Function(_RemoveItem value)? removeItem, + TResult Function(_AddDiscount value)? addDiscount, + TResult Function(_RemoveDiscount value)? removeDiscount, + TResult Function(_AddTax value)? addTax, + TResult Function(_AddServiceCharge value)? addServiceCharge, + TResult Function(_RemoveTax value)? removeTax, + TResult Function(_RemoveServiceCharge value)? removeServiceCharge, + TResult Function(_UpdateOrderType value)? updateOrderType, + TResult Function(_UpdateItemNotes value)? updateItemNotes, + TResult Function(_SaveDraftOrder value)? saveDraftOrder, + TResult Function(_LoadDraftOrder value)? loadDraftOrder, + required TResult orElse(), + }) { + if (loadDraftOrder != null) { + return loadDraftOrder(this); + } + return orElse(); + } +} + +abstract class _LoadDraftOrder implements CheckoutEvent { + const factory _LoadDraftOrder(final DraftOrderModel data) = + _$LoadDraftOrderImpl; + + DraftOrderModel get data; + + /// Create a copy of CheckoutEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadDraftOrderImplCopyWith<_$LoadDraftOrderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$CheckoutState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CheckoutStateCopyWith<$Res> { + factory $CheckoutStateCopyWith( + CheckoutState value, $Res Function(CheckoutState) then) = + _$CheckoutStateCopyWithImpl<$Res, CheckoutState>; +} + +/// @nodoc +class _$CheckoutStateCopyWithImpl<$Res, $Val extends CheckoutState> + implements $CheckoutStateCopyWith<$Res> { + _$CheckoutStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$CheckoutStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'CheckoutState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements CheckoutState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$CheckoutStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'CheckoutState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements CheckoutState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call( + {List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$CheckoutStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? items = null, + Object? discountModel = freezed, + Object? discount = null, + Object? discountAmount = null, + Object? tax = null, + Object? serviceCharge = null, + Object? totalQuantity = null, + Object? totalPrice = null, + Object? draftName = null, + Object? orderType = null, + }) { + return _then(_$LoadedImpl( + null == items + ? _value._items + : items // ignore: cast_nullable_to_non_nullable + as List, + freezed == discountModel + ? _value.discountModel + : discountModel // ignore: cast_nullable_to_non_nullable + as Discount?, + null == discount + ? _value.discount + : discount // ignore: cast_nullable_to_non_nullable + as int, + null == discountAmount + ? _value.discountAmount + : discountAmount // ignore: cast_nullable_to_non_nullable + as int, + null == tax + ? _value.tax + : tax // ignore: cast_nullable_to_non_nullable + as int, + null == serviceCharge + ? _value.serviceCharge + : serviceCharge // ignore: cast_nullable_to_non_nullable + as int, + null == totalQuantity + ? _value.totalQuantity + : totalQuantity // ignore: cast_nullable_to_non_nullable + as int, + null == totalPrice + ? _value.totalPrice + : totalPrice // ignore: cast_nullable_to_non_nullable + as int, + null == draftName + ? _value.draftName + : draftName // ignore: cast_nullable_to_non_nullable + as String, + null == orderType + ? _value.orderType + : orderType // ignore: cast_nullable_to_non_nullable + as OrderType, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl( + final List items, + this.discountModel, + this.discount, + this.discountAmount, + this.tax, + this.serviceCharge, + this.totalQuantity, + this.totalPrice, + this.draftName, + this.orderType) + : _items = items; + + final List _items; + @override + List get items { + if (_items is EqualUnmodifiableListView) return _items; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_items); + } + + @override + final Discount? discountModel; + @override + final int discount; + @override + final int discountAmount; + @override + final int tax; + @override + final int serviceCharge; + @override + final int totalQuantity; + @override + final int totalPrice; + @override + final String draftName; + @override + final OrderType orderType; + + @override + String toString() { + return 'CheckoutState.loaded(items: $items, discountModel: $discountModel, discount: $discount, discountAmount: $discountAmount, tax: $tax, serviceCharge: $serviceCharge, totalQuantity: $totalQuantity, totalPrice: $totalPrice, draftName: $draftName, orderType: $orderType)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality().equals(other._items, _items) && + (identical(other.discountModel, discountModel) || + other.discountModel == discountModel) && + (identical(other.discount, discount) || + other.discount == discount) && + (identical(other.discountAmount, discountAmount) || + other.discountAmount == discountAmount) && + (identical(other.tax, tax) || other.tax == tax) && + (identical(other.serviceCharge, serviceCharge) || + other.serviceCharge == serviceCharge) && + (identical(other.totalQuantity, totalQuantity) || + other.totalQuantity == totalQuantity) && + (identical(other.totalPrice, totalPrice) || + other.totalPrice == totalPrice) && + (identical(other.draftName, draftName) || + other.draftName == draftName) && + (identical(other.orderType, orderType) || + other.orderType == orderType)); + } + + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_items), + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) { + return loaded(items, discountModel, discount, discountAmount, tax, + serviceCharge, totalQuantity, totalPrice, draftName, orderType); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) { + return loaded?.call(items, discountModel, discount, discountAmount, tax, + serviceCharge, totalQuantity, totalPrice, draftName, orderType); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(items, discountModel, discount, discountAmount, tax, + serviceCharge, totalQuantity, totalPrice, draftName, orderType); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements CheckoutState { + const factory _Loaded( + final List items, + final Discount? discountModel, + final int discount, + final int discountAmount, + final int tax, + final int serviceCharge, + final int totalQuantity, + final int totalPrice, + final String draftName, + final OrderType orderType) = _$LoadedImpl; + + List get items; + Discount? get discountModel; + int get discount; + int get discountAmount; + int get tax; + int get serviceCharge; + int get totalQuantity; + int get totalPrice; + String get draftName; + OrderType get orderType; + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$CheckoutStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'CheckoutState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements CheckoutState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SavedDraftOrderImplCopyWith<$Res> { + factory _$$SavedDraftOrderImplCopyWith(_$SavedDraftOrderImpl value, + $Res Function(_$SavedDraftOrderImpl) then) = + __$$SavedDraftOrderImplCopyWithImpl<$Res>; + @useResult + $Res call({int orderId}); +} + +/// @nodoc +class __$$SavedDraftOrderImplCopyWithImpl<$Res> + extends _$CheckoutStateCopyWithImpl<$Res, _$SavedDraftOrderImpl> + implements _$$SavedDraftOrderImplCopyWith<$Res> { + __$$SavedDraftOrderImplCopyWithImpl( + _$SavedDraftOrderImpl _value, $Res Function(_$SavedDraftOrderImpl) _then) + : super(_value, _then); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderId = null, + }) { + return _then(_$SavedDraftOrderImpl( + null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$SavedDraftOrderImpl implements _SavedDraftOrder { + const _$SavedDraftOrderImpl(this.orderId); + + @override + final int orderId; + + @override + String toString() { + return 'CheckoutState.savedDraftOrder(orderId: $orderId)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SavedDraftOrderImpl && + (identical(other.orderId, orderId) || other.orderId == orderId)); + } + + @override + int get hashCode => Object.hash(runtimeType, orderId); + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SavedDraftOrderImplCopyWith<_$SavedDraftOrderImpl> get copyWith => + __$$SavedDraftOrderImplCopyWithImpl<_$SavedDraftOrderImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) + loaded, + required TResult Function(String message) error, + required TResult Function(int orderId) savedDraftOrder, + }) { + return savedDraftOrder(orderId); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult? Function(String message)? error, + TResult? Function(int orderId)? savedDraftOrder, + }) { + return savedDraftOrder?.call(orderId); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType)? + loaded, + TResult Function(String message)? error, + TResult Function(int orderId)? savedDraftOrder, + required TResult orElse(), + }) { + if (savedDraftOrder != null) { + return savedDraftOrder(orderId); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + required TResult Function(_SavedDraftOrder value) savedDraftOrder, + }) { + return savedDraftOrder(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + TResult? Function(_SavedDraftOrder value)? savedDraftOrder, + }) { + return savedDraftOrder?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + TResult Function(_SavedDraftOrder value)? savedDraftOrder, + required TResult orElse(), + }) { + if (savedDraftOrder != null) { + return savedDraftOrder(this); + } + return orElse(); + } +} + +abstract class _SavedDraftOrder implements CheckoutState { + const factory _SavedDraftOrder(final int orderId) = _$SavedDraftOrderImpl; + + int get orderId; + + /// Create a copy of CheckoutState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SavedDraftOrderImplCopyWith<_$SavedDraftOrderImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/checkout/checkout_event.dart b/lib/presentation/home/bloc/checkout/checkout_event.dart new file mode 100644 index 0000000..e276431 --- /dev/null +++ b/lib/presentation/home/bloc/checkout/checkout_event.dart @@ -0,0 +1,38 @@ +part of 'checkout_bloc.dart'; + +@freezed +class CheckoutEvent with _$CheckoutEvent { + const factory CheckoutEvent.started() = _Started; + //add item + const factory CheckoutEvent.addItem(Product product) = _AddItem; + //remove item + const factory CheckoutEvent.removeItem(Product product) = _RemoveItem; + + //add discount + const factory CheckoutEvent.addDiscount(Discount discount) = _AddDiscount; + //remove discount + const factory CheckoutEvent.removeDiscount() = _RemoveDiscount; + //add tax + const factory CheckoutEvent.addTax(int tax) = _AddTax; + //add service charge + const factory CheckoutEvent.addServiceCharge(int serviceCharge) = + _AddServiceCharge; + //remove tax + const factory CheckoutEvent.removeTax() = _RemoveTax; + //remove service charge + const factory CheckoutEvent.removeServiceCharge() = _RemoveServiceCharge; + + //update order type + const factory CheckoutEvent.updateOrderType(OrderType orderType) = _UpdateOrderType; + + //update item notes + const factory CheckoutEvent.updateItemNotes(Product product, String notes) = _UpdateItemNotes; + + //save draft order + const factory CheckoutEvent.saveDraftOrder( + int tableNumber, String draftName, int discountAmount) = _SaveDraftOrder; + + //load draft order + const factory CheckoutEvent.loadDraftOrder(DraftOrderModel data) = + _LoadDraftOrder; +} diff --git a/lib/presentation/home/bloc/checkout/checkout_state.dart b/lib/presentation/home/bloc/checkout/checkout_state.dart new file mode 100644 index 0000000..738d63c --- /dev/null +++ b/lib/presentation/home/bloc/checkout/checkout_state.dart @@ -0,0 +1,22 @@ +part of 'checkout_bloc.dart'; + +@freezed +class CheckoutState with _$CheckoutState { + const factory CheckoutState.initial() = _Initial; + const factory CheckoutState.loading() = _Loading; + const factory CheckoutState.loaded( + List items, + Discount? discountModel, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int totalQuantity, + int totalPrice, + String draftName, + OrderType orderType) = _Loaded; + const factory CheckoutState.error(String message) = _Error; + + //save draft order + const factory CheckoutState.savedDraftOrder(int orderId) = _SavedDraftOrder; +} diff --git a/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.dart b/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.dart new file mode 100644 index 0000000..884c4fa --- /dev/null +++ b/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.dart @@ -0,0 +1,20 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_table_status_event.dart'; +part 'get_table_status_state.dart'; +part 'get_table_status_bloc.freezed.dart'; + +class GetTableStatusBloc + extends Bloc { + GetTableStatusBloc() : super(_Initial()) { + on<_GetTablesStatus>((event, emit) async { + emit(_Loading()); + final tables = + await ProductLocalDatasource.instance.getTableByStatus(event.status); + emit(_Success(tables)); + }); + } +} diff --git a/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.freezed.dart b/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.freezed.dart new file mode 100644 index 0000000..db73954 --- /dev/null +++ b/lib/presentation/home/bloc/get_table_status/get_table_status_bloc.freezed.dart @@ -0,0 +1,767 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_table_status_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetTableStatusEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String status) getTablesStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String status)? getTablesStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String status)? getTablesStatus, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTablesStatus value) getTablesStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTablesStatus value)? getTablesStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTablesStatus value)? getTablesStatus, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetTableStatusEventCopyWith<$Res> { + factory $GetTableStatusEventCopyWith( + GetTableStatusEvent value, $Res Function(GetTableStatusEvent) then) = + _$GetTableStatusEventCopyWithImpl<$Res, GetTableStatusEvent>; +} + +/// @nodoc +class _$GetTableStatusEventCopyWithImpl<$Res, $Val extends GetTableStatusEvent> + implements $GetTableStatusEventCopyWith<$Res> { + _$GetTableStatusEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetTableStatusEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetTableStatusEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableStatusEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetTableStatusEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String status) getTablesStatus, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String status)? getTablesStatus, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String status)? getTablesStatus, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTablesStatus value) getTablesStatus, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTablesStatus value)? getTablesStatus, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTablesStatus value)? getTablesStatus, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetTableStatusEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetTablesStatusImplCopyWith<$Res> { + factory _$$GetTablesStatusImplCopyWith(_$GetTablesStatusImpl value, + $Res Function(_$GetTablesStatusImpl) then) = + __$$GetTablesStatusImplCopyWithImpl<$Res>; + @useResult + $Res call({String status}); +} + +/// @nodoc +class __$$GetTablesStatusImplCopyWithImpl<$Res> + extends _$GetTableStatusEventCopyWithImpl<$Res, _$GetTablesStatusImpl> + implements _$$GetTablesStatusImplCopyWith<$Res> { + __$$GetTablesStatusImplCopyWithImpl( + _$GetTablesStatusImpl _value, $Res Function(_$GetTablesStatusImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableStatusEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? status = null, + }) { + return _then(_$GetTablesStatusImpl( + null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetTablesStatusImpl implements _GetTablesStatus { + const _$GetTablesStatusImpl(this.status); + + @override + final String status; + + @override + String toString() { + return 'GetTableStatusEvent.getTablesStatus(status: $status)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetTablesStatusImpl && + (identical(other.status, status) || other.status == status)); + } + + @override + int get hashCode => Object.hash(runtimeType, status); + + /// Create a copy of GetTableStatusEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetTablesStatusImplCopyWith<_$GetTablesStatusImpl> get copyWith => + __$$GetTablesStatusImplCopyWithImpl<_$GetTablesStatusImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String status) getTablesStatus, + }) { + return getTablesStatus(status); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String status)? getTablesStatus, + }) { + return getTablesStatus?.call(status); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String status)? getTablesStatus, + required TResult orElse(), + }) { + if (getTablesStatus != null) { + return getTablesStatus(status); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTablesStatus value) getTablesStatus, + }) { + return getTablesStatus(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTablesStatus value)? getTablesStatus, + }) { + return getTablesStatus?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTablesStatus value)? getTablesStatus, + required TResult orElse(), + }) { + if (getTablesStatus != null) { + return getTablesStatus(this); + } + return orElse(); + } +} + +abstract class _GetTablesStatus implements GetTableStatusEvent { + const factory _GetTablesStatus(final String status) = _$GetTablesStatusImpl; + + String get status; + + /// Create a copy of GetTableStatusEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetTablesStatusImplCopyWith<_$GetTablesStatusImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$GetTableStatusState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetTableStatusStateCopyWith<$Res> { + factory $GetTableStatusStateCopyWith( + GetTableStatusState value, $Res Function(GetTableStatusState) then) = + _$GetTableStatusStateCopyWithImpl<$Res, GetTableStatusState>; +} + +/// @nodoc +class _$GetTableStatusStateCopyWithImpl<$Res, $Val extends GetTableStatusState> + implements $GetTableStatusStateCopyWith<$Res> { + _$GetTableStatusStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetTableStatusStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetTableStatusState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetTableStatusState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetTableStatusStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetTableStatusState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetTableStatusState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({List tables}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetTableStatusStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tables = null, + }) { + return _then(_$SuccessImpl( + null == tables + ? _value._tables + : tables // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(final List tables) : _tables = tables; + + final List _tables; + @override + List get tables { + if (_tables is EqualUnmodifiableListView) return _tables; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_tables); + } + + @override + String toString() { + return 'GetTableStatusState.success(tables: $tables)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + const DeepCollectionEquality().equals(other._tables, _tables)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_tables)); + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return success(tables); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return success?.call(tables); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(tables); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetTableStatusState { + const factory _Success(final List tables) = _$SuccessImpl; + + List get tables; + + /// Create a copy of GetTableStatusState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/get_table_status/get_table_status_event.dart b/lib/presentation/home/bloc/get_table_status/get_table_status_event.dart new file mode 100644 index 0000000..bdb40a0 --- /dev/null +++ b/lib/presentation/home/bloc/get_table_status/get_table_status_event.dart @@ -0,0 +1,9 @@ +part of 'get_table_status_bloc.dart'; + +@freezed +class GetTableStatusEvent with _$GetTableStatusEvent { + const factory GetTableStatusEvent.started() = _Started; + + const factory GetTableStatusEvent.getTablesStatus(String status) = + _GetTablesStatus; +} diff --git a/lib/presentation/home/bloc/get_table_status/get_table_status_state.dart b/lib/presentation/home/bloc/get_table_status/get_table_status_state.dart new file mode 100644 index 0000000..397566a --- /dev/null +++ b/lib/presentation/home/bloc/get_table_status/get_table_status_state.dart @@ -0,0 +1,8 @@ +part of 'get_table_status_bloc.dart'; + +@freezed +class GetTableStatusState with _$GetTableStatusState { + const factory GetTableStatusState.initial() = _Initial; + const factory GetTableStatusState.loading() = _Loading; + const factory GetTableStatusState.success(List tables) = _Success; +} diff --git a/lib/presentation/home/bloc/local_product/local_product_bloc.dart b/lib/presentation/home/bloc/local_product/local_product_bloc.dart new file mode 100644 index 0000000..2c1eac7 --- /dev/null +++ b/lib/presentation/home/bloc/local_product/local_product_bloc.dart @@ -0,0 +1,26 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; + +import '../../../../data/models/response/product_response_model.dart'; + +part 'local_product_bloc.freezed.dart'; +part 'local_product_event.dart'; +part 'local_product_state.dart'; + +class LocalProductBloc extends Bloc { + final ProductLocalDatasource productLocalDatasource; + LocalProductBloc( + this.productLocalDatasource, + ) : super(const _Initial()) { + on<_GetLocalProduct>((event, emit) async { + emit(const _Loading()); + final result = await productLocalDatasource.getProducts(); + log("Result: ${result.length}"); + emit(_Loaded(result)); + }); + } +} diff --git a/lib/presentation/home/bloc/local_product/local_product_bloc.freezed.dart b/lib/presentation/home/bloc/local_product/local_product_bloc.freezed.dart new file mode 100644 index 0000000..d1ecbde --- /dev/null +++ b/lib/presentation/home/bloc/local_product/local_product_bloc.freezed.dart @@ -0,0 +1,907 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'local_product_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$LocalProductEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getLocalProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getLocalProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getLocalProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetLocalProduct value) getLocalProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetLocalProduct value)? getLocalProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetLocalProduct value)? getLocalProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LocalProductEventCopyWith<$Res> { + factory $LocalProductEventCopyWith( + LocalProductEvent value, $Res Function(LocalProductEvent) then) = + _$LocalProductEventCopyWithImpl<$Res, LocalProductEvent>; +} + +/// @nodoc +class _$LocalProductEventCopyWithImpl<$Res, $Val extends LocalProductEvent> + implements $LocalProductEventCopyWith<$Res> { + _$LocalProductEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LocalProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$LocalProductEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'LocalProductEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getLocalProduct, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getLocalProduct, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getLocalProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetLocalProduct value) getLocalProduct, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetLocalProduct value)? getLocalProduct, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetLocalProduct value)? getLocalProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements LocalProductEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetLocalProductImplCopyWith<$Res> { + factory _$$GetLocalProductImplCopyWith(_$GetLocalProductImpl value, + $Res Function(_$GetLocalProductImpl) then) = + __$$GetLocalProductImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetLocalProductImplCopyWithImpl<$Res> + extends _$LocalProductEventCopyWithImpl<$Res, _$GetLocalProductImpl> + implements _$$GetLocalProductImplCopyWith<$Res> { + __$$GetLocalProductImplCopyWithImpl( + _$GetLocalProductImpl _value, $Res Function(_$GetLocalProductImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetLocalProductImpl implements _GetLocalProduct { + const _$GetLocalProductImpl(); + + @override + String toString() { + return 'LocalProductEvent.getLocalProduct()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetLocalProductImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getLocalProduct, + }) { + return getLocalProduct(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getLocalProduct, + }) { + return getLocalProduct?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getLocalProduct, + required TResult orElse(), + }) { + if (getLocalProduct != null) { + return getLocalProduct(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetLocalProduct value) getLocalProduct, + }) { + return getLocalProduct(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetLocalProduct value)? getLocalProduct, + }) { + return getLocalProduct?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetLocalProduct value)? getLocalProduct, + required TResult orElse(), + }) { + if (getLocalProduct != null) { + return getLocalProduct(this); + } + return orElse(); + } +} + +abstract class _GetLocalProduct implements LocalProductEvent { + const factory _GetLocalProduct() = _$GetLocalProductImpl; +} + +/// @nodoc +mixin _$LocalProductState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LocalProductStateCopyWith<$Res> { + factory $LocalProductStateCopyWith( + LocalProductState value, $Res Function(LocalProductState) then) = + _$LocalProductStateCopyWithImpl<$Res, LocalProductState>; +} + +/// @nodoc +class _$LocalProductStateCopyWithImpl<$Res, $Val extends LocalProductState> + implements $LocalProductStateCopyWith<$Res> { + _$LocalProductStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$LocalProductStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'LocalProductState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements LocalProductState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$LocalProductStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'LocalProductState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements LocalProductState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List products}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$LocalProductStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? products = null, + }) { + return _then(_$LoadedImpl( + null == products + ? _value._products + : products // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List products) : _products = products; + + final List _products; + @override + List get products { + if (_products is EqualUnmodifiableListView) return _products; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_products); + } + + @override + String toString() { + return 'LocalProductState.loaded(products: $products)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality().equals(other._products, _products)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_products)); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) loaded, + required TResult Function(String message) error, + }) { + return loaded(products); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(products); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(products); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements LocalProductState { + const factory _Loaded(final List products) = _$LoadedImpl; + + List get products; + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$LocalProductStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'LocalProductState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements LocalProductState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of LocalProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/local_product/local_product_event.dart b/lib/presentation/home/bloc/local_product/local_product_event.dart new file mode 100644 index 0000000..cd293d6 --- /dev/null +++ b/lib/presentation/home/bloc/local_product/local_product_event.dart @@ -0,0 +1,7 @@ +part of 'local_product_bloc.dart'; + +@freezed +class LocalProductEvent with _$LocalProductEvent { + const factory LocalProductEvent.started() = _Started; + const factory LocalProductEvent.getLocalProduct() = _GetLocalProduct; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/local_product/local_product_state.dart b/lib/presentation/home/bloc/local_product/local_product_state.dart new file mode 100644 index 0000000..b350e30 --- /dev/null +++ b/lib/presentation/home/bloc/local_product/local_product_state.dart @@ -0,0 +1,9 @@ +part of 'local_product_bloc.dart'; + +@freezed +class LocalProductState with _$LocalProductState { + const factory LocalProductState.initial() = _Initial; + const factory LocalProductState.loading() = _Loading; + const factory LocalProductState.loaded(List products) = _Loaded; + const factory LocalProductState.error(String message) = _Error; +} diff --git a/lib/presentation/home/bloc/online_checker/online_checker_bloc.dart b/lib/presentation/home/bloc/online_checker/online_checker_bloc.dart new file mode 100644 index 0000000..54d153f --- /dev/null +++ b/lib/presentation/home/bloc/online_checker/online_checker_bloc.dart @@ -0,0 +1,18 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'online_checker_event.dart'; +part 'online_checker_state.dart'; +part 'online_checker_bloc.freezed.dart'; + +class OnlineCheckerBloc extends Bloc { + OnlineCheckerBloc() : super(_Initial()) { + on<_Check>((event, emit) { + if (event.isOnline) { + emit(const _Online()); + } else { + emit(const _Offline()); + } + }); + } +} diff --git a/lib/presentation/home/bloc/online_checker/online_checker_bloc.freezed.dart b/lib/presentation/home/bloc/online_checker/online_checker_bloc.freezed.dart new file mode 100644 index 0000000..d9d4f16 --- /dev/null +++ b/lib/presentation/home/bloc/online_checker/online_checker_bloc.freezed.dart @@ -0,0 +1,902 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'online_checker_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$OnlineCheckerEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(bool isOnline) check, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(bool isOnline)? check, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(bool isOnline)? check, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Check value) check, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Check value)? check, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Check value)? check, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OnlineCheckerEventCopyWith<$Res> { + factory $OnlineCheckerEventCopyWith( + OnlineCheckerEvent value, $Res Function(OnlineCheckerEvent) then) = + _$OnlineCheckerEventCopyWithImpl<$Res, OnlineCheckerEvent>; +} + +/// @nodoc +class _$OnlineCheckerEventCopyWithImpl<$Res, $Val extends OnlineCheckerEvent> + implements $OnlineCheckerEventCopyWith<$Res> { + _$OnlineCheckerEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of OnlineCheckerEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$OnlineCheckerEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'OnlineCheckerEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(bool isOnline) check, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(bool isOnline)? check, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(bool isOnline)? check, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Check value) check, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Check value)? check, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Check value)? check, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements OnlineCheckerEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$CheckImplCopyWith<$Res> { + factory _$$CheckImplCopyWith( + _$CheckImpl value, $Res Function(_$CheckImpl) then) = + __$$CheckImplCopyWithImpl<$Res>; + @useResult + $Res call({bool isOnline}); +} + +/// @nodoc +class __$$CheckImplCopyWithImpl<$Res> + extends _$OnlineCheckerEventCopyWithImpl<$Res, _$CheckImpl> + implements _$$CheckImplCopyWith<$Res> { + __$$CheckImplCopyWithImpl( + _$CheckImpl _value, $Res Function(_$CheckImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? isOnline = null, + }) { + return _then(_$CheckImpl( + null == isOnline + ? _value.isOnline + : isOnline // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc + +class _$CheckImpl implements _Check { + const _$CheckImpl(this.isOnline); + + @override + final bool isOnline; + + @override + String toString() { + return 'OnlineCheckerEvent.check(isOnline: $isOnline)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CheckImpl && + (identical(other.isOnline, isOnline) || + other.isOnline == isOnline)); + } + + @override + int get hashCode => Object.hash(runtimeType, isOnline); + + /// Create a copy of OnlineCheckerEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$CheckImplCopyWith<_$CheckImpl> get copyWith => + __$$CheckImplCopyWithImpl<_$CheckImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(bool isOnline) check, + }) { + return check(isOnline); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(bool isOnline)? check, + }) { + return check?.call(isOnline); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(bool isOnline)? check, + required TResult orElse(), + }) { + if (check != null) { + return check(isOnline); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Check value) check, + }) { + return check(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Check value)? check, + }) { + return check?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Check value)? check, + required TResult orElse(), + }) { + if (check != null) { + return check(this); + } + return orElse(); + } +} + +abstract class _Check implements OnlineCheckerEvent { + const factory _Check(final bool isOnline) = _$CheckImpl; + + bool get isOnline; + + /// Create a copy of OnlineCheckerEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$CheckImplCopyWith<_$CheckImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$OnlineCheckerState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() online, + required TResult Function() offline, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? online, + TResult? Function()? offline, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? online, + TResult Function()? offline, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Online value) online, + required TResult Function(_Offline value) offline, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Online value)? online, + TResult? Function(_Offline value)? offline, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Online value)? online, + TResult Function(_Offline value)? offline, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OnlineCheckerStateCopyWith<$Res> { + factory $OnlineCheckerStateCopyWith( + OnlineCheckerState value, $Res Function(OnlineCheckerState) then) = + _$OnlineCheckerStateCopyWithImpl<$Res, OnlineCheckerState>; +} + +/// @nodoc +class _$OnlineCheckerStateCopyWithImpl<$Res, $Val extends OnlineCheckerState> + implements $OnlineCheckerStateCopyWith<$Res> { + _$OnlineCheckerStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$OnlineCheckerStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'OnlineCheckerState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() online, + required TResult Function() offline, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? online, + TResult? Function()? offline, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? online, + TResult Function()? offline, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Online value) online, + required TResult Function(_Offline value) offline, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Online value)? online, + TResult? Function(_Offline value)? offline, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Online value)? online, + TResult Function(_Offline value)? offline, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements OnlineCheckerState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$OnlineImplCopyWith<$Res> { + factory _$$OnlineImplCopyWith( + _$OnlineImpl value, $Res Function(_$OnlineImpl) then) = + __$$OnlineImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$OnlineImplCopyWithImpl<$Res> + extends _$OnlineCheckerStateCopyWithImpl<$Res, _$OnlineImpl> + implements _$$OnlineImplCopyWith<$Res> { + __$$OnlineImplCopyWithImpl( + _$OnlineImpl _value, $Res Function(_$OnlineImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$OnlineImpl implements _Online { + const _$OnlineImpl(); + + @override + String toString() { + return 'OnlineCheckerState.online()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$OnlineImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() online, + required TResult Function() offline, + required TResult Function(String message) error, + }) { + return online(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? online, + TResult? Function()? offline, + TResult? Function(String message)? error, + }) { + return online?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? online, + TResult Function()? offline, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (online != null) { + return online(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Online value) online, + required TResult Function(_Offline value) offline, + required TResult Function(_Error value) error, + }) { + return online(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Online value)? online, + TResult? Function(_Offline value)? offline, + TResult? Function(_Error value)? error, + }) { + return online?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Online value)? online, + TResult Function(_Offline value)? offline, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (online != null) { + return online(this); + } + return orElse(); + } +} + +abstract class _Online implements OnlineCheckerState { + const factory _Online() = _$OnlineImpl; +} + +/// @nodoc +abstract class _$$OfflineImplCopyWith<$Res> { + factory _$$OfflineImplCopyWith( + _$OfflineImpl value, $Res Function(_$OfflineImpl) then) = + __$$OfflineImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$OfflineImplCopyWithImpl<$Res> + extends _$OnlineCheckerStateCopyWithImpl<$Res, _$OfflineImpl> + implements _$$OfflineImplCopyWith<$Res> { + __$$OfflineImplCopyWithImpl( + _$OfflineImpl _value, $Res Function(_$OfflineImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$OfflineImpl implements _Offline { + const _$OfflineImpl(); + + @override + String toString() { + return 'OnlineCheckerState.offline()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$OfflineImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() online, + required TResult Function() offline, + required TResult Function(String message) error, + }) { + return offline(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? online, + TResult? Function()? offline, + TResult? Function(String message)? error, + }) { + return offline?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? online, + TResult Function()? offline, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (offline != null) { + return offline(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Online value) online, + required TResult Function(_Offline value) offline, + required TResult Function(_Error value) error, + }) { + return offline(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Online value)? online, + TResult? Function(_Offline value)? offline, + TResult? Function(_Error value)? error, + }) { + return offline?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Online value)? online, + TResult Function(_Offline value)? offline, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (offline != null) { + return offline(this); + } + return orElse(); + } +} + +abstract class _Offline implements OnlineCheckerState { + const factory _Offline() = _$OfflineImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$OnlineCheckerStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'OnlineCheckerState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() online, + required TResult Function() offline, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? online, + TResult? Function()? offline, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? online, + TResult Function()? offline, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Online value) online, + required TResult Function(_Offline value) offline, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Online value)? online, + TResult? Function(_Offline value)? offline, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Online value)? online, + TResult Function(_Offline value)? offline, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements OnlineCheckerState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of OnlineCheckerState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/online_checker/online_checker_event.dart b/lib/presentation/home/bloc/online_checker/online_checker_event.dart new file mode 100644 index 0000000..1552f87 --- /dev/null +++ b/lib/presentation/home/bloc/online_checker/online_checker_event.dart @@ -0,0 +1,7 @@ +part of 'online_checker_bloc.dart'; + +@freezed +class OnlineCheckerEvent with _$OnlineCheckerEvent { + const factory OnlineCheckerEvent.started() = _Started; + const factory OnlineCheckerEvent.check(bool isOnline) = _Check; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/online_checker/online_checker_state.dart b/lib/presentation/home/bloc/online_checker/online_checker_state.dart new file mode 100644 index 0000000..748c5a6 --- /dev/null +++ b/lib/presentation/home/bloc/online_checker/online_checker_state.dart @@ -0,0 +1,9 @@ +part of 'online_checker_bloc.dart'; + +@freezed +class OnlineCheckerState with _$OnlineCheckerState { + const factory OnlineCheckerState.initial() = _Initial; + const factory OnlineCheckerState.online() = _Online; + const factory OnlineCheckerState.offline() = _Offline; + const factory OnlineCheckerState.error(String message) = _Error; +} diff --git a/lib/presentation/home/bloc/order/order_bloc.dart b/lib/presentation/home/bloc/order/order_bloc.dart new file mode 100644 index 0000000..9a303bc --- /dev/null +++ b/lib/presentation/home/bloc/order/order_bloc.dart @@ -0,0 +1,97 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; + +import '../../models/order_model.dart'; +import '../../models/product_quantity.dart'; +import '../../models/order_type.dart'; + +part 'order_bloc.freezed.dart'; +part 'order_event.dart'; +part 'order_state.dart'; + +class OrderBloc extends Bloc { + final OrderRemoteDatasource orderRemoteDatasource; + OrderBloc( + this.orderRemoteDatasource, + ) : super(const _Initial()) { + log("🔧 OrderBloc: Constructor called"); + log("🔧 OrderBloc: OrderRemoteDatasource instance: $orderRemoteDatasource"); + on<_Order>((event, emit) async { + log("🎯 OrderBloc: Event handler triggered!"); + emit(const _Loading()); + log("🚀 OrderBloc: Starting order process"); + log("📋 Order event received: ${event.toString()}"); + log("Start 1"); + + final subTotal = event.items.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price!.toIntegerFromText * element.quantity)); + // final total = subTotal + event.tax + event.serviceCharge - event.discount; + + final totalItem = event.items.fold( + 0, (previousValue, element) => previousValue + element.quantity); + + final userData = await AuthLocalDataSource().getAuthData(); + + final dataInput = OrderModel( + subTotal: subTotal, + paymentAmount: event.paymentAmount, + tax: event.tax, + discount: event.discount, + discountAmount: event.discountAmount, + serviceCharge: event.serviceCharge, + total: event.totalPriceFinal, + paymentMethod: event.paymentMethod, + totalItem: totalItem, + idKasir: userData.user?.id ?? 1, + namaKasir: userData.user?.name ?? 'Kasir A', + transactionTime: DateTime.now().toIso8601String(), + customerName: event.customerName, + tableNumber: event.tableNumber, + status: event.status, + paymentStatus: event.paymentStatus, + isSync: 0, + orderItems: event.items, + orderType: event.orderType, + ); + log("Start 2"); + + //check state online or offline + + log("🔄 About to call API to save order..."); + log("📤 Order data being sent to API: ${dataInput.toServerMap()}"); + log("🌐 OrderRemoteDatasource instance: $orderRemoteDatasource"); + + bool value = false; + try { + value = await orderRemoteDatasource.saveOrder(dataInput); + log("📥 API response received: $value"); + } catch (e) { + log("💥 Error calling API: $e"); + value = false; + } + int id = 0; + if (value) { + id = await ProductLocalDatasource.instance + .saveOrder(dataInput.copyWith(isSync: 1)); + } else { + id = await ProductLocalDatasource.instance + .saveOrder(dataInput.copyWith(isSync: 1)); + } + + emit(_Loaded( + dataInput, + id, + )); + }); + } +} diff --git a/lib/presentation/home/bloc/order/order_bloc.freezed.dart b/lib/presentation/home/bloc/order/order_bloc.freezed.dart new file mode 100644 index 0000000..aac2c09 --- /dev/null +++ b/lib/presentation/home/bloc/order/order_bloc.freezed.dart @@ -0,0 +1,1290 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'order_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$OrderEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType) + order, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Order value) order, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Order value)? order, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Order value)? order, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OrderEventCopyWith<$Res> { + factory $OrderEventCopyWith( + OrderEvent value, $Res Function(OrderEvent) then) = + _$OrderEventCopyWithImpl<$Res, OrderEvent>; +} + +/// @nodoc +class _$OrderEventCopyWithImpl<$Res, $Val extends OrderEvent> + implements $OrderEventCopyWith<$Res> { + _$OrderEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of OrderEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$OrderEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'OrderEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType) + order, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Order value) order, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Order value)? order, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Order value)? order, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements OrderEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$OrderImplCopyWith<$Res> { + factory _$$OrderImplCopyWith( + _$OrderImpl value, $Res Function(_$OrderImpl) then) = + __$$OrderImplCopyWithImpl<$Res>; + @useResult + $Res call( + {List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType}); +} + +/// @nodoc +class __$$OrderImplCopyWithImpl<$Res> + extends _$OrderEventCopyWithImpl<$Res, _$OrderImpl> + implements _$$OrderImplCopyWith<$Res> { + __$$OrderImplCopyWithImpl( + _$OrderImpl _value, $Res Function(_$OrderImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? items = null, + Object? discount = null, + Object? discountAmount = null, + Object? tax = null, + Object? serviceCharge = null, + Object? paymentAmount = null, + Object? customerName = null, + Object? tableNumber = null, + Object? status = null, + Object? paymentStatus = null, + Object? paymentMethod = null, + Object? totalPriceFinal = null, + Object? orderType = null, + }) { + return _then(_$OrderImpl( + null == items + ? _value._items + : items // ignore: cast_nullable_to_non_nullable + as List, + null == discount + ? _value.discount + : discount // ignore: cast_nullable_to_non_nullable + as int, + null == discountAmount + ? _value.discountAmount + : discountAmount // ignore: cast_nullable_to_non_nullable + as int, + null == tax + ? _value.tax + : tax // ignore: cast_nullable_to_non_nullable + as int, + null == serviceCharge + ? _value.serviceCharge + : serviceCharge // ignore: cast_nullable_to_non_nullable + as int, + null == paymentAmount + ? _value.paymentAmount + : paymentAmount // ignore: cast_nullable_to_non_nullable + as int, + null == customerName + ? _value.customerName + : customerName // ignore: cast_nullable_to_non_nullable + as String, + null == tableNumber + ? _value.tableNumber + : tableNumber // ignore: cast_nullable_to_non_nullable + as int, + null == status + ? _value.status + : status // ignore: cast_nullable_to_non_nullable + as String, + null == paymentStatus + ? _value.paymentStatus + : paymentStatus // ignore: cast_nullable_to_non_nullable + as String, + null == paymentMethod + ? _value.paymentMethod + : paymentMethod // ignore: cast_nullable_to_non_nullable + as String, + null == totalPriceFinal + ? _value.totalPriceFinal + : totalPriceFinal // ignore: cast_nullable_to_non_nullable + as int, + null == orderType + ? _value.orderType + : orderType // ignore: cast_nullable_to_non_nullable + as OrderType, + )); + } +} + +/// @nodoc + +class _$OrderImpl implements _Order { + const _$OrderImpl( + final List items, + this.discount, + this.discountAmount, + this.tax, + this.serviceCharge, + this.paymentAmount, + this.customerName, + this.tableNumber, + this.status, + this.paymentStatus, + this.paymentMethod, + this.totalPriceFinal, + this.orderType) + : _items = items; + + final List _items; + @override + List get items { + if (_items is EqualUnmodifiableListView) return _items; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_items); + } + + @override + final int discount; + @override + final int discountAmount; + @override + final int tax; + @override + final int serviceCharge; + @override + final int paymentAmount; + @override + final String customerName; + @override + final int tableNumber; + @override + final String status; + @override + final String paymentStatus; + @override + final String paymentMethod; + @override + final int totalPriceFinal; + @override + final OrderType orderType; + + @override + String toString() { + return 'OrderEvent.order(items: $items, discount: $discount, discountAmount: $discountAmount, tax: $tax, serviceCharge: $serviceCharge, paymentAmount: $paymentAmount, customerName: $customerName, tableNumber: $tableNumber, status: $status, paymentStatus: $paymentStatus, paymentMethod: $paymentMethod, totalPriceFinal: $totalPriceFinal, orderType: $orderType)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$OrderImpl && + const DeepCollectionEquality().equals(other._items, _items) && + (identical(other.discount, discount) || + other.discount == discount) && + (identical(other.discountAmount, discountAmount) || + other.discountAmount == discountAmount) && + (identical(other.tax, tax) || other.tax == tax) && + (identical(other.serviceCharge, serviceCharge) || + other.serviceCharge == serviceCharge) && + (identical(other.paymentAmount, paymentAmount) || + other.paymentAmount == paymentAmount) && + (identical(other.customerName, customerName) || + other.customerName == customerName) && + (identical(other.tableNumber, tableNumber) || + other.tableNumber == tableNumber) && + (identical(other.status, status) || other.status == status) && + (identical(other.paymentStatus, paymentStatus) || + other.paymentStatus == paymentStatus) && + (identical(other.paymentMethod, paymentMethod) || + other.paymentMethod == paymentMethod) && + (identical(other.totalPriceFinal, totalPriceFinal) || + other.totalPriceFinal == totalPriceFinal) && + (identical(other.orderType, orderType) || + other.orderType == orderType)); + } + + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_items), + discount, + discountAmount, + tax, + serviceCharge, + paymentAmount, + customerName, + tableNumber, + status, + paymentStatus, + paymentMethod, + totalPriceFinal, + orderType); + + /// Create a copy of OrderEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$OrderImplCopyWith<_$OrderImpl> get copyWith => + __$$OrderImplCopyWithImpl<_$OrderImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType) + order, + }) { + return order( + items, + discount, + discountAmount, + tax, + serviceCharge, + paymentAmount, + customerName, + tableNumber, + status, + paymentStatus, + paymentMethod, + totalPriceFinal, + orderType); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + }) { + return order?.call( + items, + discount, + discountAmount, + tax, + serviceCharge, + paymentAmount, + customerName, + tableNumber, + status, + paymentStatus, + paymentMethod, + totalPriceFinal, + orderType); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType)? + order, + required TResult orElse(), + }) { + if (order != null) { + return order( + items, + discount, + discountAmount, + tax, + serviceCharge, + paymentAmount, + customerName, + tableNumber, + status, + paymentStatus, + paymentMethod, + totalPriceFinal, + orderType); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Order value) order, + }) { + return order(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Order value)? order, + }) { + return order?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Order value)? order, + required TResult orElse(), + }) { + if (order != null) { + return order(this); + } + return orElse(); + } +} + +abstract class _Order implements OrderEvent { + const factory _Order( + final List items, + final int discount, + final int discountAmount, + final int tax, + final int serviceCharge, + final int paymentAmount, + final String customerName, + final int tableNumber, + final String status, + final String paymentStatus, + final String paymentMethod, + final int totalPriceFinal, + final OrderType orderType) = _$OrderImpl; + + List get items; + int get discount; + int get discountAmount; + int get tax; + int get serviceCharge; + int get paymentAmount; + String get customerName; + int get tableNumber; + String get status; + String get paymentStatus; + String get paymentMethod; + int get totalPriceFinal; + OrderType get orderType; + + /// Create a copy of OrderEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$OrderImplCopyWith<_$OrderImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$OrderState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel orderModel, int orderId) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel orderModel, int orderId)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel orderModel, int orderId)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $OrderStateCopyWith<$Res> { + factory $OrderStateCopyWith( + OrderState value, $Res Function(OrderState) then) = + _$OrderStateCopyWithImpl<$Res, OrderState>; +} + +/// @nodoc +class _$OrderStateCopyWithImpl<$Res, $Val extends OrderState> + implements $OrderStateCopyWith<$Res> { + _$OrderStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$OrderStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'OrderState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel orderModel, int orderId) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel orderModel, int orderId)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel orderModel, int orderId)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements OrderState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$OrderStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'OrderState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel orderModel, int orderId) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel orderModel, int orderId)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel orderModel, int orderId)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements OrderState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({OrderModel orderModel, int orderId}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$OrderStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderModel = null, + Object? orderId = null, + }) { + return _then(_$LoadedImpl( + null == orderModel + ? _value.orderModel + : orderModel // ignore: cast_nullable_to_non_nullable + as OrderModel, + null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(this.orderModel, this.orderId); + + @override + final OrderModel orderModel; + @override + final int orderId; + + @override + String toString() { + return 'OrderState.loaded(orderModel: $orderModel, orderId: $orderId)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + (identical(other.orderModel, orderModel) || + other.orderModel == orderModel) && + (identical(other.orderId, orderId) || other.orderId == orderId)); + } + + @override + int get hashCode => Object.hash(runtimeType, orderModel, orderId); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel orderModel, int orderId) loaded, + required TResult Function(String message) error, + }) { + return loaded(orderModel, orderId); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel orderModel, int orderId)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(orderModel, orderId); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel orderModel, int orderId)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(orderModel, orderId); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements OrderState { + const factory _Loaded(final OrderModel orderModel, final int orderId) = + _$LoadedImpl; + + OrderModel get orderModel; + int get orderId; + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$OrderStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'OrderState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel orderModel, int orderId) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel orderModel, int orderId)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel orderModel, int orderId)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements OrderState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of OrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/order/order_event.dart b/lib/presentation/home/bloc/order/order_event.dart new file mode 100644 index 0000000..c1ba49f --- /dev/null +++ b/lib/presentation/home/bloc/order/order_event.dart @@ -0,0 +1,21 @@ +part of 'order_bloc.dart'; + +@freezed +class OrderEvent with _$OrderEvent { + const factory OrderEvent.started() = _Started; + const factory OrderEvent.order( + List items, + int discount, + int discountAmount, + int tax, + int serviceCharge, + int paymentAmount, + String customerName, + int tableNumber, + String status, + String paymentStatus, + String paymentMethod, + int totalPriceFinal, + OrderType orderType, + ) = _Order; +} diff --git a/lib/presentation/home/bloc/order/order_state.dart b/lib/presentation/home/bloc/order/order_state.dart new file mode 100644 index 0000000..85a916b --- /dev/null +++ b/lib/presentation/home/bloc/order/order_state.dart @@ -0,0 +1,9 @@ +part of 'order_bloc.dart'; + +@freezed +class OrderState with _$OrderState { + const factory OrderState.initial() = _Initial; + const factory OrderState.loading() = _Loading; + const factory OrderState.loaded(OrderModel orderModel, int orderId) = _Loaded; + const factory OrderState.error(String message) = _Error; +} diff --git a/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.dart b/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.dart new file mode 100644 index 0000000..b18d945 --- /dev/null +++ b/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.dart @@ -0,0 +1,24 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/payment_methods_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart'; + +part 'payment_methods_event.dart'; +part 'payment_methods_state.dart'; +part 'payment_methods_bloc.freezed.dart'; + +class PaymentMethodsBloc extends Bloc { + final PaymentMethodsRemoteDatasource datasource; + + PaymentMethodsBloc(this.datasource) : super(const _Initial()) { + on<_FetchPaymentMethods>((event, emit) async { + emit(const _Loading()); + final response = await datasource.getPaymentMethods(); + response.fold( + (l) => emit(_Error(l)), + (r) => emit(_Loaded(r.data ?? [])), + ); + }); + } +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.freezed.dart b/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.freezed.dart new file mode 100644 index 0000000..27af4ba --- /dev/null +++ b/lib/presentation/home/bloc/payment_methods/payment_methods_bloc.freezed.dart @@ -0,0 +1,794 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'payment_methods_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$PaymentMethodsEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() fetchPaymentMethods, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? fetchPaymentMethods, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? fetchPaymentMethods, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_FetchPaymentMethods value) fetchPaymentMethods, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_FetchPaymentMethods value)? fetchPaymentMethods, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_FetchPaymentMethods value)? fetchPaymentMethods, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PaymentMethodsEventCopyWith<$Res> { + factory $PaymentMethodsEventCopyWith( + PaymentMethodsEvent value, $Res Function(PaymentMethodsEvent) then) = + _$PaymentMethodsEventCopyWithImpl<$Res, PaymentMethodsEvent>; +} + +/// @nodoc +class _$PaymentMethodsEventCopyWithImpl<$Res, $Val extends PaymentMethodsEvent> + implements $PaymentMethodsEventCopyWith<$Res> { + _$PaymentMethodsEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of PaymentMethodsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$FetchPaymentMethodsImplCopyWith<$Res> { + factory _$$FetchPaymentMethodsImplCopyWith(_$FetchPaymentMethodsImpl value, + $Res Function(_$FetchPaymentMethodsImpl) then) = + __$$FetchPaymentMethodsImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$FetchPaymentMethodsImplCopyWithImpl<$Res> + extends _$PaymentMethodsEventCopyWithImpl<$Res, _$FetchPaymentMethodsImpl> + implements _$$FetchPaymentMethodsImplCopyWith<$Res> { + __$$FetchPaymentMethodsImplCopyWithImpl(_$FetchPaymentMethodsImpl _value, + $Res Function(_$FetchPaymentMethodsImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$FetchPaymentMethodsImpl implements _FetchPaymentMethods { + const _$FetchPaymentMethodsImpl(); + + @override + String toString() { + return 'PaymentMethodsEvent.fetchPaymentMethods()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$FetchPaymentMethodsImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() fetchPaymentMethods, + }) { + return fetchPaymentMethods(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? fetchPaymentMethods, + }) { + return fetchPaymentMethods?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? fetchPaymentMethods, + required TResult orElse(), + }) { + if (fetchPaymentMethods != null) { + return fetchPaymentMethods(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_FetchPaymentMethods value) fetchPaymentMethods, + }) { + return fetchPaymentMethods(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_FetchPaymentMethods value)? fetchPaymentMethods, + }) { + return fetchPaymentMethods?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_FetchPaymentMethods value)? fetchPaymentMethods, + required TResult orElse(), + }) { + if (fetchPaymentMethods != null) { + return fetchPaymentMethods(this); + } + return orElse(); + } +} + +abstract class _FetchPaymentMethods implements PaymentMethodsEvent { + const factory _FetchPaymentMethods() = _$FetchPaymentMethodsImpl; +} + +/// @nodoc +mixin _$PaymentMethodsState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List paymentMethods) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List paymentMethods)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List paymentMethods)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PaymentMethodsStateCopyWith<$Res> { + factory $PaymentMethodsStateCopyWith( + PaymentMethodsState value, $Res Function(PaymentMethodsState) then) = + _$PaymentMethodsStateCopyWithImpl<$Res, PaymentMethodsState>; +} + +/// @nodoc +class _$PaymentMethodsStateCopyWithImpl<$Res, $Val extends PaymentMethodsState> + implements $PaymentMethodsStateCopyWith<$Res> { + _$PaymentMethodsStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$PaymentMethodsStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'PaymentMethodsState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List paymentMethods) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List paymentMethods)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List paymentMethods)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements PaymentMethodsState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$PaymentMethodsStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'PaymentMethodsState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List paymentMethods) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List paymentMethods)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List paymentMethods)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements PaymentMethodsState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List paymentMethods}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$PaymentMethodsStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? paymentMethods = null, + }) { + return _then(_$LoadedImpl( + null == paymentMethods + ? _value._paymentMethods + : paymentMethods // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List paymentMethods) + : _paymentMethods = paymentMethods; + + final List _paymentMethods; + @override + List get paymentMethods { + if (_paymentMethods is EqualUnmodifiableListView) return _paymentMethods; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_paymentMethods); + } + + @override + String toString() { + return 'PaymentMethodsState.loaded(paymentMethods: $paymentMethods)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality() + .equals(other._paymentMethods, _paymentMethods)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_paymentMethods)); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List paymentMethods) loaded, + required TResult Function(String message) error, + }) { + return loaded(paymentMethods); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List paymentMethods)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(paymentMethods); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List paymentMethods)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(paymentMethods); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements PaymentMethodsState { + const factory _Loaded(final List paymentMethods) = + _$LoadedImpl; + + List get paymentMethods; + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$PaymentMethodsStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'PaymentMethodsState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List paymentMethods) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List paymentMethods)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List paymentMethods)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements PaymentMethodsState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of PaymentMethodsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/payment_methods/payment_methods_event.dart b/lib/presentation/home/bloc/payment_methods/payment_methods_event.dart new file mode 100644 index 0000000..7299045 --- /dev/null +++ b/lib/presentation/home/bloc/payment_methods/payment_methods_event.dart @@ -0,0 +1,6 @@ +part of 'payment_methods_bloc.dart'; + +@freezed +class PaymentMethodsEvent with _$PaymentMethodsEvent { + const factory PaymentMethodsEvent.fetchPaymentMethods() = _FetchPaymentMethods; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/payment_methods/payment_methods_state.dart b/lib/presentation/home/bloc/payment_methods/payment_methods_state.dart new file mode 100644 index 0000000..593a6f8 --- /dev/null +++ b/lib/presentation/home/bloc/payment_methods/payment_methods_state.dart @@ -0,0 +1,9 @@ +part of 'payment_methods_bloc.dart'; + +@freezed +class PaymentMethodsState with _$PaymentMethodsState { + const factory PaymentMethodsState.initial() = _Initial; + const factory PaymentMethodsState.loading() = _Loading; + const factory PaymentMethodsState.loaded(List paymentMethods) = _Loaded; + const factory PaymentMethodsState.error(String message) = _Error; +} \ No newline at end of file diff --git a/lib/presentation/home/bloc/qris/qris_bloc.dart b/lib/presentation/home/bloc/qris/qris_bloc.dart new file mode 100644 index 0000000..d9a4ac4 --- /dev/null +++ b/lib/presentation/home/bloc/qris/qris_bloc.dart @@ -0,0 +1,38 @@ +import 'dart:async'; +import 'dart:developer'; + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/midtrans_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/qris_response_model.dart'; +import 'package:enaklo_pos/data/models/response/qris_status_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'qris_event.dart'; +part 'qris_state.dart'; +part 'qris_bloc.freezed.dart'; + +class QrisBloc extends Bloc { + final MidtransRemoteDatasource datasource; + QrisBloc( + this.datasource, + ) : super(const _Initial()) { + on<_GenerateQRCode>((event, emit) async { + emit(const QrisState.loading()); + final response = + await datasource.generateQRCode(event.orderId, event.grossAmount); + log("response: ${response}"); + emit(_QrisResponse(response)); + }); + + on<_CheckPaymentStatus>((event, emit) async { + // emit(const QrisState.loading()); + final response = await datasource.checkPaymentStatus(event.orderId); + log(" OrderID: ${event.orderId} | response: ${response}"); + // Future.delayed(const Duration(seconds: 5)); + // emit(QrisState.statusCheck(response)); + if (response.transactionStatus == 'settlement') { + emit(_Success('Pembayaran Berhasil')); + } + }); + } +} diff --git a/lib/presentation/home/bloc/qris/qris_bloc.freezed.dart b/lib/presentation/home/bloc/qris/qris_bloc.freezed.dart new file mode 100644 index 0000000..a06bd46 --- /dev/null +++ b/lib/presentation/home/bloc/qris/qris_bloc.freezed.dart @@ -0,0 +1,1527 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'qris_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$QrisEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String orderId, int grossAmount) generateQRCode, + required TResult Function(String orderId) checkPaymentStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String orderId, int grossAmount)? generateQRCode, + TResult? Function(String orderId)? checkPaymentStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String orderId, int grossAmount)? generateQRCode, + TResult Function(String orderId)? checkPaymentStatus, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GenerateQRCode value) generateQRCode, + required TResult Function(_CheckPaymentStatus value) checkPaymentStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GenerateQRCode value)? generateQRCode, + TResult? Function(_CheckPaymentStatus value)? checkPaymentStatus, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GenerateQRCode value)? generateQRCode, + TResult Function(_CheckPaymentStatus value)? checkPaymentStatus, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $QrisEventCopyWith<$Res> { + factory $QrisEventCopyWith(QrisEvent value, $Res Function(QrisEvent) then) = + _$QrisEventCopyWithImpl<$Res, QrisEvent>; +} + +/// @nodoc +class _$QrisEventCopyWithImpl<$Res, $Val extends QrisEvent> + implements $QrisEventCopyWith<$Res> { + _$QrisEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$QrisEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'QrisEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String orderId, int grossAmount) generateQRCode, + required TResult Function(String orderId) checkPaymentStatus, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String orderId, int grossAmount)? generateQRCode, + TResult? Function(String orderId)? checkPaymentStatus, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String orderId, int grossAmount)? generateQRCode, + TResult Function(String orderId)? checkPaymentStatus, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GenerateQRCode value) generateQRCode, + required TResult Function(_CheckPaymentStatus value) checkPaymentStatus, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GenerateQRCode value)? generateQRCode, + TResult? Function(_CheckPaymentStatus value)? checkPaymentStatus, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GenerateQRCode value)? generateQRCode, + TResult Function(_CheckPaymentStatus value)? checkPaymentStatus, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements QrisEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GenerateQRCodeImplCopyWith<$Res> { + factory _$$GenerateQRCodeImplCopyWith(_$GenerateQRCodeImpl value, + $Res Function(_$GenerateQRCodeImpl) then) = + __$$GenerateQRCodeImplCopyWithImpl<$Res>; + @useResult + $Res call({String orderId, int grossAmount}); +} + +/// @nodoc +class __$$GenerateQRCodeImplCopyWithImpl<$Res> + extends _$QrisEventCopyWithImpl<$Res, _$GenerateQRCodeImpl> + implements _$$GenerateQRCodeImplCopyWith<$Res> { + __$$GenerateQRCodeImplCopyWithImpl( + _$GenerateQRCodeImpl _value, $Res Function(_$GenerateQRCodeImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderId = null, + Object? grossAmount = null, + }) { + return _then(_$GenerateQRCodeImpl( + null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as String, + null == grossAmount + ? _value.grossAmount + : grossAmount // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$GenerateQRCodeImpl implements _GenerateQRCode { + const _$GenerateQRCodeImpl(this.orderId, this.grossAmount); + + @override + final String orderId; + @override + final int grossAmount; + + @override + String toString() { + return 'QrisEvent.generateQRCode(orderId: $orderId, grossAmount: $grossAmount)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GenerateQRCodeImpl && + (identical(other.orderId, orderId) || other.orderId == orderId) && + (identical(other.grossAmount, grossAmount) || + other.grossAmount == grossAmount)); + } + + @override + int get hashCode => Object.hash(runtimeType, orderId, grossAmount); + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GenerateQRCodeImplCopyWith<_$GenerateQRCodeImpl> get copyWith => + __$$GenerateQRCodeImplCopyWithImpl<_$GenerateQRCodeImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String orderId, int grossAmount) generateQRCode, + required TResult Function(String orderId) checkPaymentStatus, + }) { + return generateQRCode(orderId, grossAmount); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String orderId, int grossAmount)? generateQRCode, + TResult? Function(String orderId)? checkPaymentStatus, + }) { + return generateQRCode?.call(orderId, grossAmount); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String orderId, int grossAmount)? generateQRCode, + TResult Function(String orderId)? checkPaymentStatus, + required TResult orElse(), + }) { + if (generateQRCode != null) { + return generateQRCode(orderId, grossAmount); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GenerateQRCode value) generateQRCode, + required TResult Function(_CheckPaymentStatus value) checkPaymentStatus, + }) { + return generateQRCode(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GenerateQRCode value)? generateQRCode, + TResult? Function(_CheckPaymentStatus value)? checkPaymentStatus, + }) { + return generateQRCode?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GenerateQRCode value)? generateQRCode, + TResult Function(_CheckPaymentStatus value)? checkPaymentStatus, + required TResult orElse(), + }) { + if (generateQRCode != null) { + return generateQRCode(this); + } + return orElse(); + } +} + +abstract class _GenerateQRCode implements QrisEvent { + const factory _GenerateQRCode(final String orderId, final int grossAmount) = + _$GenerateQRCodeImpl; + + String get orderId; + int get grossAmount; + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GenerateQRCodeImplCopyWith<_$GenerateQRCodeImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$CheckPaymentStatusImplCopyWith<$Res> { + factory _$$CheckPaymentStatusImplCopyWith(_$CheckPaymentStatusImpl value, + $Res Function(_$CheckPaymentStatusImpl) then) = + __$$CheckPaymentStatusImplCopyWithImpl<$Res>; + @useResult + $Res call({String orderId}); +} + +/// @nodoc +class __$$CheckPaymentStatusImplCopyWithImpl<$Res> + extends _$QrisEventCopyWithImpl<$Res, _$CheckPaymentStatusImpl> + implements _$$CheckPaymentStatusImplCopyWith<$Res> { + __$$CheckPaymentStatusImplCopyWithImpl(_$CheckPaymentStatusImpl _value, + $Res Function(_$CheckPaymentStatusImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orderId = null, + }) { + return _then(_$CheckPaymentStatusImpl( + null == orderId + ? _value.orderId + : orderId // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$CheckPaymentStatusImpl implements _CheckPaymentStatus { + const _$CheckPaymentStatusImpl(this.orderId); + + @override + final String orderId; + + @override + String toString() { + return 'QrisEvent.checkPaymentStatus(orderId: $orderId)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CheckPaymentStatusImpl && + (identical(other.orderId, orderId) || other.orderId == orderId)); + } + + @override + int get hashCode => Object.hash(runtimeType, orderId); + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$CheckPaymentStatusImplCopyWith<_$CheckPaymentStatusImpl> get copyWith => + __$$CheckPaymentStatusImplCopyWithImpl<_$CheckPaymentStatusImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String orderId, int grossAmount) generateQRCode, + required TResult Function(String orderId) checkPaymentStatus, + }) { + return checkPaymentStatus(orderId); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String orderId, int grossAmount)? generateQRCode, + TResult? Function(String orderId)? checkPaymentStatus, + }) { + return checkPaymentStatus?.call(orderId); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String orderId, int grossAmount)? generateQRCode, + TResult Function(String orderId)? checkPaymentStatus, + required TResult orElse(), + }) { + if (checkPaymentStatus != null) { + return checkPaymentStatus(orderId); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GenerateQRCode value) generateQRCode, + required TResult Function(_CheckPaymentStatus value) checkPaymentStatus, + }) { + return checkPaymentStatus(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GenerateQRCode value)? generateQRCode, + TResult? Function(_CheckPaymentStatus value)? checkPaymentStatus, + }) { + return checkPaymentStatus?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GenerateQRCode value)? generateQRCode, + TResult Function(_CheckPaymentStatus value)? checkPaymentStatus, + required TResult orElse(), + }) { + if (checkPaymentStatus != null) { + return checkPaymentStatus(this); + } + return orElse(); + } +} + +abstract class _CheckPaymentStatus implements QrisEvent { + const factory _CheckPaymentStatus(final String orderId) = + _$CheckPaymentStatusImpl; + + String get orderId; + + /// Create a copy of QrisEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$CheckPaymentStatusImplCopyWith<_$CheckPaymentStatusImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$QrisState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $QrisStateCopyWith<$Res> { + factory $QrisStateCopyWith(QrisState value, $Res Function(QrisState) then) = + _$QrisStateCopyWithImpl<$Res, QrisState>; +} + +/// @nodoc +class _$QrisStateCopyWithImpl<$Res, $Val extends QrisState> + implements $QrisStateCopyWith<$Res> { + _$QrisStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'QrisState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements QrisState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'QrisState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements QrisState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$QrisResponseImplCopyWith<$Res> { + factory _$$QrisResponseImplCopyWith( + _$QrisResponseImpl value, $Res Function(_$QrisResponseImpl) then) = + __$$QrisResponseImplCopyWithImpl<$Res>; + @useResult + $Res call({QrisResponseModel qrisResponseModel}); +} + +/// @nodoc +class __$$QrisResponseImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$QrisResponseImpl> + implements _$$QrisResponseImplCopyWith<$Res> { + __$$QrisResponseImplCopyWithImpl( + _$QrisResponseImpl _value, $Res Function(_$QrisResponseImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? qrisResponseModel = null, + }) { + return _then(_$QrisResponseImpl( + null == qrisResponseModel + ? _value.qrisResponseModel + : qrisResponseModel // ignore: cast_nullable_to_non_nullable + as QrisResponseModel, + )); + } +} + +/// @nodoc + +class _$QrisResponseImpl implements _QrisResponse { + const _$QrisResponseImpl(this.qrisResponseModel); + + @override + final QrisResponseModel qrisResponseModel; + + @override + String toString() { + return 'QrisState.qrisResponse(qrisResponseModel: $qrisResponseModel)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$QrisResponseImpl && + (identical(other.qrisResponseModel, qrisResponseModel) || + other.qrisResponseModel == qrisResponseModel)); + } + + @override + int get hashCode => Object.hash(runtimeType, qrisResponseModel); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$QrisResponseImplCopyWith<_$QrisResponseImpl> get copyWith => + __$$QrisResponseImplCopyWithImpl<_$QrisResponseImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return qrisResponse(qrisResponseModel); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return qrisResponse?.call(qrisResponseModel); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (qrisResponse != null) { + return qrisResponse(qrisResponseModel); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return qrisResponse(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return qrisResponse?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (qrisResponse != null) { + return qrisResponse(this); + } + return orElse(); + } +} + +abstract class _QrisResponse implements QrisState { + const factory _QrisResponse(final QrisResponseModel qrisResponseModel) = + _$QrisResponseImpl; + + QrisResponseModel get qrisResponseModel; + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$QrisResponseImplCopyWith<_$QrisResponseImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'QrisState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements QrisState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'QrisState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements QrisState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$StatusCheckImplCopyWith<$Res> { + factory _$$StatusCheckImplCopyWith( + _$StatusCheckImpl value, $Res Function(_$StatusCheckImpl) then) = + __$$StatusCheckImplCopyWithImpl<$Res>; + @useResult + $Res call({QrisStatusResponseModel qrisStatusResponseModel}); +} + +/// @nodoc +class __$$StatusCheckImplCopyWithImpl<$Res> + extends _$QrisStateCopyWithImpl<$Res, _$StatusCheckImpl> + implements _$$StatusCheckImplCopyWith<$Res> { + __$$StatusCheckImplCopyWithImpl( + _$StatusCheckImpl _value, $Res Function(_$StatusCheckImpl) _then) + : super(_value, _then); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? qrisStatusResponseModel = null, + }) { + return _then(_$StatusCheckImpl( + null == qrisStatusResponseModel + ? _value.qrisStatusResponseModel + : qrisStatusResponseModel // ignore: cast_nullable_to_non_nullable + as QrisStatusResponseModel, + )); + } +} + +/// @nodoc + +class _$StatusCheckImpl implements _StatusCheck { + const _$StatusCheckImpl(this.qrisStatusResponseModel); + + @override + final QrisStatusResponseModel qrisStatusResponseModel; + + @override + String toString() { + return 'QrisState.statusCheck(qrisStatusResponseModel: $qrisStatusResponseModel)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StatusCheckImpl && + (identical( + other.qrisStatusResponseModel, qrisStatusResponseModel) || + other.qrisStatusResponseModel == qrisStatusResponseModel)); + } + + @override + int get hashCode => Object.hash(runtimeType, qrisStatusResponseModel); + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$StatusCheckImplCopyWith<_$StatusCheckImpl> get copyWith => + __$$StatusCheckImplCopyWithImpl<_$StatusCheckImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(QrisResponseModel qrisResponseModel) qrisResponse, + required TResult Function(String message) success, + required TResult Function(String message) error, + required TResult Function(QrisStatusResponseModel qrisStatusResponseModel) + statusCheck, + }) { + return statusCheck(qrisStatusResponseModel); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + TResult? Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + }) { + return statusCheck?.call(qrisStatusResponseModel); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(QrisResponseModel qrisResponseModel)? qrisResponse, + TResult Function(String message)? success, + TResult Function(String message)? error, + TResult Function(QrisStatusResponseModel qrisStatusResponseModel)? + statusCheck, + required TResult orElse(), + }) { + if (statusCheck != null) { + return statusCheck(qrisStatusResponseModel); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_QrisResponse value) qrisResponse, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + required TResult Function(_StatusCheck value) statusCheck, + }) { + return statusCheck(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_QrisResponse value)? qrisResponse, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + TResult? Function(_StatusCheck value)? statusCheck, + }) { + return statusCheck?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_QrisResponse value)? qrisResponse, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + TResult Function(_StatusCheck value)? statusCheck, + required TResult orElse(), + }) { + if (statusCheck != null) { + return statusCheck(this); + } + return orElse(); + } +} + +abstract class _StatusCheck implements QrisState { + const factory _StatusCheck( + final QrisStatusResponseModel qrisStatusResponseModel) = + _$StatusCheckImpl; + + QrisStatusResponseModel get qrisStatusResponseModel; + + /// Create a copy of QrisState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$StatusCheckImplCopyWith<_$StatusCheckImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/home/bloc/qris/qris_event.dart b/lib/presentation/home/bloc/qris/qris_event.dart new file mode 100644 index 0000000..51ebd17 --- /dev/null +++ b/lib/presentation/home/bloc/qris/qris_event.dart @@ -0,0 +1,13 @@ +part of 'qris_bloc.dart'; + +@freezed +class QrisEvent with _$QrisEvent { + const factory QrisEvent.started() = _Started; + //generateQRCode + const factory QrisEvent.generateQRCode(String orderId, int grossAmount) = + _GenerateQRCode; + + //checkPaymentStatus + const factory QrisEvent.checkPaymentStatus(String orderId) = + _CheckPaymentStatus; +} diff --git a/lib/presentation/home/bloc/qris/qris_state.dart b/lib/presentation/home/bloc/qris/qris_state.dart new file mode 100644 index 0000000..592dd5d --- /dev/null +++ b/lib/presentation/home/bloc/qris/qris_state.dart @@ -0,0 +1,13 @@ +part of 'qris_bloc.dart'; + +@freezed +class QrisState with _$QrisState { + const factory QrisState.initial() = _Initial; + const factory QrisState.loading() = _Loading; + const factory QrisState.qrisResponse(QrisResponseModel qrisResponseModel) = + _QrisResponse; + const factory QrisState.success(String message) = _Success; + const factory QrisState.error(String message) = _Error; + const factory QrisState.statusCheck( + QrisStatusResponseModel qrisStatusResponseModel) = _StatusCheck; +} diff --git a/lib/presentation/home/bloc/status_table/status_table_bloc.dart b/lib/presentation/home/bloc/status_table/status_table_bloc.dart new file mode 100644 index 0000000..840fb4b --- /dev/null +++ b/lib/presentation/home/bloc/status_table/status_table_bloc.dart @@ -0,0 +1,19 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'status_table_event.dart'; +part 'status_table_state.dart'; +part 'status_table_bloc.freezed.dart'; + +class StatusTableBloc extends Bloc { + final ProductLocalDatasource datasource; + StatusTableBloc(this.datasource) : super(StatusTableState.initial()) { + on<_StatusTable>((event, emit) async { + emit(_Loading()); + await datasource.updateStatusTable(event.table); + emit(_Success()); + }); + } +} diff --git a/lib/presentation/home/bloc/status_table/status_table_bloc.freezed.dart b/lib/presentation/home/bloc/status_table/status_table_bloc.freezed.dart new file mode 100644 index 0000000..65bfc1a --- /dev/null +++ b/lib/presentation/home/bloc/status_table/status_table_bloc.freezed.dart @@ -0,0 +1,725 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'status_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$StatusTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) statusTabel, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? statusTabel, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? statusTabel, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_StatusTable value) statusTabel, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_StatusTable value)? statusTabel, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_StatusTable value)? statusTabel, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StatusTableEventCopyWith<$Res> { + factory $StatusTableEventCopyWith( + StatusTableEvent value, $Res Function(StatusTableEvent) then) = + _$StatusTableEventCopyWithImpl<$Res, StatusTableEvent>; +} + +/// @nodoc +class _$StatusTableEventCopyWithImpl<$Res, $Val extends StatusTableEvent> + implements $StatusTableEventCopyWith<$Res> { + _$StatusTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of StatusTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$StatusTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of StatusTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'StatusTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) statusTabel, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? statusTabel, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? statusTabel, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_StatusTable value) statusTabel, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_StatusTable value)? statusTabel, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_StatusTable value)? statusTabel, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements StatusTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$StatusTableImplCopyWith<$Res> { + factory _$$StatusTableImplCopyWith( + _$StatusTableImpl value, $Res Function(_$StatusTableImpl) then) = + __$$StatusTableImplCopyWithImpl<$Res>; + @useResult + $Res call({TableModel table}); +} + +/// @nodoc +class __$$StatusTableImplCopyWithImpl<$Res> + extends _$StatusTableEventCopyWithImpl<$Res, _$StatusTableImpl> + implements _$$StatusTableImplCopyWith<$Res> { + __$$StatusTableImplCopyWithImpl( + _$StatusTableImpl _value, $Res Function(_$StatusTableImpl) _then) + : super(_value, _then); + + /// Create a copy of StatusTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? table = null, + }) { + return _then(_$StatusTableImpl( + null == table + ? _value.table + : table // ignore: cast_nullable_to_non_nullable + as TableModel, + )); + } +} + +/// @nodoc + +class _$StatusTableImpl implements _StatusTable { + const _$StatusTableImpl(this.table); + + @override + final TableModel table; + + @override + String toString() { + return 'StatusTableEvent.statusTabel(table: $table)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$StatusTableImpl && + (identical(other.table, table) || other.table == table)); + } + + @override + int get hashCode => Object.hash(runtimeType, table); + + /// Create a copy of StatusTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$StatusTableImplCopyWith<_$StatusTableImpl> get copyWith => + __$$StatusTableImplCopyWithImpl<_$StatusTableImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) statusTabel, + }) { + return statusTabel(table); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? statusTabel, + }) { + return statusTabel?.call(table); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? statusTabel, + required TResult orElse(), + }) { + if (statusTabel != null) { + return statusTabel(table); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_StatusTable value) statusTabel, + }) { + return statusTabel(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_StatusTable value)? statusTabel, + }) { + return statusTabel?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_StatusTable value)? statusTabel, + required TResult orElse(), + }) { + if (statusTabel != null) { + return statusTabel(this); + } + return orElse(); + } +} + +abstract class _StatusTable implements StatusTableEvent { + const factory _StatusTable(final TableModel table) = _$StatusTableImpl; + + TableModel get table; + + /// Create a copy of StatusTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$StatusTableImplCopyWith<_$StatusTableImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$StatusTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $StatusTableStateCopyWith<$Res> { + factory $StatusTableStateCopyWith( + StatusTableState value, $Res Function(StatusTableState) then) = + _$StatusTableStateCopyWithImpl<$Res, StatusTableState>; +} + +/// @nodoc +class _$StatusTableStateCopyWithImpl<$Res, $Val extends StatusTableState> + implements $StatusTableStateCopyWith<$Res> { + _$StatusTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of StatusTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$StatusTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of StatusTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'StatusTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements StatusTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$StatusTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of StatusTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'StatusTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements StatusTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$StatusTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of StatusTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(); + + @override + String toString() { + return 'StatusTableState.success()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SuccessImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() success, + }) { + return success(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? success, + }) { + return success?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? success, + required TResult orElse(), + }) { + if (success != null) { + return success(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements StatusTableState { + const factory _Success() = _$SuccessImpl; +} diff --git a/lib/presentation/home/bloc/status_table/status_table_event.dart b/lib/presentation/home/bloc/status_table/status_table_event.dart new file mode 100644 index 0000000..09f8b8d --- /dev/null +++ b/lib/presentation/home/bloc/status_table/status_table_event.dart @@ -0,0 +1,9 @@ +part of 'status_table_bloc.dart'; + +@freezed +class StatusTableEvent with _$StatusTableEvent { + const factory StatusTableEvent.started() = _Started; + const factory StatusTableEvent.statusTabel( + TableModel table, + ) = _StatusTable; +} diff --git a/lib/presentation/home/bloc/status_table/status_table_state.dart b/lib/presentation/home/bloc/status_table/status_table_state.dart new file mode 100644 index 0000000..edacb2f --- /dev/null +++ b/lib/presentation/home/bloc/status_table/status_table_state.dart @@ -0,0 +1,8 @@ +part of 'status_table_bloc.dart'; + +@freezed +class StatusTableState with _$StatusTableState { + const factory StatusTableState.initial() = _Initial; + const factory StatusTableState.loading() = _Loading; + const factory StatusTableState.success() = _Success; +} diff --git a/lib/presentation/home/dialog/discount_dialog.dart b/lib/presentation/home/dialog/discount_dialog.dart new file mode 100644 index 0000000..30ecb8b --- /dev/null +++ b/lib/presentation/home/dialog/discount_dialog.dart @@ -0,0 +1,98 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; + +import '../../../core/constants/colors.dart'; +import '../../setting/bloc/discount/discount_bloc.dart'; + +class DiscountDialog extends StatefulWidget { + const DiscountDialog({super.key}); + + @override + State createState() => _DiscountDialogState(); +} + +class _DiscountDialogState extends State { + @override + void initState() { + context.read().add(const DiscountEvent.getDiscounts()); + super.initState(); + } + + int discountIdSelected = 0; + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Stack( + alignment: Alignment.center, + children: [ + const Text( + 'DISKON', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + Align( + alignment: Alignment.centerRight, + child: IconButton( + onPressed: () { + context.pop(); + }, + icon: const Icon( + Icons.cancel, + color: AppColors.primary, + size: 30.0, + ), + ), + ), + ], + ), + content: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const SizedBox.shrink(), + loading: () => const Center( + child: CircularProgressIndicator(), + ), + loaded: (discounts) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: discounts + .map( + (discount) => ListTile( + title: Text('Nama Diskon: ${discount.name}'), + subtitle: Text('Potongan harga (${discount.value}%)'), + contentPadding: EdgeInsets.zero, + textColor: AppColors.primary, + trailing: Checkbox( + value: discount.id == discountIdSelected, + onChanged: (value) { + setState(() { + discountIdSelected = discount.id!; + context.read().add( + CheckoutEvent.addDiscount( + discount, + ), + ); + }); + }, + ), + onTap: () { + // context.pop(); + }, + ), + ) + .toList(), + ); + }, + ); + }, + ), + ); + } +} diff --git a/lib/presentation/home/dialog/payment_qris_dialog.dart b/lib/presentation/home/dialog/payment_qris_dialog.dart new file mode 100644 index 0000000..483545b --- /dev/null +++ b/lib/presentation/home/dialog/payment_qris_dialog.dart @@ -0,0 +1,282 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:async'; +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; +import 'package:intl/intl.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/presentation/home/bloc/qris/qris_bloc.dart'; +import 'package:enaklo_pos/presentation/home/widgets/success_payment_dialog.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_order/sync_order_bloc.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; +import 'package:widgets_to_image/widgets_to_image.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; + +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../bloc/order/order_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; + +class PaymentQrisDialog extends StatefulWidget { + final List items; + final int discount; + final int discountAmount; + final int tax; + final int serviceCharge; + final int paymentAmount; + final String customerName; + final int tableNumber; + final String status; + final String paymentStatus; + final String paymentMethod; + final int price; + final int totalQty; + final int subTotal; + final bool? isTablePaymentPage; + const PaymentQrisDialog({ + super.key, + required this.items, + required this.discount, + required this.discountAmount, + required this.tax, + required this.serviceCharge, + required this.paymentAmount, + required this.customerName, + required this.tableNumber, + required this.status, + required this.paymentStatus, + required this.paymentMethod, + required this.price, + required this.totalQty, + required this.subTotal, + this.isTablePaymentPage = false, + }); + + @override + State createState() => _PaymentQrisDialogState(); +} + +class _PaymentQrisDialogState extends State { + String orderId = ''; + Timer? timer; + + WidgetsToImageController controller = WidgetsToImageController(); + @override + void initState() { + orderId = DateTime.now().millisecondsSinceEpoch.toString(); + context.read().add(QrisEvent.generateQRCode( + orderId, + widget.price, + )); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + scrollable: true, + contentPadding: const EdgeInsets.all(0), + backgroundColor: AppColors.primary, + content: SizedBox( + width: context.deviceWidth * 0.4, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding( + padding: EdgeInsets.all(12.0), + child: Text( + 'Pembayaran QRIS', + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontFamily: 'Quicksand', + fontWeight: FontWeight.w700, + height: 0, + ), + ), + ), + const SpaceHeight(6.0), + Container( + width: context.deviceWidth, + padding: const EdgeInsets.all(14.0), + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(20.0)), + color: AppColors.white, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + BlocListener( + listener: (context, state) { + state.maybeWhen(orElse: () { + return; + }, qrisResponse: (data) { + const onSec = Duration(seconds: 5); + timer = Timer.periodic(onSec, (timer) { + context + .read() + .add(QrisEvent.checkPaymentStatus( + orderId.toString(), + )); + }); + }, success: (message) async { + context.read().add(OrderEvent.order( + widget.items, + widget.discount, + widget.discountAmount, + widget.tax, + widget.serviceCharge, + widget.paymentAmount, + widget.customerName, + widget.tableNumber, + 'completed', + 'paid', + 'Qris', + widget.price, + OrderType.dineIn)); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => SuccessPaymentDialog( + isTablePaymentPage: widget.isTablePaymentPage, + data: widget.items, + totalQty: widget.totalQty, + totalPrice: widget.price, + totalTax: widget.tax, + totalDiscount: widget.discountAmount, + subTotal: widget.subTotal, + normalPrice: widget.price, + totalService: widget.serviceCharge, + draftName: widget.customerName, + ), + ); + }); + }, + child: BlocBuilder( + builder: (context, state) { + log('state: $state'); + return state.maybeWhen( + orElse: () { + return const SizedBox(); + }, + qrisResponse: (data) { + log("URL: ${data.actions!.first.url!}"); + return WidgetsToImage( + controller: controller, + child: Container( + width: 340.0, + // height: 256.0, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20.0), + color: Colors.white, + ), + child: Column( + children: [ + Center( + child: Image.network( + data.actions!.first.url!, + ), + ), + // const SpaceHeight(5.0), + Text( + NumberFormat.currency( + locale: 'id', + symbol: 'Rp ', + ).format(widget.price), + style: const TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold), + ), + ], + ), + ), + ); + }, + loading: () { + return Container( + width: 256.0, + height: 256.0, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(20.0), + color: Colors.white, + ), + child: const Center( + child: CircularProgressIndicator( + color: AppColors.white, + ), + ), + ); + }, + ); + }, + ), + ), + const SpaceHeight(12.0), + const Text( + 'Scan QRIS to make payment', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 14, + ), + ), + const SpaceHeight(12.0), + //button print qr + ElevatedButton( + onPressed: () async { + try { + final sizeReceipt = await AuthLocalDataSource().getSizeReceipt(); + final bytes = await controller.capture(); + final printValue = await PrintDataoutputs.instance + .printQRIS(widget.price, bytes!, int.parse(sizeReceipt)); + + // Get the receipt printer to print QRIS + final receiptPrinter = await ProductLocalDatasource.instance + .getPrinterByCode('receipt'); + + if (receiptPrinter != null) { + await PrinterService().printWithPrinter( + receiptPrinter, + printValue, + context + ); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('No receipt printer configured')), + ); + } + } catch (e) { + log("Error printing QRIS: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing QRIS: $e')), + ); + } + }, + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.primary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + child: const Text( + 'Print QRIS', + style: TextStyle( + color: Colors.white, + fontSize: 16, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/home/dialog/service_dialog.dart b/lib/presentation/home/dialog/service_dialog.dart new file mode 100644 index 0000000..8d76cd6 --- /dev/null +++ b/lib/presentation/home/dialog/service_dialog.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; + +import '../../../core/constants/colors.dart'; + +class ServiceDialog extends StatelessWidget { + const ServiceDialog({super.key}); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Stack( + alignment: Alignment.center, + children: [ + const Text( + 'LAYANAN', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + Align( + alignment: Alignment.centerRight, + child: IconButton( + onPressed: () => context.pop(), + icon: const Icon( + Icons.cancel, + color: AppColors.primary, + size: 30.0, + ), + ), + ), + ], + ), + content: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + initial: () => const SizedBox(), + loading: () => const Center(child: CircularProgressIndicator()), + loaded: (data, a, b, c, d, service, e, f, g, orderType) => ListTile( + title: Text('Presentase ($service%)'), + subtitle: const Text('Biaya layanan'), + contentPadding: EdgeInsets.zero, + textColor: AppColors.primary, + trailing: Checkbox( + value: service > 0, + onChanged: (value) { + context.read().add( + CheckoutEvent.addServiceCharge(service > 0 ? 0 : service), + ); + }, + ), + onTap: () { + context.pop(); + }, + ), + orElse: () => const SizedBox(), + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/presentation/home/dialog/tax_dialog.dart b/lib/presentation/home/dialog/tax_dialog.dart new file mode 100644 index 0000000..dea83a1 --- /dev/null +++ b/lib/presentation/home/dialog/tax_dialog.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + +import '../../../core/constants/colors.dart'; +import '../bloc/checkout/checkout_bloc.dart'; + +class TaxDialog extends StatelessWidget { + const TaxDialog({super.key}); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Stack( + alignment: Alignment.center, + children: [ + const Text( + 'PAJAK PB1', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + Align( + alignment: Alignment.centerRight, + child: IconButton( + onPressed: () => context.pop(), + icon: const Icon( + Icons.cancel, + color: AppColors.primary, + size: 30.0, + ), + ), + ), + ], + ), + content: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + initial: () => const SizedBox(), + loading: () => const Center(child: CircularProgressIndicator()), + loaded: (data, a, b, c, tax, d, e, f, g, orderType) => ListTile( + title: const Text('PB1'), + subtitle: Text('tarif pajak ($tax%)'), + contentPadding: EdgeInsets.zero, + textColor: AppColors.primary, + trailing: Checkbox( + value: tax > 0, + onChanged: (value) { + context.read().add( + CheckoutEvent.addTax(tax > 0 ? 0 : tax), + ); + }, + ), + onTap: () { + context.pop(); + }, + ), + orElse: () => const SizedBox(), + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/presentation/home/models/order_item.dart b/lib/presentation/home/models/order_item.dart new file mode 100644 index 0000000..4e81869 --- /dev/null +++ b/lib/presentation/home/models/order_item.dart @@ -0,0 +1,31 @@ +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +import 'product_model.dart'; + +class OrderItem { + final Product product; + int quantity; + OrderItem({ + required this.product, + required this.quantity, + }); + + factory OrderItem.fromMap(Map map) { + return OrderItem( + product: Product.fromMap(map['product']), + quantity: map['quantity']?.toInt() ?? 0, + ); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is OrderItem && + other.product == product && + other.quantity == quantity; + } + + @override + int get hashCode => product.hashCode ^ quantity.hashCode; +} diff --git a/lib/presentation/home/models/order_model.dart b/lib/presentation/home/models/order_model.dart new file mode 100644 index 0000000..9d5f94f --- /dev/null +++ b/lib/presentation/home/models/order_model.dart @@ -0,0 +1,211 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:convert'; + +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; + +// id INTEGER PRIMARY KEY AUTOINCREMENT, +// sub_total INTEGER, +// tax INTEGER, +// discount INTEGER, +// service_charge INTEGER, +// total INTEGER, +// payment_method TEXT, +// total_item INTEGER, +// id_kasir INTEGER, +// nama_kasir TEXT, +// transaction_time TEXT, +// is_sync INTEGER DEFAULT 0 + +class OrderModel { + final int? id; + //payment_amount + final int paymentAmount; + final int subTotal; + final int tax; + final int discount; + final int discountAmount; + final int serviceCharge; + final int total; + final String paymentMethod; + final int totalItem; + final int idKasir; + final String namaKasir; + final String transactionTime; + final String customerName; + final int tableNumber; + final String status; + final String paymentStatus; + final int isSync; + final List orderItems; + final OrderType orderType; + OrderModel({ + this.id, + required this.paymentAmount, + required this.subTotal, + required this.tax, + required this.discount, + required this.discountAmount, + required this.serviceCharge, + required this.total, + required this.paymentMethod, + required this.totalItem, + required this.idKasir, + required this.namaKasir, + required this.transactionTime, + required this.customerName, + required this.tableNumber, + required this.status, + required this.paymentStatus, + required this.isSync, + required this.orderItems, + this.orderType = OrderType.dineIn, + }); + + // 'payment_amount' => 'required', + // 'sub_total' => 'required', + // 'tax' => 'required', + // 'discount' => 'required', + // 'service_charge' => 'required', + // 'total' => 'required', + // 'payment_method' => 'required', + // 'total_item' => 'required', + // 'id_kasir' => 'required', + // 'nama_kasir' => 'required', + // 'transaction_time' => 'required', + // 'order_items' => 'required' + + Map toServerMap() { + return { + 'payment_amount': paymentAmount, + 'sub_total': subTotal, + 'tax': tax, + 'discount': discount, + 'discount_amount': discountAmount, + 'service_charge': serviceCharge, + 'total': total, + 'payment_method': paymentMethod, + 'total_item': totalItem, + 'id_kasir': idKasir, + 'nama_kasir': namaKasir, + 'customer_name': customerName, + 'table_number': tableNumber, + 'status': status, + 'payment_status': paymentStatus, + 'transaction_time': transactionTime, + 'order_type': orderType.value, + 'order_items': orderItems.map((e) => e.toServerMap(id)).toList(), + }; + } + + Map toMap({bool includeOrderType = true}) { + final map = { + // 'id': id, + 'payment_amount': paymentAmount, + 'sub_total': subTotal, + 'tax': tax, + 'discount': discount, + 'discount_amount': discountAmount, + 'service_charge': serviceCharge, + 'total': total, + 'payment_method': paymentMethod, + 'total_item': totalItem, + 'id_kasir': 1, + 'nama_kasir': 'Kasir', + 'transaction_time': transactionTime, + 'customer_name': customerName, + 'table_number': tableNumber, + 'status': status, + 'payment_status': paymentStatus, + 'is_sync': isSync, + }; + + if (includeOrderType) { + map['order_type'] = orderType.value; + } + + return map; + } + + factory OrderModel.fromMap(Map map) { + print("Discount AMount${map['discount_amount']}"); + return OrderModel( + id: map['id']?.toInt(), + paymentAmount: map['payment_amount']?.toInt() ?? 0, + subTotal: map['sub_total']?.toInt() ?? 0, + tax: map['tax']?.toInt() ?? 0, + discount: map['discount']?.toInt() ?? 0, + discountAmount: map['discount_amount']?.toInt() ?? 0, + serviceCharge: map['service_charge']?.toInt() ?? 0, + total: map['total']?.toInt() ?? 0, + paymentMethod: map['payment_method'] ?? '', + totalItem: map['total_item']?.toInt() ?? 0, + idKasir: map['id_kasir']?.toInt() ?? 0, + namaKasir: map['nama_kasir'] ?? '', + transactionTime: map['transaction_time'] ?? '', + isSync: map['is_sync']?.toInt() ?? 0, + customerName: map['customer_name'] ?? '', + tableNumber: map['table_number']?.toInt() ?? 0, + status: map['status'] ?? '', + paymentStatus: map['payment_status'] ?? '', + orderType: OrderType.fromString(map['order_type'] ?? 'DINE IN'), + orderItems: [], + ); + } + + String toJson() => json.encode(toServerMap()); + + factory OrderModel.fromJson(String source) => + OrderModel.fromMap(json.decode(source)); + + OrderModel copyWith({ + int? id, + int? paymentAmount, + int? subTotal, + int? tax, + int? discount, + int? discountAmount, + int? serviceCharge, + int? total, + String? paymentMethod, + int? totalItem, + int? idKasir, + String? namaKasir, + String? transactionTime, + String? customerName, + int? tableNumber, + String? status, + String? paymentStatus, + int? isSync, + List? orderItems, + OrderType? orderType, + }) { + return OrderModel( + id: id ?? this.id, + paymentAmount: paymentAmount ?? this.paymentAmount, + subTotal: subTotal ?? this.subTotal, + tax: tax ?? this.tax, + discount: discount ?? this.discount, + discountAmount: discountAmount ?? this.discountAmount, + serviceCharge: serviceCharge ?? this.serviceCharge, + total: total ?? this.total, + paymentMethod: paymentMethod ?? this.paymentMethod, + totalItem: totalItem ?? this.totalItem, + idKasir: idKasir ?? this.idKasir, + namaKasir: namaKasir ?? this.namaKasir, + transactionTime: transactionTime ?? this.transactionTime, + customerName: customerName ?? this.customerName, + tableNumber: tableNumber ?? this.tableNumber, + status: status ?? this.status, + paymentStatus: paymentStatus ?? this.paymentStatus, + isSync: isSync ?? this.isSync, + orderItems: orderItems ?? this.orderItems, + orderType: orderType ?? this.orderType, + ); + } + + @override + String toString() { + return 'OrderModel(id: $id, paymentAmount: $paymentAmount, subTotal: $subTotal, tax: $tax, discount: $discount, discountAmount: $discountAmount, serviceCharge: $serviceCharge, total: $total, paymentMethod: $paymentMethod, totalItem: $totalItem, idKasir: $idKasir, namaKasir: $namaKasir, transactionTime: $transactionTime, customerName: $customerName, tableNumber: $tableNumber, status: $status, paymentStatus: $paymentStatus, isSync: $isSync, orderItems: $orderItems, orderType: $orderType)'; + } +} diff --git a/lib/presentation/home/models/order_type.dart b/lib/presentation/home/models/order_type.dart new file mode 100644 index 0000000..d9b4019 --- /dev/null +++ b/lib/presentation/home/models/order_type.dart @@ -0,0 +1,16 @@ +enum OrderType { + dineIn('DINE IN'), + takeAway('TAKE AWAY'), + grab('GRAB'), + delivery('DELIVERY'); + + final String value; + const OrderType(this.value); + + static OrderType fromString(String value) { + return OrderType.values.firstWhere( + (type) => type.value == value, + orElse: () => OrderType.dineIn, + ); + } +} \ No newline at end of file diff --git a/lib/presentation/home/models/product_category.dart b/lib/presentation/home/models/product_category.dart new file mode 100644 index 0000000..c774083 --- /dev/null +++ b/lib/presentation/home/models/product_category.dart @@ -0,0 +1,13 @@ +enum ProductCategory { + none('None'), + drink('Minuman'), + food('Makanan'), + snack('Snack'); + + final String value; + const ProductCategory(this.value); + + bool get isFood => this == ProductCategory.food; + bool get isDrink => this == ProductCategory.drink; + bool get isSnack => this == ProductCategory.snack; +} diff --git a/lib/presentation/home/models/product_model.dart b/lib/presentation/home/models/product_model.dart new file mode 100644 index 0000000..82f6fe5 --- /dev/null +++ b/lib/presentation/home/models/product_model.dart @@ -0,0 +1,43 @@ + +import 'package:enaklo_pos/core/extensions/int_ext.dart'; + +import 'product_category.dart'; + +class ProductModel { + final String image; + final String name; + final ProductCategory category; + final int price; + final int stock; + + ProductModel({ + required this.image, + required this.name, + required this.category, + required this.price, + required this.stock, + }); + + String get priceFormat => price.currencyFormatRp; + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is ProductModel && + other.image == image && + other.name == name && + other.category == category && + other.price == price && + other.stock == stock; + } + + @override + int get hashCode { + return image.hashCode ^ + name.hashCode ^ + category.hashCode ^ + price.hashCode ^ + stock.hashCode; + } +} diff --git a/lib/presentation/home/models/product_quantity.dart b/lib/presentation/home/models/product_quantity.dart new file mode 100644 index 0000000..335ccdb --- /dev/null +++ b/lib/presentation/home/models/product_quantity.dart @@ -0,0 +1,94 @@ +import 'dart:convert'; +import 'dart:developer'; + +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +class ProductQuantity { + final Product product; + int quantity; + String notes; + ProductQuantity({ + required this.product, + required this.quantity, + this.notes = '', + }); + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + + return other is ProductQuantity && + other.product == product && + other.quantity == quantity && + other.notes == notes; + } + + @override + int get hashCode => product.hashCode ^ quantity.hashCode ^ notes.hashCode; + + Map toMap() { + return { + 'product': product.toMap(), + 'quantity': quantity, + 'notes': notes, + }; + } + + Map toLocalMap(int orderId) { + log("OrderProductId: ${product.id}"); + + return { + 'id_order': orderId, + 'id_product': product.productId, + 'quantity': quantity, + 'price': product.price, + 'notes': notes, + }; + } + + Map toServerMap(int? orderId) { + log("toServerMap: ${product.productId}"); + + return { + 'id_order': orderId ?? 0, + 'id_product': product.productId, + 'quantity': quantity, + 'price': product.price, + 'notes': notes, + }; + } + + factory ProductQuantity.fromMap(Map map) { + return ProductQuantity( + product: Product.fromMap(map['product']), + quantity: map['quantity']?.toInt() ?? 0, + notes: map['notes'] ?? '', + ); + } + + factory ProductQuantity.fromLocalMap(Map map) { + log("ProductQuantity: $map"); + return ProductQuantity( + product: Product.fromOrderMap(map), + quantity: map['quantity']?.toInt() ?? 0, + notes: map['notes'] ?? '', + ); + } + + String toJson() => json.encode(toMap()); + + factory ProductQuantity.fromJson(String source) => + ProductQuantity.fromMap(json.decode(source)); + + ProductQuantity copyWith({ + Product? product, + int? quantity, + String? notes, + }) { + return ProductQuantity( + product: product ?? this.product, + quantity: quantity ?? this.quantity, + notes: notes ?? this.notes, + ); + } +} diff --git a/lib/presentation/home/pages/confirm_payment_page.dart b/lib/presentation/home/pages/confirm_payment_page.dart new file mode 100644 index 0000000..5f8863c --- /dev/null +++ b/lib/presentation/home/pages/confirm_payment_page.dart @@ -0,0 +1,1697 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/order/order_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/payment_methods/payment_methods_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; +import 'package:enaklo_pos/presentation/home/widgets/save_order_dialog.dart'; +import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../widgets/order_menu.dart'; +import '../widgets/success_payment_dialog.dart'; +import '../widgets/order_type_selector.dart'; + +class ConfirmPaymentPage extends StatefulWidget { + final bool isTable; + final TableModel? table; + + const ConfirmPaymentPage({ + Key? key, + required this.isTable, + this.table, + }) : super(key: key); + + @override + State createState() => _ConfirmPaymentPageState(); +} + +class _ConfirmPaymentPageState extends State { + final totalPriceController = TextEditingController(); + final customerController = TextEditingController(); + bool isPayNow = true; + bool isAddToOrder = false; + PaymentMethod? selectedPaymentMethod; + TableModel? selectTable; + int discountAmount = 0; + int priceValue = 0; + int uangPas = 0; + int uangPas2 = 0; + int uangPas3 = 0; + + // int discountAmountValue = 0; + int totalPriceFinal = 0; + + // int taxFinal = 0; + // int serviceChargeFinal = 0; + + @override + void initState() { + // Fetch available tables by default + context + .read() + .add(GetTableStatusEvent.getTablesStatus('available')); + context + .read() + .add(PaymentMethodsEvent.fetchPaymentMethods()); + + // Set a default payment method in case API fails + selectedPaymentMethod = PaymentMethod( + id: 1, + name: 'Cash', + description: 'Cash payment', + isActive: true, + sortOrder: 1, + ); + // if (selectTable == null && widget.table != null) { + // selectTable = tables.firstWhere( + // (t) => t.id == widget.table!.id, + // orElse: () => null, + // ); + // } + if (widget.table != null) { + // selectTable = TableModel( + // tableNumber: widget.table!.tableNumber, + // startTime: widget.table!.startTime, + // status: widget.table!.status, + // orderId: widget.table!.orderId, + // paymentAmount: widget.table!.paymentAmount, + // position: widget.table!.position, + // ); + } + super.initState(); + } + + @override + void dispose() { + totalPriceController.dispose(); + customerController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Hero( + tag: 'payment_confirmation_screen', + child: Scaffold( + body: Row( + children: [ + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Konfirmasi', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + Text( + widget.isTable + ? 'Orders Table ${widget.table?.tableName}' + : 'Orders #1', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ], + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(24.0), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Item', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + SizedBox( + width: 160, + ), + SizedBox( + width: 50.0, + child: Text( + 'Qty', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + child: Text( + 'Price', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SpaceHeight(8), + const Divider(), + const SpaceHeight(8), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: Text('No Items'), + ), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + OrderMenu(data: products[index]), + separatorBuilder: (context, index) => + const SpaceHeight(12.0), + itemCount: products.length, + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Sub total', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + )); + return Text( + price.currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Diskon', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final subTotal = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + )); + + final finalDiscount = discount / 100 * subTotal; + discountAmount = finalDiscount.toInt(); + return Text( + '$discount % (${finalDiscount.toInt().currencyFormatRp})', + style: TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Pajak PB1', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final subTotal = + price - (discount / 100 * price); + final finalTax = subTotal * (tax / 100); + final finalDiscount = discount / 100 * subTotal; + // discountAmountValue = finalDiscount.toInt(); + // taxFinal = finalTax.toInt(); + return Text( + '$tax % (${finalTax.toInt().currencyFormatRp})', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Biaya Layanan', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final nominalServiceCharge = + (serviceCharge / 100) * + (price - discountAmount); + + // serviceChargeFinal = + // nominalServiceCharge.toInt(); + return Text( + '$serviceCharge % (${nominalServiceCharge.toInt().currencyFormatRp})', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(10.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total', + style: TextStyle( + color: AppColors.grey, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final subTotal = + price - (discount / 100 * price); + final finalTax = subTotal * (tax / 100); + final service = + (serviceCharge / 100) * subTotal; + final total = subTotal + finalTax + service; + priceValue = total.toInt(); + totalPriceController.text = + total.ceil().currencyFormatRpV2; + uangPas = total.ceil(); + uangPas2 = uangPas ~/ 50000 * 50000 + 50000; + uangPas3 = uangPas ~/ 50000 * 50000 + 100000; + totalPriceFinal = total.ceil(); + // log("totalPriceFinal: $totalPriceFinal"); + return Text( + total.ceil().currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + fontSize: 16, + ), + ); + }, + ), + ], + ), + ], + ), + ), + ), + ), + Expanded( + flex: 3, + child: Align( + alignment: Alignment.topCenter, + child: ListView( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.isTable != true) ...[ + const Text( + 'Pembayaran', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + isPayNow && !isAddToOrder + ? Button.filled( + height: 52.0, + width: 200.0, + onPressed: () { + isPayNow = true; + isAddToOrder = false; + setState(() {}); + }, + label: 'Bayar Sekarang', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () { + isPayNow = true; + isAddToOrder = false; + setState(() {}); + }, + label: 'Bayar Sekarang'), + SpaceWidth(8), + !isPayNow && !isAddToOrder + ? Button.filled( + width: 200.0, + height: 52.0, + onPressed: () async { + print( + "🔘 Bayar Nanti button pressed (filled)"); + print( + "🔘 Fetching available tables for Bayar Nanti"); + isPayNow = false; + isAddToOrder = false; + + // Debug: Check all tables first + final allTables = await ProductLocalDatasource.instance.getAllTable(); + print("🔘 All tables in database: ${allTables.length}"); + allTables.forEach((table) { + print("🔘 Table: ${table.tableName} - Status: ${table.status} - ID: ${table.id}"); + }); + + // Fetch available tables for Bayar Nanti + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'available'), + ); + setState(() {}); + }, + label: 'Bayar Nanti', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () async { + print( + "🔘 Bayar Nanti button pressed (outlined)"); + print( + "🔘 Fetching available tables for Bayar Nanti"); + isPayNow = false; + isAddToOrder = false; + + // Debug: Check all tables first + final allTables = await ProductLocalDatasource.instance.getAllTable(); + print("🔘 All tables in database: ${allTables.length}"); + allTables.forEach((table) { + print("🔘 Table: ${table.tableName} - Status: ${table.status} - ID: ${table.id}"); + }); + + // Fetch available tables for Bayar Nanti + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'available'), + ); + setState(() {}); + }, + label: 'Bayar Nanti'), + SpaceWidth(8), + isAddToOrder + ? Button.filled( + width: 200.0, + height: 52.0, + onPressed: () { + isPayNow = false; + isAddToOrder = true; + setState(() {}); + }, + label: 'Tambah ke Pesanan', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () { + print( + "🔘 Tambah button pressed (outlined)"); + print( + "🔘 Fetching occupied tables for Tambah ke Pesanan"); + isPayNow = false; + isAddToOrder = true; + // Fetch occupied tables for Tambah ke Pesanan + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'occupied'), + ); + setState(() {}); + }, + label: 'Tambah ke Pesanan', + ), + ], + ), + ), + ], + const SpaceHeight(8.0), + if (!isPayNow && !isAddToOrder) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Pilih Meja', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => + const CircularProgressIndicator(), + success: (tables) { + print( + "🔘 Tables fetched: ${tables.length} tables"); + print( + "🔘 Table statuses: ${tables.map((t) => '${t.tableName}: ${t.status}').join(', ')}"); + print( + "🔘 Current mode: ${!isPayNow && !isAddToOrder ? 'Pay Later' : isAddToOrder ? 'Add to Order' : 'Pay Now'}"); + // No need to filter since we're fetching the correct tables directly + final availableTables = tables; + + if (selectTable == null && + availableTables.isNotEmpty) { + selectTable = availableTables.first; + } + + if (availableTables.isEmpty) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.orange[50], + borderRadius: + BorderRadius.circular(16), + border: Border.all( + color: Colors.orange, + width: 1, + ), + ), + child: const Text( + 'Tidak ada meja yang tersedia. Silakan pilih opsi lain.', + style: + TextStyle(color: Colors.orange), + ), + ); + } + + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: Theme.of(context).primaryColor, + width: 2, + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + isExpanded: true, + value: selectTable, + onChanged: (TableModel? newValue) { + setState(() { + selectTable = newValue; + }); + }, + items: availableTables + .map< + DropdownMenuItem>( + (TableModel value) => + DropdownMenuItem< + TableModel>( + value: value, + child: Text(value.tableName), + ), + ) + .toList(), + ), + ), + ); + }, + ); + }), + ], + const SpaceHeight(8.0), + if (isAddToOrder) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Pilih Meja yang Sudah Ada Pesanan', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => + const CircularProgressIndicator(), + success: (tables) { + print( + "🔘 Add to Order - Tables fetched: ${tables.length} tables"); + print( + "🔘 Add to Order - Table statuses: ${tables.map((t) => '${t.tableName}: ${t.status}').join(', ')}"); + // No need to filter since we're fetching occupied tables directly + final occupiedTables = tables; + + if (selectTable == null && + occupiedTables.isNotEmpty) { + selectTable = occupiedTables.first; + } + + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: Theme.of(context).primaryColor, + width: 2, + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + isExpanded: true, + value: selectTable, + onChanged: (TableModel? newValue) { + setState(() { + selectTable = newValue; + }); + }, + items: occupiedTables + .map< + DropdownMenuItem>( + (TableModel value) => + DropdownMenuItem< + TableModel>( + value: value, + child: Text( + '${value.tableName} (Occupied)'), + ), + ) + .toList(), + ), + ), + ); + }, + ); + }), + ], + if (!isAddToOrder) ...[ + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Customer', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + TextFormField( + controller: customerController, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + ), + hintText: 'Nama Customer', + ), + textCapitalization: TextCapitalization.words, + ), + ], + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const OrderTypeSelector(), + const SpaceHeight(8.0), + if (isPayNow) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Metode Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + loading: () => const Center( + child: Column( + children: [ + CircularProgressIndicator(), + SizedBox(height: 8.0), + Text('Loading payment methods...'), + ], + ), + ), + error: (message) => Column( + children: [ + Center( + child: Text( + 'Error loading payment methods: $message'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent + .fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ), + loaded: (paymentMethods) { + log("Loaded ${paymentMethods.length} payment methods"); + paymentMethods.forEach((method) { + log("Payment method: ${method.name} (ID: ${method.id})"); + }); + if (paymentMethods.isEmpty) { + return Column( + children: [ + const Center( + child: Text( + 'No payment methods available'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent + .fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ); + } + + // Set default selected payment method if none selected or if current selection is not in the list + if (selectedPaymentMethod == null || + !paymentMethods.any((method) => + method.id == + selectedPaymentMethod?.id)) { + selectedPaymentMethod = + paymentMethods.first; + } + + return Wrap( + spacing: 12.0, + runSpacing: 8.0, + children: paymentMethods.map((method) { + final isSelected = + selectedPaymentMethod?.id == + method.id; + return Container( + constraints: const BoxConstraints( + minWidth: 120.0, + ), + decoration: isSelected + ? BoxDecoration( + border: Border.all( + color: AppColors.primary, + width: 2.0, + ), + borderRadius: + BorderRadius.circular( + 8.0), + ) + : null, + child: Tooltip( + message: method.description ?? + 'No description available', + child: isSelected + ? Button.filled( + width: double.infinity, + height: 50.0, + onPressed: () { + setState(() { + selectedPaymentMethod = + method; + }); + }, + label: method.name + ?.isNotEmpty == + true + ? method.name! + : 'Unknown', + ) + : Button.outlined( + width: double.infinity, + height: 50.0, + onPressed: () { + setState(() { + selectedPaymentMethod = + method; + }); + }, + label: method.name + ?.isNotEmpty == + true + ? method.name! + : 'Unknown', + ), + ), + ); + }).toList(), + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Total Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return TextFormField( + controller: totalPriceController, + keyboardType: TextInputType.number, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: + BorderRadius.circular(8.0), + ), + hintText: 'Total harga', + ), + onChanged: (value) { + priceValue = value.toIntegerFromText; + final int newValue = + value.toIntegerFromText; + totalPriceController.text = + newValue.currencyFormatRp; + totalPriceController.selection = + TextSelection.fromPosition( + TextPosition( + offset: totalPriceController + .text.length)); + }, + ); + }, + ), + const SpaceHeight(20.0), + BlocBuilder( + builder: (context, state) { + return Row( + children: [ + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas + .toString() + .currencyFormatRpV2; + priceValue = uangPas; + }, + label: 'UANG PAS', + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas2 + .toString() + .currencyFormatRpV2; + priceValue = uangPas2; + }, + label: uangPas2 + .toString() + .currencyFormatRpV2, + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas3 + .toString() + .currencyFormatRpV2; + priceValue = uangPas3; + }, + label: uangPas3 + .toString() + .currencyFormatRpV2, + ), + ], + ); + }, + ), + ] + ], + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: ColoredBox( + color: AppColors.white, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 24.0, vertical: 16.0), + child: Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () => context.pop(), + label: 'Kembali', + ), + ), + const SpaceWidth(8.0), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + savedDraftOrder: (orderDraftId) { + log("PRICEVALUE: ${priceValue}"); + + final newTabel = TableModel( + id: widget.isTable + ? widget.table!.id + : selectTable?.id, + tableName: widget.isTable + ? widget.table!.tableName + : selectTable?.tableName ?? + '0', + status: 'occupied', + paymentAmount: priceValue, + orderId: orderDraftId, + startTime: DateTime.now() + .toIso8601String(), + position: widget.isTable + ? widget.table!.position + : selectTable!.position); + log('new tabel: ${newTabel.toMap()}'); + context + .read() + .add(StatusTableEvent.statusTabel( + newTabel, + )); + }); + }, + child: + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + + final orderType = state.maybeWhen( + orElse: () => OrderType.dineIn, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + orderType, + ); + + final subTotal = + price - (discount / 100 * price); + final totalDiscount = + discount / 100 * price; + final finalTax = subTotal * (tax / 100); + final totalServiceCharge = + (serviceCharge / 100) * price; + + List items = + state.maybeWhen( + orElse: () => [], + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products, + ); + final totalQty = items.fold( + 0, + (previousValue, element) => + previousValue + element.quantity, + ); + + return Flexible( + child: Button.filled( + onPressed: () async { + print("🔘 Payment button pressed"); + print("🔘 isPayNow: $isPayNow"); + print( + "🔘 isAddToOrder: $isAddToOrder"); + print( + "🔘 selectedPaymentMethod: ${selectedPaymentMethod?.name}"); + if (selectedPaymentMethod == null) { + ScaffoldMessenger.of(context) + .showSnackBar( + const SnackBar( + content: Text( + 'Please select a payment method'), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (widget.isTable) { + log("discountAmountValue: $totalDiscount"); + context.read().add( + CheckoutEvent + .saveDraftOrder( + widget.isTable == true + ? widget.table!.id! + : selectTable!.id!, + customerController.text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + table: widget.table!, + draftName: + customerController.text, + ), + ); + } else if (isPayNow) { + log("🔘 Entering Pay Now flow"); + // context.read().add( + // OrderEvent.addPaymentMethod( + // items, + // totalPrice, + // finalTax, + // discount != null + // ? discount.value + // .replaceAll( + // '.00', '') + // .toIntegerFromText + // : 0, + // finalDiscountAmount, + // finalService, + // subTotal, + // totalPriceController.text + // .toIntegerFromText, + // auth?.user.name ?? '-', + // totalQuantity, + // auth?.user.id ?? 1, + // isCash + // ? 'Cash' + // : 'QR Pay')); + final paymentMethodName = + selectedPaymentMethod?.name + ?.toLowerCase() ?? + ''; + log("Selected payment method: ${selectedPaymentMethod?.name} (normalized: $paymentMethodName)"); + if (paymentMethodName == 'cash' || + paymentMethodName == + 'tunai' || + paymentMethodName == + 'uang tunai' || + paymentMethodName == + 'cash payment') { + log("🔘 Payment method is cash, proceeding with OrderBloc call"); + log("discountAmountValue: $totalDiscount"); + log("💳 About to call OrderBloc for cash payment"); + log("💳 OrderBloc instance: ${context.read()}"); + log("💳 About to dispatch OrderEvent.order for cash payment"); + context.read().add( + OrderEvent.order( + items, + discount, + totalDiscount.toInt(), + finalTax.toInt(), + 0, + totalPriceController + .text + .toIntegerFromText, + customerController.text, + 0, + 'completed', + 'paid', + selectedPaymentMethod + ?.name ?? + 'Cash', + totalPriceFinal, + orderType)); + log("💳 OrderEvent.order dispatched for cash payment"); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: + totalServiceCharge + .toInt(), + draftName: + customerController.text, + ), + ); + } else { + // Process non-cash payment directly without QRIS dialog + log("Processing non-cash payment: ${selectedPaymentMethod?.name}"); + log("💳 About to call OrderBloc for non-cash payment"); + log("💳 OrderBloc instance: ${context.read()}"); + context.read().add( + OrderEvent.order( + items, + discount, + totalDiscount.toInt(), + finalTax.toInt(), + 0, + totalPriceController + .text + .toIntegerFromText, + customerController.text, + 0, + 'completed', + 'paid', + selectedPaymentMethod + ?.name ?? + 'Unknown Payment Method', + totalPriceFinal, + orderType)); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: + totalServiceCharge + .toInt(), + draftName: + customerController.text, + ), + ); + } + } else if (isAddToOrder) { + // Tambahkan ke pesanan meja yang sudah ada + if (selectTable != null) { + // Ambil draft order yang sudah ada + final existingDraftOrder = + await ProductLocalDatasource + .instance + .getDraftOrderById( + selectTable! + .orderId ?? + 0); + + if (existingDraftOrder != + null) { + // Convert items ke DraftOrderItem + final newDraftItems = items + .map((item) => + DraftOrderItem( + product: + item.product, + quantity: + item.quantity, + )) + .toList(); + + // Gabungkan dengan pesanan yang sudah ada + final updatedItems = [ + ...existingDraftOrder + .orders, + ...newDraftItems + ]; + + final updatedDraftOrder = + existingDraftOrder + .copyWith( + orders: updatedItems, + totalQuantity: + updatedItems.fold( + 0, + (sum, item) => + sum + + item.quantity), + subTotal: updatedItems.fold< + int>( + 0, + (sum, item) => + sum + + (int.tryParse(item + .product + .price ?? + '0') ?? + 0) * + item.quantity), + ); + + // Update draft order + await ProductLocalDatasource + .instance + .updateDraftOrder( + updatedDraftOrder); + + // Tampilkan dialog sukses + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal, + totalTax: + finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: + subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController + .text, + ), + ); + } else { + // Jika tidak ada draft order, buat baru + context + .read() + .add( + CheckoutEvent + .saveDraftOrder( + selectTable!.id!, + customerController + .text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal, + totalTax: + finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: + subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController + .text, + ), + ); + } + } else { + ScaffoldMessenger.of(context) + .showSnackBar( + const SnackBar( + content: Text( + 'Pilih meja terlebih dahulu'), + backgroundColor: Colors.red, + ), + ); + } + } else { + context.read().add( + CheckoutEvent + .saveDraftOrder( + widget.isTable == true + ? widget.table!.id! + : selectTable!.id!, + customerController.text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController.text, + ), + ); + } + }, + label: isPayNow + ? 'Bayar' + : isAddToOrder + ? 'Simpan' + : 'Simpan Order', + ), + ); + }, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/home/pages/confirm_payment_page.dart.backup b/lib/presentation/home/pages/confirm_payment_page.dart.backup new file mode 100644 index 0000000..a397994 --- /dev/null +++ b/lib/presentation/home/pages/confirm_payment_page.dart.backup @@ -0,0 +1,1651 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/order/order_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/payment_methods/payment_methods_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; +import 'package:enaklo_pos/presentation/home/widgets/save_order_dialog.dart'; +import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../widgets/order_menu.dart'; +import '../widgets/success_payment_dialog.dart'; +import '../widgets/order_type_selector.dart'; +import '../widgets/payment_method_selector.dart'; + +class ConfirmPaymentPage extends StatefulWidget { + final bool isTable; + final TableModel? table; + + const ConfirmPaymentPage({ + Key? key, + required this.isTable, + this.table, + }) : super(key: key); + + @override + State createState() => _ConfirmPaymentPageState(); +} + +class _ConfirmPaymentPageState extends State { + final totalPriceController = TextEditingController(); + final customerController = TextEditingController(); + bool isPayNow = true; + bool isAddToOrder = false; + PaymentMethod? selectedPaymentMethod; + TableModel? selectTable; + int discountAmount = 0; + int priceValue = 0; + int uangPas = 0; + int uangPas2 = 0; + int uangPas3 = 0; + + // int discountAmountValue = 0; + int totalPriceFinal = 0; + + // int taxFinal = 0; + // int serviceChargeFinal = 0; + + @override + void initState() { + // Fetch available tables by default + context + .read() + .add(GetTableStatusEvent.getTablesStatus('available')); + context + .read() + .add(PaymentMethodsEvent.fetchPaymentMethods()); + + // Set a default payment method in case API fails + selectedPaymentMethod = PaymentMethod( + id: 1, + name: 'Cash', + description: 'Cash payment', + isActive: true, + sortOrder: 1, + ); + // if (selectTable == null && widget.table != null) { + // selectTable = tables.firstWhere( + // (t) => t.id == widget.table!.id, + // orElse: () => null, + // ); + // } + if (widget.table != null) { + // selectTable = TableModel( + // tableNumber: widget.table!.tableNumber, + // startTime: widget.table!.startTime, + // status: widget.table!.status, + // orderId: widget.table!.orderId, + // paymentAmount: widget.table!.paymentAmount, + // position: widget.table!.position, + // ); + } + super.initState(); + } + + @override + void dispose() { + totalPriceController.dispose(); + customerController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Hero( + tag: 'payment_confirmation_screen', + child: Scaffold( + body: Row( + children: [ + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Konfirmasi', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + Text( + widget.isTable + ? 'Orders Table ${widget.table?.tableName}' + : 'Orders #1', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ], + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(24.0), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Item', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + SizedBox( + width: 160, + ), + SizedBox( + width: 50.0, + child: Text( + 'Qty', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + child: Text( + 'Price', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SpaceHeight(8), + const Divider(), + const SpaceHeight(8), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: Text('No Items'), + ), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + OrderMenu(data: products[index]), + separatorBuilder: (context, index) => + const SpaceHeight(12.0), + itemCount: products.length, + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Sub total', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + )); + return Text( + price.currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Diskon', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final subTotal = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + )); + + final finalDiscount = discount / 100 * subTotal; + discountAmount = finalDiscount.toInt(); + return Text( + '$discount % (${finalDiscount.toInt().currencyFormatRp})', + style: TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Pajak PB1', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final subTotal = + price - (discount / 100 * price); + final finalTax = subTotal * (tax / 100); + final finalDiscount = discount / 100 * subTotal; + // discountAmountValue = finalDiscount.toInt(); + // taxFinal = finalTax.toInt(); + return Text( + '$tax % (${finalTax.toInt().currencyFormatRp})', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Biaya Layanan', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final nominalServiceCharge = + (serviceCharge / 100) * + (price - discountAmount); + + // serviceChargeFinal = + // nominalServiceCharge.toInt(); + return Text( + '$serviceCharge % (${nominalServiceCharge.toInt().currencyFormatRp})', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(10.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total', + style: TextStyle( + color: AppColors.grey, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final subTotal = + price - (discount / 100 * price); + final finalTax = subTotal * (tax / 100); + final service = + (serviceCharge / 100) * subTotal; + final total = subTotal + finalTax + service; + priceValue = total.toInt(); + totalPriceController.text = + total.ceil().currencyFormatRpV2; + uangPas = total.ceil(); + uangPas2 = uangPas ~/ 50000 * 50000 + 50000; + uangPas3 = uangPas ~/ 50000 * 50000 + 100000; + totalPriceFinal = total.ceil(); + // log("totalPriceFinal: $totalPriceFinal"); + return Text( + total.ceil().currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + fontSize: 16, + ), + ); + }, + ), + ], + ), + ], + ), + ), + ), + ), + Expanded( + flex: 3, + child: Align( + alignment: Alignment.topCenter, + child: ListView( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.isTable != true) ...[ + const Text( + 'Pembayaran', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + isPayNow && !isAddToOrder + ? Button.filled( + height: 52.0, + width: 200.0, + onPressed: () { + isPayNow = true; + isAddToOrder = false; + setState(() {}); + }, + label: 'Bayar Sekarang', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () { + isPayNow = true; + isAddToOrder = false; + setState(() {}); + }, + label: 'Bayar Sekarang'), + SpaceWidth(8), + !isPayNow && !isAddToOrder + ? Button.filled( + width: 200.0, + height: 52.0, + onPressed: () async { + print( + "🔘 Bayar Nanti button pressed (filled)"); + print( + "🔘 Fetching available tables for Bayar Nanti"); + isPayNow = false; + isAddToOrder = false; + + // Debug: Check all tables first + final allTables = await ProductLocalDatasource.instance.getAllTable(); + print("🔘 All tables in database: ${allTables.length}"); + allTables.forEach((table) { + print("🔘 Table: ${table.tableName} - Status: ${table.status} - ID: ${table.id}"); + }); + + // Fetch available tables for Bayar Nanti + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'available'), + ); + setState(() {}); + }, + label: 'Bayar Nanti', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () async { + print( + "🔘 Bayar Nanti button pressed (outlined)"); + print( + "🔘 Fetching available tables for Bayar Nanti"); + isPayNow = false; + isAddToOrder = false; + + // Debug: Check all tables first + final allTables = await ProductLocalDatasource.instance.getAllTable(); + print("🔘 All tables in database: ${allTables.length}"); + allTables.forEach((table) { + print("🔘 Table: ${table.tableName} - Status: ${table.status} - ID: ${table.id}"); + }); + + // Fetch available tables for Bayar Nanti + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'available'), + ); + setState(() {}); + }, + label: 'Bayar Nanti'), + SpaceWidth(8), + isAddToOrder + ? Button.filled( + width: 200.0, + height: 52.0, + onPressed: () { + isPayNow = false; + isAddToOrder = true; + setState(() {}); + }, + label: 'Tambah ke Pesanan', + ) + : Button.outlined( + width: 200.0, + height: 52.0, + onPressed: () { + print( + "🔘 Tambah button pressed (outlined)"); + print( + "🔘 Fetching occupied tables for Tambah ke Pesanan"); + isPayNow = false; + isAddToOrder = true; + // Fetch occupied tables for Tambah ke Pesanan + context + .read() + .add( + GetTableStatusEvent + .getTablesStatus( + 'occupied'), + ); + setState(() {}); + }, + label: 'Tambah ke Pesanan', + ), + ], + ), + ), + ], + const SpaceHeight(8.0), + if (!isPayNow && !isAddToOrder) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Pilih Meja', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => + const CircularProgressIndicator(), + success: (tables) { + print( + "🔘 Tables fetched: ${tables.length} tables"); + print( + "🔘 Table statuses: ${tables.map((t) => '${t.tableName}: ${t.status}').join(', ')}"); + print( + "🔘 Current mode: ${!isPayNow && !isAddToOrder ? 'Pay Later' : isAddToOrder ? 'Add to Order' : 'Pay Now'}"); + // No need to filter since we're fetching the correct tables directly + final availableTables = tables; + + if (selectTable == null && + availableTables.isNotEmpty) { + selectTable = availableTables.first; + } + + if (availableTables.isEmpty) { + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: Colors.orange[50], + borderRadius: + BorderRadius.circular(16), + border: Border.all( + color: Colors.orange, + width: 1, + ), + ), + child: const Text( + 'Tidak ada meja yang tersedia. Silakan pilih opsi lain.', + style: + TextStyle(color: Colors.orange), + ), + ); + } + + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: Theme.of(context).primaryColor, + width: 2, + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + isExpanded: true, + value: selectTable, + onChanged: (TableModel? newValue) { + setState(() { + selectTable = newValue; + }); + }, + items: availableTables + .map< + DropdownMenuItem>( + (TableModel value) => + DropdownMenuItem< + TableModel>( + value: value, + child: Text(value.tableName), + ), + ) + .toList(), + ), + ), + ); + }, + ); + }), + ], + const SpaceHeight(8.0), + if (isAddToOrder) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Pilih Meja yang Sudah Ada Pesanan', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => + const CircularProgressIndicator(), + success: (tables) { + print( + "🔘 Add to Order - Tables fetched: ${tables.length} tables"); + print( + "🔘 Add to Order - Table statuses: ${tables.map((t) => '${t.tableName}: ${t.status}').join(', ')}"); + // No need to filter since we're fetching occupied tables directly + final occupiedTables = tables; + + if (selectTable == null && + occupiedTables.isNotEmpty) { + selectTable = occupiedTables.first; + } + + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: Theme.of(context).primaryColor, + width: 2, + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + isExpanded: true, + value: selectTable, + onChanged: (TableModel? newValue) { + setState(() { + selectTable = newValue; + }); + }, + items: occupiedTables + .map< + DropdownMenuItem>( + (TableModel value) => + DropdownMenuItem< + TableModel>( + value: value, + child: Text( + '${value.tableName} (Occupied)'), + ), + ) + .toList(), + ), + ), + ); + }, + ); + }), + ], + if (!isAddToOrder) ...[ + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Customer', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + TextFormField( + controller: customerController, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + ), + hintText: 'Nama Customer', + ), + textCapitalization: TextCapitalization.words, + ), + ], + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const OrderTypeSelector(), + const SpaceHeight(8.0), + if (isPayNow) ...[ + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Metode Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + loading: () => const Center( + child: Column( + children: [ + CircularProgressIndicator(), + SizedBox(height: 8.0), + Text('Loading payment methods...'), + ], + ), + ), + error: (message) => Column( + children: [ + Center( + child: Text( + 'Error loading payment methods: $message'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent + .fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ), + loaded: (paymentMethods) { + log("Loaded ${paymentMethods.length} payment methods"); + paymentMethods.forEach((method) { + log("Payment method: ${method.name} (ID: ${method.id})"); + }); + if (paymentMethods.isEmpty) { + return Column( + children: [ + const Center( + child: Text( + 'No payment methods available'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent + .fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ); + } + + // Set default selected payment method if none selected or if current selection is not in the list + if (selectedPaymentMethod == null || + !paymentMethods.any((method) => + method.id == + selectedPaymentMethod?.id)) { + selectedPaymentMethod = + paymentMethods.first; + } + + return PaymentMethodSelector( + paymentMethods: paymentMethods, + selectedPaymentMethod: selectedPaymentMethod, + onPaymentMethodSelected: (method) { + setState(() { + selectedPaymentMethod = method; + }); + }, + ); + }, + ); + }, + }, + ); + }, + ), + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Total Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return TextFormField( + controller: totalPriceController, + keyboardType: TextInputType.number, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: + BorderRadius.circular(8.0), + ), + hintText: 'Total harga', + ), + onChanged: (value) { + priceValue = value.toIntegerFromText; + final int newValue = + value.toIntegerFromText; + totalPriceController.text = + newValue.currencyFormatRp; + totalPriceController.selection = + TextSelection.fromPosition( + TextPosition( + offset: totalPriceController + .text.length)); + }, + ); + }, + ), + const SpaceHeight(20.0), + BlocBuilder( + builder: (context, state) { + return Row( + children: [ + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas + .toString() + .currencyFormatRpV2; + priceValue = uangPas; + }, + label: 'UANG PAS', + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas2 + .toString() + .currencyFormatRpV2; + priceValue = uangPas2; + }, + label: uangPas2 + .toString() + .currencyFormatRpV2, + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () { + totalPriceController.text = uangPas3 + .toString() + .currencyFormatRpV2; + priceValue = uangPas3; + }, + label: uangPas3 + .toString() + .currencyFormatRpV2, + ), + ], + ); + }, + ), + ] + ], + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: ColoredBox( + color: AppColors.white, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 24.0, vertical: 16.0), + child: Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () => context.pop(), + label: 'Kembali', + ), + ), + const SpaceWidth(8.0), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + savedDraftOrder: (orderDraftId) { + log("PRICEVALUE: ${priceValue}"); + + final newTabel = TableModel( + id: widget.isTable + ? widget.table!.id + : selectTable?.id, + tableName: widget.isTable + ? widget.table!.tableName + : selectTable?.tableName ?? + '0', + status: 'occupied', + paymentAmount: priceValue, + orderId: orderDraftId, + startTime: DateTime.now() + .toIso8601String(), + position: widget.isTable + ? widget.table!.position + : selectTable!.position); + log('new tabel: ${newTabel.toMap()}'); + context + .read() + .add(StatusTableEvent.statusTabel( + newTabel, + )); + }); + }, + child: + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + serviceCharge, + ); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + + final orderType = state.maybeWhen( + orElse: () => OrderType.dineIn, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + orderType, + ); + + final subTotal = + price - (discount / 100 * price); + final totalDiscount = + discount / 100 * price; + final finalTax = subTotal * (tax / 100); + final totalServiceCharge = + (serviceCharge / 100) * price; + + List items = + state.maybeWhen( + orElse: () => [], + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products, + ); + final totalQty = items.fold( + 0, + (previousValue, element) => + previousValue + element.quantity, + ); + + return Flexible( + child: Button.filled( + onPressed: () async { + print("🔘 Payment button pressed"); + print("🔘 isPayNow: $isPayNow"); + print( + "🔘 isAddToOrder: $isAddToOrder"); + print( + "🔘 selectedPaymentMethod: ${selectedPaymentMethod?.name}"); + if (selectedPaymentMethod == null) { + ScaffoldMessenger.of(context) + .showSnackBar( + const SnackBar( + content: Text( + 'Please select a payment method'), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (widget.isTable) { + log("discountAmountValue: $totalDiscount"); + context.read().add( + CheckoutEvent + .saveDraftOrder( + widget.isTable == true + ? widget.table!.id! + : selectTable!.id!, + customerController.text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + table: widget.table!, + draftName: + customerController.text, + ), + ); + } else if (isPayNow) { + log("🔘 Entering Pay Now flow"); + // context.read().add( + // OrderEvent.addPaymentMethod( + // items, + // totalPrice, + // finalTax, + // discount != null + // ? discount.value + // .replaceAll( + // '.00', '') + // .toIntegerFromText + // : 0, + // finalDiscountAmount, + // finalService, + // subTotal, + // totalPriceController.text + // .toIntegerFromText, + // auth?.user.name ?? '-', + // totalQuantity, + // auth?.user.id ?? 1, + // isCash + // ? 'Cash' + // : 'QR Pay')); + final paymentMethodName = + selectedPaymentMethod?.name + ?.toLowerCase() ?? + ''; + log("Selected payment method: ${selectedPaymentMethod?.name} (normalized: $paymentMethodName)"); + if (paymentMethodName == 'cash' || + paymentMethodName == + 'tunai' || + paymentMethodName == + 'uang tunai' || + paymentMethodName == + 'cash payment') { + log("🔘 Payment method is cash, proceeding with OrderBloc call"); + log("discountAmountValue: $totalDiscount"); + log("💳 About to call OrderBloc for cash payment"); + log("💳 OrderBloc instance: ${context.read()}"); + log("💳 About to dispatch OrderEvent.order for cash payment"); + context.read().add( + OrderEvent.order( + items, + discount, + totalDiscount.toInt(), + finalTax.toInt(), + 0, + totalPriceController + .text + .toIntegerFromText, + customerController.text, + 0, + 'completed', + 'paid', + selectedPaymentMethod + ?.name ?? + 'Cash', + totalPriceFinal, + orderType)); + log("💳 OrderEvent.order dispatched for cash payment"); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: + totalServiceCharge + .toInt(), + draftName: + customerController.text, + ), + ); + } else { + // Process non-cash payment directly without QRIS dialog + log("Processing non-cash payment: ${selectedPaymentMethod?.name}"); + log("💳 About to call OrderBloc for non-cash payment"); + log("💳 OrderBloc instance: ${context.read()}"); + context.read().add( + OrderEvent.order( + items, + discount, + totalDiscount.toInt(), + finalTax.toInt(), + 0, + totalPriceController + .text + .toIntegerFromText, + customerController.text, + 0, + 'completed', + 'paid', + selectedPaymentMethod + ?.name ?? + 'Unknown Payment Method', + totalPriceFinal, + orderType)); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: + totalServiceCharge + .toInt(), + draftName: + customerController.text, + ), + ); + } + } else if (isAddToOrder) { + // Tambahkan ke pesanan meja yang sudah ada + if (selectTable != null) { + // Ambil draft order yang sudah ada + final existingDraftOrder = + await ProductLocalDatasource + .instance + .getDraftOrderById( + selectTable! + .orderId ?? + 0); + + if (existingDraftOrder != + null) { + // Convert items ke DraftOrderItem + final newDraftItems = items + .map((item) => + DraftOrderItem( + product: + item.product, + quantity: + item.quantity, + )) + .toList(); + + // Gabungkan dengan pesanan yang sudah ada + final updatedItems = [ + ...existingDraftOrder + .orders, + ...newDraftItems + ]; + + final updatedDraftOrder = + existingDraftOrder + .copyWith( + orders: updatedItems, + totalQuantity: + updatedItems.fold( + 0, + (sum, item) => + sum + + item.quantity), + subTotal: updatedItems.fold< + int>( + 0, + (sum, item) => + sum + + (int.tryParse(item + .product + .price ?? + '0') ?? + 0) * + item.quantity), + ); + + // Update draft order + await ProductLocalDatasource + .instance + .updateDraftOrder( + updatedDraftOrder); + + // Tampilkan dialog sukses + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal, + totalTax: + finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: + subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController + .text, + ), + ); + } else { + // Jika tidak ada draft order, buat baru + context + .read() + .add( + CheckoutEvent + .saveDraftOrder( + selectTable!.id!, + customerController + .text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal, + totalTax: + finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: + subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController + .text, + ), + ); + } + } else { + ScaffoldMessenger.of(context) + .showSnackBar( + const SnackBar( + content: Text( + 'Pilih meja terlebih dahulu'), + backgroundColor: Colors.red, + ), + ); + } + } else { + context.read().add( + CheckoutEvent + .saveDraftOrder( + widget.isTable == true + ? widget.table!.id! + : selectTable!.id!, + customerController.text, + totalDiscount.toInt(), + ), + ); + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SaveOrderDialog( + data: items, + totalQty: totalQty, + totalPrice: totalPriceFinal, + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + table: selectTable!, + draftName: + customerController.text, + ), + ); + } + }, + label: isPayNow + ? 'Bayar' + : isAddToOrder + ? 'Simpan' + : 'Simpan Order', + ), + ); + }, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/home/pages/dashboard_page.dart b/lib/presentation/home/pages/dashboard_page.dart new file mode 100644 index 0000000..547f8f9 --- /dev/null +++ b/lib/presentation/home/pages/dashboard_page.dart @@ -0,0 +1,226 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:async'; +import 'dart:developer'; + +import 'package:connectivity_plus/connectivity_plus.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:google_fonts/google_fonts.dart'; + +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/presentation/auth/login_page.dart'; +import 'package:enaklo_pos/presentation/report/pages/report_page.dart'; +import 'package:enaklo_pos/presentation/sales/pages/sales_page.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_order/sync_order_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/pages/printer_configuration_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/settings_page.dart'; +import 'package:enaklo_pos/presentation/table/pages/new_table_management_page.dart'; +import 'package:enaklo_pos/presentation/table/pages/table_page.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../auth/bloc/logout/logout_bloc.dart'; +import '../bloc/online_checker/online_checker_bloc.dart'; +import '../widgets/nav_item.dart'; +import 'home_page.dart'; + +class DashboardPage extends StatefulWidget { + final int? index; + final TableModel? table; + const DashboardPage({ + Key? key, + this.index = 0, + this.table, + }) : super(key: key); + + @override + State createState() => _DashboardPageState(); +} + +class _DashboardPageState extends State { + int _selectedIndex = 0; + + List _pages = []; + + void _onItemTapped(int index) { + _selectedIndex = index; + setState(() {}); + } + + @override + void initState() { + super.initState(); + _selectedIndex = widget.index!; + _pages = [ + HomePage( + isTable: false, + table: widget.table, + ), + // const TablePage(), + TableManagementScreen(), + const ReportPage(), + const PrinterConfigurationPage(), + // SalesPage(), + const SettingsPage(), + ]; + StreamSubscription> subscription = Connectivity() + .onConnectivityChanged + .listen((List connectivityResult) { + // Received changes in available connectivity types! + if (connectivityResult.contains(ConnectivityResult.mobile)) { + // Mobile network available. + context + .read() + .add(const OnlineCheckerEvent.check(true)); + } else if (connectivityResult.contains(ConnectivityResult.wifi)) { + // Wi-fi is available. + context + .read() + .add(const OnlineCheckerEvent.check(true)); + // Note for Android: + // When both mobile and Wi-Fi are turned on system will return Wi-Fi only as active network type + } else { + // Neither mobile network nor Wi-fi available. + context + .read() + .add(const OnlineCheckerEvent.check(false)); + } + }); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Scaffold( + body: Row( + children: [ + Expanded( + flex: 1, + child: SizedBox( + height: (context.deviceHeight - 40.0).clamp(0.0, double.infinity), + child: ColoredBox( + color: AppColors.primary, + child: ListView( + children: [ + NavItem( + iconPath: Assets.icons.homeResto.path, + isActive: _selectedIndex == 0, + onTap: () => _onItemTapped(0), + ), + NavItem( + iconPath: Assets.icons.kelolaProduk.path, + isActive: _selectedIndex == 1, + onTap: () => _onItemTapped(1), + ), + NavItem( + iconPath: Assets.icons.dashboard.path, + isActive: _selectedIndex == 2, + onTap: () => _onItemTapped(2), + ), + NavItem( + iconPath: Assets.icons.print.path, + isActive: _selectedIndex == 3, + onTap: () => _onItemTapped(3), + ), + NavItem( + iconPath: Assets.icons.setting.path, + isActive: _selectedIndex == 4, + onTap: () => _onItemTapped(4), + ), + //container flag online/offline + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => Container( + width: 40, + margin: + const EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: AppColors.red, + borderRadius: BorderRadius.circular(8.0), + ), + child: const Icon( + Icons.signal_wifi_off, + color: AppColors.white, + ), + ), + online: () { + log("🌐 Dashboard: Internet connection detected, triggering sync"); + context.read().add( + const SyncOrderEvent.syncOrder(), + ); + return Container( + width: 40, + margin: + const EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: AppColors.green, + borderRadius: BorderRadius.circular(8.0), + ), + child: const Icon( + Icons.wifi, + color: AppColors.white, + ), + ); + }, + ); + }, + ), + + BlocListener( + listener: (context, state) { + state.maybeMap( + orElse: () {}, + error: (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(e.message), + backgroundColor: AppColors.red, + ), + ); + }, + success: (value) { + AuthLocalDataSource().removeAuthData(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Logout success'), + backgroundColor: AppColors.primary, + ), + ); + Navigator.pushReplacement(context, + MaterialPageRoute(builder: (context) { + return const LoginPage(); + })); + }, + ); + }, + child: NavItem( + iconPath: Assets.icons.logout.path, + isActive: false, + onTap: () { + context + .read() + .add(const LogoutEvent.logout()); + }, + ), + ), + ], + ), + ), + ), + ), + Expanded( + flex: 10, + child: _pages[_selectedIndex], + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/home/pages/home_page.dart b/lib/presentation/home/pages/home_page.dart new file mode 100644 index 0000000..a255743 --- /dev/null +++ b/lib/presentation/home/pages/home_page.dart @@ -0,0 +1,690 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/local_product/local_product_bloc.dart'; +import 'package:enaklo_pos/presentation/home/dialog/discount_dialog.dart'; +import 'package:enaklo_pos/presentation/home/dialog/tax_dialog.dart'; +import 'package:enaklo_pos/presentation/home/pages/confirm_payment_page.dart'; +import 'package:enaklo_pos/presentation/home/pages/dashboard_page.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../dialog/service_dialog.dart'; +import '../widgets/column_button.dart'; +import '../widgets/custom_tab_bar.dart'; +import '../widgets/home_title.dart'; +import '../widgets/order_menu.dart'; +import '../widgets/product_card.dart'; + +class HomePage extends StatefulWidget { + final bool isTable; + final TableModel? table; + const HomePage({ + Key? key, + required this.isTable, + this.table, + }) : super(key: key); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + final searchController = TextEditingController(); + String searchQuery = ''; + + @override + void initState() { + // First sync products from API, then load local products + _syncAndLoadProducts(); + super.initState(); + } + + void _syncAndLoadProducts() { + // Trigger sync from API first + context.read().add(const SyncProductEvent.syncProduct()); + + // Also load local products initially in case sync fails or takes time + context + .read() + .add(const LocalProductEvent.getLocalProduct()); + + // Initialize checkout with tax and service charge settings + context.read().add(const CheckoutEvent.started()); + } + + void onCategoryTap(int index) { + searchController.clear(); + setState(() { + searchQuery = ''; + }); + } + + List _filterProducts(List products) { + if (searchQuery.isEmpty) { + return products; + } + + return products.where((product) { + final productName = product.name?.toLowerCase() ?? ''; + final queryLower = searchQuery.toLowerCase(); + return productName.contains(queryLower); + }).toList(); + } + + List _filterProductsByCategory(List products, int categoryId) { + final filteredBySearch = _filterProducts(products); + return filteredBySearch.where((element) => element.category?.id == categoryId).toList(); + } + + @override + Widget build(BuildContext context) { + return Hero( + tag: 'confirmation_screen', + child: Scaffold( + body: BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + error: (message) { + // If sync fails, still try to load local products + context + .read() + .add(const LocalProductEvent.getLocalProduct()); + }, + loaded: (productResponseModel) async { + // Store context reference before async operations + final localProductBloc = context.read(); + + // Save synced products to local database + await ProductLocalDatasource.instance.deleteAllProducts(); + await ProductLocalDatasource.instance.insertProducts( + productResponseModel.data!, + ); + // Then load local products to display + localProductBloc.add(const LocalProductEvent.getLocalProduct()); + }, + ); + }, + child: Row( + children: [ + Expanded( + flex: 3, + child: Align( + alignment: AlignmentDirectional.topStart, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + HomeTitle( + controller: searchController, + onChanged: (value) { + setState(() { + searchQuery = value; + }); + }, + ), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return CustomTabBar( + tabTitles: const [ + 'Semua', + 'Makanan', + 'Minuman', + 'Paket' + ], + initialTabIndex: 0, + tabViews: [ + // All Products Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + final filteredProducts = _filterProducts(products); + if (filteredProducts.isEmpty) { + return const Center( + child: Text('No Items Found'), + ); + } + return GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) => + ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ), + ); + }), + ), + // Makanan Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 1); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) => + ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ), + ); + }), + ), + // Minuman Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 2); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + return ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ); + }, + ); + }), + ), + // Snack Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 3); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + return ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ); + }, + ); + }), + ), + ], + ); + }, + ), + ], + ), + ), + ), + ), + ), + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: Stack( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () { + if (widget.table == null) { + context.push(DashboardPage( + index: 1, + )); + } + }, + child: Text( + 'Meja: ${widget.table == null ? 'Belum Pilih Meja' : '${widget.table!.id}'}', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + ), + const SpaceHeight(8.0), + Button.filled( + width: 180.0, + height: 40, + onPressed: () {}, + label: 'Pesanan#', + ), + + // Row( + // children: [ + // Button.filled( + // width: 120.0, + // height: 40, + // onPressed: () {}, + // label: 'Dine In', + // ), + // const SpaceWidth(8.0), + // Button.outlined( + // width: 100.0, + // height: 40, + // onPressed: () {}, + // label: 'To Go', + // ), + // ], + // ), + const SpaceHeight(16.0), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Item', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + SizedBox( + width: 130, + ), + SizedBox( + width: 50.0, + child: Text( + 'Qty', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + child: Text( + 'Price', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SpaceHeight(8), + const Divider(), + const SpaceHeight(8), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: Text('No Items'), + ), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + return ListView.separated( + shrinkWrap: true, + physics: + const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + OrderMenu(data: products[index]), + separatorBuilder: (context, index) => + const SpaceHeight(1.0), + itemCount: products.length, + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + ColumnButton( + label: 'Diskon', + svgGenImage: Assets.icons.diskon, + onPressed: () => showDialog( + context: context, + barrierDismissible: false, + builder: (context) => const DiscountDialog(), + ), + ), + ColumnButton( + label: 'Pajak PB1', + svgGenImage: Assets.icons.pajak, + onPressed: () => showDialog( + context: context, + builder: (context) => const TaxDialog(), + ), + ), + ColumnButton( + label: 'Layanan', + svgGenImage: Assets.icons.layanan, + onPressed: () => showDialog( + context: context, + builder: (context) => const ServiceDialog(), + ), + ), + ], + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Pajak PB1', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + if (products.isEmpty) { + return 0; + } + return tax; + }); + return Text( + '$tax %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Layanan', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + return serviceCharge; + }); + return Text( + '$serviceCharge %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Diskon', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + return Text( + '$discount %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Sub total', + style: TextStyle( + color: AppColors.grey, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + if (products.isEmpty) { + return 0; + } + return products + .map((e) => + e.product.price! + .toIntegerFromText * + e.quantity) + .reduce((value, element) => + value + element); + }); + + return Text( + price.currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.bold, + fontSize: 16), + ); + }, + ), + ], + ), + const SpaceHeight(100.0), + ], + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: ColoredBox( + color: AppColors.white, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 24.0, vertical: 16.0), + child: Button.filled( + onPressed: () { + context.push(ConfirmPaymentPage( + isTable: widget.isTable, + table: widget.table, + )); + }, + label: 'Lanjutkan Pembayaran', + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _IsEmpty extends StatelessWidget { + const _IsEmpty(); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SpaceHeight(40), + Assets.icons.noProduct.svg(), + const SizedBox(height: 40.0), + const Text( + 'Belum Ada Produk', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16), + ), + ], + ); + } +} diff --git a/lib/presentation/home/pages/home_page.dart.backup b/lib/presentation/home/pages/home_page.dart.backup new file mode 100644 index 0000000..db9e67b --- /dev/null +++ b/lib/presentation/home/pages/home_page.dart.backup @@ -0,0 +1,688 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'package:flutter_posresto_app/core/extensions/build_context_ext.dart'; +import 'package:flutter_posresto_app/core/extensions/int_ext.dart'; +import 'package:flutter_posresto_app/core/extensions/string_ext.dart'; +import 'package:flutter_posresto_app/data/models/response/table_model.dart'; +import 'package:flutter_posresto_app/presentation/home/bloc/local_product/local_product_bloc.dart'; +import 'package:flutter_posresto_app/presentation/home/dialog/discount_dialog.dart'; +import 'package:flutter_posresto_app/presentation/home/dialog/tax_dialog.dart'; +import 'package:flutter_posresto_app/presentation/home/pages/confirm_payment_page.dart'; +import 'package:flutter_posresto_app/presentation/home/pages/dashboard_page.dart'; +import 'package:flutter_posresto_app/data/datasources/product_local_datasource.dart'; +import 'package:flutter_posresto_app/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; +import 'package:flutter_posresto_app/data/models/response/product_response_model.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../dialog/service_dialog.dart'; +import '../widgets/column_button.dart'; +import '../widgets/custom_tab_bar.dart'; +import '../widgets/home_title.dart'; +import '../widgets/order_menu.dart'; +import '../widgets/product_card.dart'; + +class HomePage extends StatefulWidget { + final bool isTable; + final TableModel? table; + const HomePage({ + Key? key, + required this.isTable, + this.table, + }) : super(key: key); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State { + final searchController = TextEditingController(); + String searchQuery = ''; + + @override + void initState() { + // First sync products from API, then load local products + _syncAndLoadProducts(); + super.initState(); + } + + void _syncAndLoadProducts() { + // Trigger sync from API first + context.read().add(const SyncProductEvent.syncProduct()); + + // Also load local products initially in case sync fails or takes time + context + .read() + .add(const LocalProductEvent.getLocalProduct()); + + // Initialize checkout with tax and service charge settings + context.read().add(const CheckoutEvent.started()); + } + + void onCategoryTap(int index) { + searchController.clear(); + setState(() { + searchQuery = ''; + }); + } + + List _filterProducts(List products) { + if (searchQuery.isEmpty) { + return products; + } + + return products.where((product) { + final productName = product.name?.toLowerCase() ?? ''; + final queryLower = searchQuery.toLowerCase(); + return productName.contains(queryLower); + }).toList(); + } + + List _filterProductsByCategory(List products, int categoryId) { + final filteredBySearch = _filterProducts(products); + return filteredBySearch.where((element) => element.category?.id == categoryId).toList(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + error: (message) { + // If sync fails, still try to load local products + context + .read() + .add(const LocalProductEvent.getLocalProduct()); + }, + loaded: (productResponseModel) async { + // Store context reference before async operations + final localProductBloc = context.read(); + + // Save synced products to local database + await ProductLocalDatasource.instance.deleteAllProducts(); + await ProductLocalDatasource.instance.insertProducts( + productResponseModel.data!, + ); + // Then load local products to display + localProductBloc.add(const LocalProductEvent.getLocalProduct()); + }, + ); + }, + child: Row( + children: [ + Expanded( + flex: 3, + child: Align( + alignment: AlignmentDirectional.topStart, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + HomeTitle( + controller: searchController, + onChanged: (value) { + setState(() { + searchQuery = value; + }); + }, + ), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return CustomTabBar( + tabTitles: const [ + 'Semua', + 'Makanan', + 'Minuman', + 'Snack' + ], + initialTabIndex: 0, + tabViews: [ + // All Products Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + final filteredProducts = _filterProducts(products); + if (filteredProducts.isEmpty) { + return const Center( + child: Text('No Items Found'), + ); + } + return GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) => + ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ), + ); + }), + ), + // Makanan Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 1); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) => + ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ), + ); + }), + ), + // Minuman Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 2); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + return ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ); + }, + ); + }), + ), + // Snack Tab + SizedBox( + child: state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (products) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + final filteredProducts = _filterProductsByCategory(products, 3); + return filteredProducts.isEmpty + ? const _IsEmpty() + : GridView.builder( + shrinkWrap: true, + itemCount: filteredProducts.length, + physics: + const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + return ProductCard( + data: filteredProducts[index], + onCartButton: () {}, + ); + }, + ); + }), + ), + ], + ); + }, + ), + ], + ), + ), + ), + ), + ), + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: Stack( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () { + if (widget.table == null) { + context.push(DashboardPage( + index: 1, + )); + } + }, + child: Text( + 'Meja: ${widget.table == null ? 'Belum Pilih Meja' : '${widget.table!.id}'}', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + ), + const SpaceHeight(8.0), + Button.filled( + width: 180.0, + height: 40, + onPressed: () {}, + label: 'Pesanan#', + ), + + // Row( + // children: [ + // Button.filled( + // width: 120.0, + // height: 40, + // onPressed: () {}, + // label: 'Dine In', + // ), + // const SpaceWidth(8.0), + // Button.outlined( + // width: 100.0, + // height: 40, + // onPressed: () {}, + // label: 'To Go', + // ), + // ], + // ), + const SpaceHeight(16.0), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Item', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + SizedBox( + width: 130, + ), + SizedBox( + width: 50.0, + child: Text( + 'Qty', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + child: Text( + 'Price', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SpaceHeight(8), + const Divider(), + const SpaceHeight(8), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: Text('No Items'), + ), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + return ListView.separated( + shrinkWrap: true, + physics: + const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + OrderMenu(data: products[index]), + separatorBuilder: (context, index) => + const SpaceHeight(1.0), + itemCount: products.length, + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + ColumnButton( + label: 'Diskon', + svgGenImage: Assets.icons.diskon, + onPressed: () => showDialog( + context: context, + barrierDismissible: false, + builder: (context) => const DiscountDialog(), + ), + ), + ColumnButton( + label: 'Pajak PB1', + svgGenImage: Assets.icons.pajak, + onPressed: () => showDialog( + context: context, + builder: (context) => const TaxDialog(), + ), + ), + ColumnButton( + label: 'Layanan', + svgGenImage: Assets.icons.layanan, + onPressed: () => showDialog( + context: context, + builder: (context) => const ServiceDialog(), + ), + ), + ], + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Pajak PB1', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName) { + if (products.isEmpty) { + return 0; + } + return tax; + }); + return Text( + '$tax %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Layanan', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName) { + return serviceCharge; + }); + return Text( + '$serviceCharge %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Diskon', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName) { + if (discountModel == null) { + return 0; + } + return discountModel.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + return Text( + '$discount %', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Sub total', + style: TextStyle( + color: AppColors.grey, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName) { + if (products.isEmpty) { + return 0; + } + return products + .map((e) => + e.product.price! + .toIntegerFromText * + e.quantity) + .reduce((value, element) => + value + element); + }); + + return Text( + price.currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.bold, + fontSize: 16), + ); + }, + ), + ], + ), + const SpaceHeight(100.0), + ], + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: ColoredBox( + color: AppColors.white, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 24.0, vertical: 16.0), + child: Button.filled( + onPressed: () { + context.push(ConfirmPaymentPage( + isTable: widget.isTable, + table: widget.table, + )); + }, + label: 'Lanjutkan Pembayaran', + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} + +class _IsEmpty extends StatelessWidget { + const _IsEmpty(); + + @override + Widget build(BuildContext context) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SpaceHeight(40), + Assets.icons.noProduct.svg(), + const SizedBox(height: 40.0), + const Text( + 'Belum Ada Produk', + textAlign: TextAlign.center, + style: TextStyle(fontSize: 16), + ), + ], + ); + } +} diff --git a/lib/presentation/home/pages/logout_page.dart b/lib/presentation/home/pages/logout_page.dart new file mode 100644 index 0000000..8326530 --- /dev/null +++ b/lib/presentation/home/pages/logout_page.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../../core/constants/colors.dart'; +import '../../../data/datasources/auth_local_datasource.dart'; +import '../../auth/bloc/logout/logout_bloc.dart'; +import '../../auth/login_page.dart'; + + + +class LogoutPage extends StatefulWidget { + const LogoutPage({super.key}); + + @override + State createState() => _LogoutPageState(); +} + +class _LogoutPageState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Dashboard'), + ), + body: Center( + child: Column( + children: [ + const Text('Welcome to Dashboard'), + + const SizedBox( + height: 100, + ), + BlocListener( + listener: (context, state) { + state.maybeMap( + orElse: () {}, + error: (e) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(e.message), + backgroundColor: AppColors.red, + ), + ); + }, + success: (value) { + AuthLocalDataSource().removeAuthData(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Logout success'), + backgroundColor: AppColors.primary, + ), + ); + Navigator.pushReplacement(context, + MaterialPageRoute(builder: (context) { + return const LoginPage(); + })); + }, + ); + }, + child: ElevatedButton( + onPressed: () { + context.read().add(const LogoutEvent.logout()); + }, + child: const Text('Logout'), + ), + ), + ], + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/presentation/home/widgets/column_button.dart b/lib/presentation/home/widgets/column_button.dart new file mode 100644 index 0000000..a408c45 --- /dev/null +++ b/lib/presentation/home/widgets/column_button.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; + + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class ColumnButton extends StatelessWidget { + final String label; + final SvgGenImage svgGenImage; + final VoidCallback onPressed; + + const ColumnButton({ + super.key, + required this.label, + required this.svgGenImage, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onPressed, + child: Column( + children: [ + Container( + padding: const EdgeInsets.all(8.0), + height: 40.0, + width: 40.0, + decoration: BoxDecoration( + color: AppColors.white, + border: Border.all(color: AppColors.primary), + borderRadius: const BorderRadius.all(Radius.circular(8.0)), + ), + child: svgGenImage.svg(), + ), + const SpaceHeight(8.0), + Text( + label, + style: const TextStyle( + color: AppColors.primary, + fontSize: 12, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/home/widgets/custom_tab_bar.dart b/lib/presentation/home/widgets/custom_tab_bar.dart new file mode 100644 index 0000000..ca7c652 --- /dev/null +++ b/lib/presentation/home/widgets/custom_tab_bar.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; + +import '../../../core/constants/colors.dart'; + + + +class CustomTabBar extends StatefulWidget { + final List tabTitles; + final int initialTabIndex; + final List tabViews; + + const CustomTabBar({ + super.key, + required this.tabTitles, + required this.initialTabIndex, + required this.tabViews, + }); + + @override + State createState() => _CustomTabBarState(); +} + +class _CustomTabBarState extends State { + late int _selectedIndex; + + @override + void initState() { + super.initState(); + _selectedIndex = widget.initialTabIndex; + } + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: List.generate( + widget.tabTitles.length, + (index) => GestureDetector( + onTap: () { + setState(() { + _selectedIndex = index; + }); + }, + child: Container( + padding: const EdgeInsets.symmetric(vertical: 14), + margin: const EdgeInsets.only(right: 32), + decoration: BoxDecoration( + border: _selectedIndex == index + ? const Border( + bottom: BorderSide( + width: 3.0, + color: AppColors.primary, + ), + ) + : null, + ), + child: Text( + widget.tabTitles[index], + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(vertical: 18.0), + child: widget.tabViews[_selectedIndex], + ), + ], + ); + } +} diff --git a/lib/presentation/home/widgets/home_title.dart b/lib/presentation/home/widgets/home_title.dart new file mode 100644 index 0000000..17636cc --- /dev/null +++ b/lib/presentation/home/widgets/home_title.dart @@ -0,0 +1,54 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; + +import '../../../core/components/search_input.dart'; +import '../../../core/constants/colors.dart'; + +class HomeTitle extends StatelessWidget { + final TextEditingController controller; + final Function(String value)? onChanged; + + const HomeTitle({ + super.key, + required this.controller, + this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Enaklo POS', + style: TextStyle( + color: AppColors.primary, + fontSize: 22, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 4.0), + Text( + DateTime.now().toFormattedDate(), + style: const TextStyle( + color: AppColors.subtitle, + fontSize: 16, + ), + ), + ], + ), + SizedBox( + width: 300.0, + child: SearchInput( + controller: controller, + onChanged: onChanged, + hintText: 'Search..', + ), + ), + ], + ); + } +} diff --git a/lib/presentation/home/widgets/item_notes_dialog.dart b/lib/presentation/home/widgets/item_notes_dialog.dart new file mode 100644 index 0000000..2384997 --- /dev/null +++ b/lib/presentation/home/widgets/item_notes_dialog.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class ItemNotesDialog extends StatefulWidget { + final ProductQuantity item; + + const ItemNotesDialog({ + super.key, + required this.item, + }); + + @override + State createState() => _ItemNotesDialogState(); +} + +class _ItemNotesDialogState extends State { + late TextEditingController notesController; + + @override + void initState() { + super.initState(); + notesController = TextEditingController(text: widget.item.notes); + } + + @override + void dispose() { + notesController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Add Notes'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.item.product.name ?? 'Product', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + TextField( + controller: notesController, + maxLines: 3, + decoration: const InputDecoration( + hintText: 'Enter notes for this item...', + border: OutlineInputBorder(), + ), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + Button.filled( + onPressed: () { + context.read().add( + CheckoutEvent.updateItemNotes( + widget.item.product, + notesController.text, + ), + ); + Navigator.of(context).pop(); + }, + label: 'Save', + ), + ], + ); + } +} \ No newline at end of file diff --git a/lib/presentation/home/widgets/nav_item.dart b/lib/presentation/home/widgets/nav_item.dart new file mode 100644 index 0000000..ca5ee74 --- /dev/null +++ b/lib/presentation/home/widgets/nav_item.dart @@ -0,0 +1,59 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../../../core/constants/colors.dart'; + + + +class NavItem extends StatelessWidget { + final String iconPath; + final bool isActive; + final VoidCallback onTap; + final Color color; + + const NavItem({ + super.key, + required this.iconPath, + required this.isActive, + required this.onTap, + this.color = AppColors.white, + }); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: const BorderRadius.all(Radius.circular(16.0)), + child: Padding( + padding: const EdgeInsets.all(20.0), + child: ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(12.0)), + child: ColoredBox( + color: isActive + ? AppColors.disabled.withOpacity(0.25) + : Colors.transparent, + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 25.0, + height: 25.0, + child: SvgPicture.asset( + iconPath, + colorFilter: ColorFilter.mode( + color, + BlendMode.srcIn, + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/home/widgets/order_menu.dart b/lib/presentation/home/widgets/order_menu.dart new file mode 100644 index 0000000..667675f --- /dev/null +++ b/lib/presentation/home/widgets/order_menu.dart @@ -0,0 +1,160 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/widgets/item_notes_dialog.dart'; + +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class OrderMenu extends StatelessWidget { + final ProductQuantity data; + const OrderMenu({super.key, required this.data}); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Row( + children: [ + Flexible( + child: ListTile( + contentPadding: EdgeInsets.zero, + leading: ClipRRect( + borderRadius: BorderRadius.all(Radius.circular(50.0)), + child: + // Icon( + // Icons.fastfood, + // size: 50, + // color: AppColors.primary, + // ), + CachedNetworkImage( + imageUrl: data.product.image!.contains('http') + ? data.product.image! + : '${Variables.baseUrl}/${data.product.image}', + width: 50.0, + height: 50.0, + fit: BoxFit.cover, + ), + ), + title: Row( + children: [ + Expanded( + child: Text(data.product.name ?? "-", + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + )), + ), + GestureDetector( + onTap: () { + showDialog( + context: context, + builder: (context) => ItemNotesDialog(item: data), + ); + }, + child: const Icon( + Icons.edit_note, + size: 20, + color: AppColors.primary, + ), + ), + ], + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(data.product.price!.toIntegerFromText.currencyFormatRp), + if (data.notes.isNotEmpty) ...[ + const SpaceHeight(4.0), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8.0, + vertical: 4.0, + ), + decoration: BoxDecoration( + color: AppColors.primary.withOpacity(0.1), + borderRadius: BorderRadius.circular(4.0), + ), + child: Text( + 'Notes: ${data.notes}', + style: const TextStyle( + fontSize: 12, + color: AppColors.primary, + fontStyle: FontStyle.italic, + ), + ), + ), + ], + ], + ), + ), + ), + Row( + children: [ + GestureDetector( + onTap: () { + context + .read() + .add(CheckoutEvent.removeItem(data.product)); + }, + child: Container( + width: 30, + height: 30, + color: AppColors.white, + child: const Icon( + Icons.remove_circle, + color: AppColors.primary, + ), + ), + ), + SizedBox( + width: 30.0, + child: Center( + child: Text( + data.quantity.toString(), + )), + ), + GestureDetector( + onTap: () { + context + .read() + .add(CheckoutEvent.addItem(data.product)); + }, + child: Container( + width: 30, + height: 30, + color: AppColors.white, + child: const Icon( + Icons.add_circle, + color: AppColors.primary, + ), + ), + ), + ], + ), + const SpaceWidth(8), + SizedBox( + width: 80.0, + child: Text( + (data.product.price!.toIntegerFromText * data.quantity) + .currencyFormatRp, + textAlign: TextAlign.right, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + ], + ), + ], + ); + } +} diff --git a/lib/presentation/home/widgets/order_type_selector.dart b/lib/presentation/home/widgets/order_type_selector.dart new file mode 100644 index 0000000..01eb355 --- /dev/null +++ b/lib/presentation/home/widgets/order_type_selector.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; + +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class OrderTypeSelector extends StatelessWidget { + const OrderTypeSelector({super.key}); + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const SizedBox.shrink(), + loaded: (items, discountModel, discount, discountAmount, tax, serviceCharge, totalQuantity, totalPrice, draftName, orderType) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Order Type', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(12.0), + Wrap( + spacing: 12.0, + runSpacing: 8.0, + children: OrderType.values.map((type) { + final isSelected = orderType == type; + return GestureDetector( + onTap: () { + context.read().add( + CheckoutEvent.updateOrderType(type), + ); + }, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 8.0, + ), + decoration: BoxDecoration( + color: isSelected ? AppColors.primary : AppColors.white, + border: Border.all( + color: isSelected ? AppColors.primary : AppColors.grey, + width: 1.0, + ), + borderRadius: BorderRadius.circular(8.0), + ), + child: Text( + type.value, + style: TextStyle( + color: isSelected ? AppColors.white : AppColors.black, + fontSize: 14, + fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal, + ), + ), + ), + ); + }).toList(), + ), + ], + ); + }, + ); + }, + ); + } +} \ No newline at end of file diff --git a/lib/presentation/home/widgets/product_card.dart b/lib/presentation/home/widgets/product_card.dart new file mode 100644 index 0000000..0477d13 --- /dev/null +++ b/lib/presentation/home/widgets/product_card.dart @@ -0,0 +1,189 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/constants/variables.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class ProductCard extends StatelessWidget { + final Product data; + final VoidCallback onCartButton; + + const ProductCard({ + super.key, + required this.data, + required this.onCartButton, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () { + context.read().add(CheckoutEvent.addItem(data)); + }, + child: Container( + padding: const EdgeInsets.all(16.0), + decoration: ShapeDecoration( + shape: RoundedRectangleBorder( + side: const BorderSide(width: 1, color: AppColors.card), + borderRadius: BorderRadius.circular(16), + ), + ), + child: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SpaceHeight(8), + Container( + alignment: Alignment.center, + padding: const EdgeInsets.all(12.0), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.disabled.withOpacity(0.4), + ), + child: ClipRRect( + borderRadius: BorderRadius.all(Radius.circular(40.0)), + child: + // Icon( + // Icons.fastfood, + // size: 40, + // color: AppColors.primary, + // ), + CachedNetworkImage( + imageUrl: data.image!.contains('http') + ? data.image! + : '${Variables.baseUrl}/${data.image}', + width: 60, + height: 60, + fit: BoxFit.cover, + ), + ), + ), + const Spacer(), + Text( + "${data.name}", + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const Spacer(), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: Text( + data.category?.name ?? '-', + style: const TextStyle( + color: AppColors.grey, + fontSize: 12, + ), + ), + ), + Flexible( + child: Text( + data.price!.toIntegerFromText.currencyFormatRp, + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 13, + ), + ), + ), + ], + ), + const Spacer(), + ], + ), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const SizedBox(), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + return products.any((element) => element.product == data) + ? products + .firstWhere( + (element) => element.product == data) + .quantity > + 0 + ? Align( + alignment: Alignment.topRight, + child: Container( + width: 40, + height: 40, + padding: const EdgeInsets.all(6), + decoration: const BoxDecoration( + borderRadius: + BorderRadius.all(Radius.circular(9.0)), + color: AppColors.primary, + ), + child: Center( + child: Text( + products + .firstWhere((element) => + element.product == data) + .quantity + .toString(), + style: const TextStyle( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.bold), + ), + ), + ), + ) + : Align( + alignment: Alignment.topRight, + child: Container( + width: 36, + height: 36, + padding: const EdgeInsets.all(6), + decoration: const BoxDecoration( + borderRadius: + BorderRadius.all(Radius.circular(9.0)), + color: AppColors.primary, + ), + child: Assets.icons.shoppingBasket.svg(), + ), + ) + : Align( + alignment: Alignment.topRight, + child: Container( + width: 36, + height: 36, + padding: const EdgeInsets.all(6), + decoration: const BoxDecoration( + borderRadius: + BorderRadius.all(Radius.circular(9.0)), + color: AppColors.primary, + ), + child: Assets.icons.shoppingBasket.svg(), + ), + ); + }, + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/home/widgets/save_order_dialog.dart b/lib/presentation/home/widgets/save_order_dialog.dart new file mode 100644 index 0000000..e164aae --- /dev/null +++ b/lib/presentation/home/widgets/save_order_dialog.dart @@ -0,0 +1,205 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:intl/intl.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../table/blocs/get_table/get_table_bloc.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../bloc/order/order_bloc.dart'; +import '../models/order_type.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; + +class SaveOrderDialog extends StatefulWidget { + const SaveOrderDialog({ + super.key, + required this.data, + required this.totalQty, + required this.totalPrice, + required this.totalTax, + required this.totalDiscount, + required this.subTotal, + required this.normalPrice, + required this.table, + required this.draftName, + }); + final List data; + final int totalQty; + final int totalPrice; + final int totalTax; + final int totalDiscount; + final int subTotal; + final int normalPrice; + final TableModel table; + final String draftName; + + @override + State createState() => _SaveOrderDialogState(); +} + +class _SaveOrderDialogState extends State { + // List data = []; + // int totalQty = 0; + // int totalPrice = 0; + @override + Widget build(BuildContext context) { + return AlertDialog( + content: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center(child: Assets.icons.success.svg()), + const SpaceHeight(16.0), + const Center( + child: Text( + 'Order Berhasil Disimpan', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 20, + ), + ), + ), + const SpaceHeight(20.0), + Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () { + context + .read() + .add(const CheckoutEvent.started()); + context + .read() + .add(const GetTableEvent.getTables()); + context.popToRoot(); + }, + label: 'Kembali', + ), + ), + const SpaceWidth(8.0), + Flexible( + child: BlocBuilder( + builder: (context, state) { + final orderType = state.maybeWhen( + orElse: () => OrderType.dineIn, + loaded: (items, discountModel, discount, discountAmount, tax, serviceCharge, totalQuantity, totalPrice, draftName, orderType) => orderType, + ); + + return Button.filled( + onPressed: () async { + final checkerPrinter = await ProductLocalDatasource + .instance + .getPrinterByCode('checker'); + final kitchenPrinter = await ProductLocalDatasource + .instance + .getPrinterByCode('kitchen'); + final barPrinter = await ProductLocalDatasource.instance + .getPrinterByCode('bar'); + + log("Checker printer: ${checkerPrinter?.toMap()}"); + log("Kitchen printer: ${kitchenPrinter?.toMap()}"); + log("Bar printer: ${barPrinter?.toMap()}"); + + // Checker printer + if (checkerPrinter != null) { + try { + final printValue = await PrintDataoutputs.instance + .printChecker( + widget.data, + widget.table.tableName, + widget.draftName, + 'kasir', + checkerPrinter.paper.toIntegerFromText, + orderType.value); + + await PrinterService().printWithPrinter( + checkerPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing checker: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing checker: $e')), + ); + } + } + + // Kitchen printer + if (kitchenPrinter != null) { + try { + final printValue = await PrintDataoutputs.instance.printKitchen( + widget.data, + widget.table.tableName, + widget.draftName, + 'kasir', + kitchenPrinter.paper.toIntegerFromText, + orderType.value, + ); + + await PrinterService().printWithPrinter( + kitchenPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing kitchen order: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing kitchen order: $e')), + ); + } + } + + // Bar printer + if (barPrinter != null) { + try { + final printValue = await PrintDataoutputs.instance.printBar( + widget.data, + widget.table.tableName, + widget.draftName, + 'kasir', + barPrinter.paper.toIntegerFromText, + orderType.value, + ); + + await PrinterService().printWithPrinter( + barPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing bar order: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing bar order: $e')), + ); + } + } + }, + label: 'Print Checker', + ); + }, + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/home/widgets/success_payment_dialog.dart b/lib/presentation/home/widgets/success_payment_dialog.dart new file mode 100644 index 0000000..eaf331a --- /dev/null +++ b/lib/presentation/home/widgets/success_payment_dialog.dart @@ -0,0 +1,331 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart'; +import 'package:intl/intl.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/dataoutputs/laman_print.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; +import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../table/blocs/get_table/get_table_bloc.dart'; +import '../bloc/checkout/checkout_bloc.dart'; +import '../bloc/order/order_bloc.dart'; + +class SuccessPaymentDialog extends StatefulWidget { + const SuccessPaymentDialog({ + Key? key, + required this.data, + required this.totalQty, + required this.totalPrice, + required this.totalTax, + required this.totalDiscount, + required this.subTotal, + required this.normalPrice, + required this.totalService, + required this.draftName, + this.isTablePaymentPage = false, + }) : super(key: key); + final List data; + final int totalQty; + final int totalPrice; + final int totalTax; + final int totalDiscount; + final int subTotal; + final int normalPrice; + final int totalService; + final String draftName; + final bool? isTablePaymentPage; + @override + State createState() => _SuccessPaymentDialogState(); +} + +class _SuccessPaymentDialogState extends State { + // List data = []; + // int totalQty = 0; + // int totalPrice = 0; + @override + Widget build(BuildContext context) { + return AlertDialog( + content: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center(child: Assets.icons.success.svg()), + const SpaceHeight(16.0), + const Center( + child: Text( + 'Pembayaran telah sukses dilakukan', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 20, + ), + ), + ), + const SpaceHeight(20.0), + const Text('METODE BAYAR'), + const SpaceHeight(5.0), + BlocBuilder( + builder: (context, state) { + final paymentMethod = state.maybeWhen( + orElse: () => 'Cash', + loaded: (model, orderId) => model.paymentMethod, + ); + return Text( + paymentMethod, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ); + }, + ), + const SpaceHeight(10.0), + const Divider(), + const SpaceHeight(8.0), + const Text('TOTAL TAGIHAN'), + const SpaceHeight(5.0), + BlocBuilder( + builder: (context, state) { + final total = state.maybeWhen( + orElse: () => 0, + loaded: (model, orderId) => model.total, + ); + return Text( + widget.totalPrice.currencyFormatRp, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ); + }, + ), + const SpaceHeight(10.0), + const Divider(), + const SpaceHeight(8.0), + const Text('NOMINAL BAYAR'), + const SpaceHeight(5.0), + BlocBuilder( + builder: (context, state) { + final paymentAmount = state.maybeWhen( + orElse: () => 0, + loaded: (model, orderId) => model.paymentAmount, + ); + return Text( + paymentAmount.ceil().currencyFormatRp, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ); + }, + ), + const Divider(), + const SpaceHeight(8.0), + const Text('KEMBALIAN'), + const SpaceHeight(5.0), + BlocBuilder( + builder: (context, state) { + final paymentAmount = state.maybeWhen( + orElse: () => 0, + loaded: (model, orderId) => model.paymentAmount, + ); + final total = state.maybeWhen( + orElse: () => 0, + loaded: (model, orderId) => model.total, + ); + final diff = paymentAmount - total; + log("DIFF: $diff paymentAmount: $paymentAmount total: $total"); + return Text( + diff.ceil().currencyFormatRp, + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ); + }, + ), + const SpaceHeight(10.0), + const Divider(), + const SpaceHeight(8.0), + const Text('WAKTU PEMBAYARAN'), + const SpaceHeight(5.0), + Text( + DateFormat('dd MMMM yyyy, HH:mm').format(DateTime.now()), + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ), + const SpaceHeight(20.0), + Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () { + // For table payment page, just close the dialog + // The cleanup and navigation is handled by the payment page + if (widget.isTablePaymentPage == true) { + Navigator.of(context).pop(); // Close dialog only + } else { + // For regular payment flow, reset and go to root + context + .read() + .add(const CheckoutEvent.started()); + context + .read() + .add(const GetTableEvent.getTables()); + context.popToRoot(); + } + }, + label: 'Kembali', + ), + ), + const SpaceWidth(8.0), + Flexible( + child: BlocBuilder( + builder: (context, state) { + final paymentAmount = state.maybeWhen( + orElse: () => 0, + loaded: (model, orderId) => model.paymentAmount, + ); + + final kembalian = paymentAmount - widget.totalPrice; + return BlocBuilder( + builder: (context, checkoutState) { + final orderType = checkoutState.maybeWhen( + orElse: () => OrderType.dineIn, + loaded: (items, discountModel, discount, discountAmount, tax, serviceCharge, totalQuantity, totalPrice, draftName, orderType) => orderType, + ); + + return Button.filled( + onPressed: () async { + final receiptPrinter = await ProductLocalDatasource + .instance + .getPrinterByCode('receipt'); + final kitchenPrinter = await ProductLocalDatasource + .instance + .getPrinterByCode('kitchen'); + final barPrinter = await ProductLocalDatasource.instance + .getPrinterByCode('bar'); + + // Receipt Printer + if (receiptPrinter != null) { + try { + final settingsLocalDatasource = SettingsLocalDatasource(); + final taxModel = await settingsLocalDatasource.getTax(); + final serviceChargeValue = await settingsLocalDatasource.getServiceCharge(); + + // Get the actual payment method from OrderBloc + final paymentMethod = state.maybeWhen( + orElse: () => 'Cash', + loaded: (model, orderId) => model.paymentMethod, + ); + + final printValue = + await PrintDataoutputs.instance.printOrderV3( + widget.data, + widget.totalQty, + widget.totalPrice, + paymentMethod, + paymentAmount, + kembalian, + widget.subTotal, + widget.totalDiscount, + widget.totalTax, + widget.totalService, + 'kasir', + widget.draftName, + receiptPrinter.paper.toIntegerFromText, + taxPercentage: taxModel.value, + serviceChargePercentage: serviceChargeValue, + ); + + await PrinterService().printWithPrinter( + receiptPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing receipt: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing receipt: $e')), + ); + } + } + + // Kitchen Printer + if (kitchenPrinter != null && widget.isTablePaymentPage == false) { + try { + final printValue = await PrintDataoutputs.instance.printKitchen( + widget.data, + '', + widget.draftName, + 'kasir', + kitchenPrinter.paper.toIntegerFromText, + orderType.value, + ); + + await PrinterService().printWithPrinter( + kitchenPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing kitchen order: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing kitchen order: $e')), + ); + } + } + + // Bar printer + if (barPrinter != null && widget.isTablePaymentPage == false) { + try { + final printValue = await PrintDataoutputs.instance.printBar( + widget.data, + '', + widget.draftName, + 'kasir', + barPrinter.paper.toIntegerFromText, + orderType.value, + ); + + await PrinterService().printWithPrinter( + barPrinter, + printValue, + context + ); + } catch (e) { + log("Error printing bar order: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error printing bar order: $e')), + ); + } + } + }, + label: 'Print', + ); + }, + ); + }, + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart b/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart new file mode 100644 index 0000000..c5b3eba --- /dev/null +++ b/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/models/response/item_sales_response_model.dart'; +import 'package:enaklo_pos/data/datasources/order_item_remote_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'item_sales_report_event.dart'; +part 'item_sales_report_state.dart'; +part 'item_sales_report_bloc.freezed.dart'; + +class ItemSalesReportBloc + extends Bloc { + final OrderItemRemoteDatasource datasource; + ItemSalesReportBloc(this.datasource) : super(const _Initial()) { + on<_GetItemSales>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getItemSalesByRangeDate( + event.startDate, event.endDate); + result.fold((l) => emit(_Error(l)), (r) => emit(_Loaded(r.data!))); + }); + } +} diff --git a/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.freezed.dart b/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.freezed.dart new file mode 100644 index 0000000..c7012a7 --- /dev/null +++ b/lib/presentation/report/blocs/item_sales_report/item_sales_report_bloc.freezed.dart @@ -0,0 +1,957 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'item_sales_report_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$ItemSalesReportEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getItemSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getItemSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getItemSales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetItemSales value) getItemSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetItemSales value)? getItemSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetItemSales value)? getItemSales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ItemSalesReportEventCopyWith<$Res> { + factory $ItemSalesReportEventCopyWith(ItemSalesReportEvent value, + $Res Function(ItemSalesReportEvent) then) = + _$ItemSalesReportEventCopyWithImpl<$Res, ItemSalesReportEvent>; +} + +/// @nodoc +class _$ItemSalesReportEventCopyWithImpl<$Res, + $Val extends ItemSalesReportEvent> + implements $ItemSalesReportEventCopyWith<$Res> { + _$ItemSalesReportEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ItemSalesReportEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$ItemSalesReportEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'ItemSalesReportEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getItemSales, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getItemSales, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getItemSales, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetItemSales value) getItemSales, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetItemSales value)? getItemSales, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetItemSales value)? getItemSales, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements ItemSalesReportEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetItemSalesImplCopyWith<$Res> { + factory _$$GetItemSalesImplCopyWith( + _$GetItemSalesImpl value, $Res Function(_$GetItemSalesImpl) then) = + __$$GetItemSalesImplCopyWithImpl<$Res>; + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class __$$GetItemSalesImplCopyWithImpl<$Res> + extends _$ItemSalesReportEventCopyWithImpl<$Res, _$GetItemSalesImpl> + implements _$$GetItemSalesImplCopyWith<$Res> { + __$$GetItemSalesImplCopyWithImpl( + _$GetItemSalesImpl _value, $Res Function(_$GetItemSalesImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_$GetItemSalesImpl( + startDate: null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + endDate: null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetItemSalesImpl implements _GetItemSales { + const _$GetItemSalesImpl({required this.startDate, required this.endDate}); + + @override + final String startDate; + @override + final String endDate; + + @override + String toString() { + return 'ItemSalesReportEvent.getItemSales(startDate: $startDate, endDate: $endDate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetItemSalesImpl && + (identical(other.startDate, startDate) || + other.startDate == startDate) && + (identical(other.endDate, endDate) || other.endDate == endDate)); + } + + @override + int get hashCode => Object.hash(runtimeType, startDate, endDate); + + /// Create a copy of ItemSalesReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetItemSalesImplCopyWith<_$GetItemSalesImpl> get copyWith => + __$$GetItemSalesImplCopyWithImpl<_$GetItemSalesImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getItemSales, + }) { + return getItemSales(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getItemSales, + }) { + return getItemSales?.call(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getItemSales, + required TResult orElse(), + }) { + if (getItemSales != null) { + return getItemSales(startDate, endDate); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetItemSales value) getItemSales, + }) { + return getItemSales(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetItemSales value)? getItemSales, + }) { + return getItemSales?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetItemSales value)? getItemSales, + required TResult orElse(), + }) { + if (getItemSales != null) { + return getItemSales(this); + } + return orElse(); + } +} + +abstract class _GetItemSales implements ItemSalesReportEvent { + const factory _GetItemSales( + {required final String startDate, + required final String endDate}) = _$GetItemSalesImpl; + + String get startDate; + String get endDate; + + /// Create a copy of ItemSalesReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetItemSalesImplCopyWith<_$GetItemSalesImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$ItemSalesReportState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List itemSales) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List itemSales)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List itemSales)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ItemSalesReportStateCopyWith<$Res> { + factory $ItemSalesReportStateCopyWith(ItemSalesReportState value, + $Res Function(ItemSalesReportState) then) = + _$ItemSalesReportStateCopyWithImpl<$Res, ItemSalesReportState>; +} + +/// @nodoc +class _$ItemSalesReportStateCopyWithImpl<$Res, + $Val extends ItemSalesReportState> + implements $ItemSalesReportStateCopyWith<$Res> { + _$ItemSalesReportStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$ItemSalesReportStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'ItemSalesReportState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List itemSales) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List itemSales)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List itemSales)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements ItemSalesReportState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$ItemSalesReportStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'ItemSalesReportState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List itemSales) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List itemSales)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List itemSales)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements ItemSalesReportState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List itemSales}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$ItemSalesReportStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? itemSales = null, + }) { + return _then(_$LoadedImpl( + null == itemSales + ? _value._itemSales + : itemSales // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List itemSales) : _itemSales = itemSales; + + final List _itemSales; + @override + List get itemSales { + if (_itemSales is EqualUnmodifiableListView) return _itemSales; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_itemSales); + } + + @override + String toString() { + return 'ItemSalesReportState.loaded(itemSales: $itemSales)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality() + .equals(other._itemSales, _itemSales)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_itemSales)); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List itemSales) loaded, + required TResult Function(String message) error, + }) { + return loaded(itemSales); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List itemSales)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(itemSales); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List itemSales)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(itemSales); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements ItemSalesReportState { + const factory _Loaded(final List itemSales) = _$LoadedImpl; + + List get itemSales; + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$ItemSalesReportStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'ItemSalesReportState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List itemSales) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List itemSales)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List itemSales)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements ItemSalesReportState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of ItemSalesReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/report/blocs/item_sales_report/item_sales_report_event.dart b/lib/presentation/report/blocs/item_sales_report/item_sales_report_event.dart new file mode 100644 index 0000000..1935cf0 --- /dev/null +++ b/lib/presentation/report/blocs/item_sales_report/item_sales_report_event.dart @@ -0,0 +1,10 @@ +part of 'item_sales_report_bloc.dart'; + +@freezed +class ItemSalesReportEvent with _$ItemSalesReportEvent { + const factory ItemSalesReportEvent.started() = _Started; + const factory ItemSalesReportEvent.getItemSales({ + required String startDate, + required String endDate, + }) = _GetItemSales; +} diff --git a/lib/presentation/report/blocs/item_sales_report/item_sales_report_state.dart b/lib/presentation/report/blocs/item_sales_report/item_sales_report_state.dart new file mode 100644 index 0000000..c0b3de6 --- /dev/null +++ b/lib/presentation/report/blocs/item_sales_report/item_sales_report_state.dart @@ -0,0 +1,10 @@ +part of 'item_sales_report_bloc.dart'; + +@freezed +class ItemSalesReportState with _$ItemSalesReportState { + const factory ItemSalesReportState.initial() = _Initial; + const factory ItemSalesReportState.loading() = _Loading; + const factory ItemSalesReportState.loaded(List itemSales) = + _Loaded; + const factory ItemSalesReportState.error(String message) = _Error; +} diff --git a/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart b/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart new file mode 100644 index 0000000..a45ed06 --- /dev/null +++ b/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart @@ -0,0 +1,24 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'payment_method_report_event.dart'; +part 'payment_method_report_state.dart'; +part 'payment_method_report_bloc.freezed.dart'; + +class PaymentMethodReportBloc + extends Bloc { + final OrderRemoteDatasource datasource; + PaymentMethodReportBloc(this.datasource) : super(const _Initial()) { + on<_GetPaymentMethodReport>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getPaymentMethodByRangeDate( + event.startDate, + event.endDate, + ); + + result.fold((l) => emit(_Error(l)), (r) => emit(_Loaded(r.data!))); + }); + } +} \ No newline at end of file diff --git a/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.freezed.dart b/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.freezed.dart new file mode 100644 index 0000000..2671d58 --- /dev/null +++ b/lib/presentation/report/blocs/payment_method_report/payment_method_report_bloc.freezed.dart @@ -0,0 +1,874 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'payment_method_report_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$PaymentMethodReportEvent { + String get startDate => throw _privateConstructorUsedError; + String get endDate => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function(String startDate, String endDate) + getPaymentMethodReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String startDate, String endDate)? getPaymentMethodReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String startDate, String endDate)? getPaymentMethodReport, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_GetPaymentMethodReport value) + getPaymentMethodReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_GetPaymentMethodReport value)? getPaymentMethodReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_GetPaymentMethodReport value)? getPaymentMethodReport, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + /// Create a copy of PaymentMethodReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $PaymentMethodReportEventCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PaymentMethodReportEventCopyWith<$Res> { + factory $PaymentMethodReportEventCopyWith(PaymentMethodReportEvent value, + $Res Function(PaymentMethodReportEvent) then) = + _$PaymentMethodReportEventCopyWithImpl<$Res, PaymentMethodReportEvent>; + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class _$PaymentMethodReportEventCopyWithImpl<$Res, + $Val extends PaymentMethodReportEvent> + implements $PaymentMethodReportEventCopyWith<$Res> { + _$PaymentMethodReportEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of PaymentMethodReportEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_value.copyWith( + startDate: null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + endDate: null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$GetPaymentMethodReportImplCopyWith<$Res> + implements $PaymentMethodReportEventCopyWith<$Res> { + factory _$$GetPaymentMethodReportImplCopyWith( + _$GetPaymentMethodReportImpl value, + $Res Function(_$GetPaymentMethodReportImpl) then) = + __$$GetPaymentMethodReportImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class __$$GetPaymentMethodReportImplCopyWithImpl<$Res> + extends _$PaymentMethodReportEventCopyWithImpl<$Res, + _$GetPaymentMethodReportImpl> + implements _$$GetPaymentMethodReportImplCopyWith<$Res> { + __$$GetPaymentMethodReportImplCopyWithImpl( + _$GetPaymentMethodReportImpl _value, + $Res Function(_$GetPaymentMethodReportImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodReportEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_$GetPaymentMethodReportImpl( + startDate: null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + endDate: null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetPaymentMethodReportImpl implements _GetPaymentMethodReport { + const _$GetPaymentMethodReportImpl( + {required this.startDate, required this.endDate}); + + @override + final String startDate; + @override + final String endDate; + + @override + String toString() { + return 'PaymentMethodReportEvent.getPaymentMethodReport(startDate: $startDate, endDate: $endDate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetPaymentMethodReportImpl && + (identical(other.startDate, startDate) || + other.startDate == startDate) && + (identical(other.endDate, endDate) || other.endDate == endDate)); + } + + @override + int get hashCode => Object.hash(runtimeType, startDate, endDate); + + /// Create a copy of PaymentMethodReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetPaymentMethodReportImplCopyWith<_$GetPaymentMethodReportImpl> + get copyWith => __$$GetPaymentMethodReportImplCopyWithImpl< + _$GetPaymentMethodReportImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(String startDate, String endDate) + getPaymentMethodReport, + }) { + return getPaymentMethodReport(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String startDate, String endDate)? getPaymentMethodReport, + }) { + return getPaymentMethodReport?.call(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String startDate, String endDate)? getPaymentMethodReport, + required TResult orElse(), + }) { + if (getPaymentMethodReport != null) { + return getPaymentMethodReport(startDate, endDate); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_GetPaymentMethodReport value) + getPaymentMethodReport, + }) { + return getPaymentMethodReport(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_GetPaymentMethodReport value)? getPaymentMethodReport, + }) { + return getPaymentMethodReport?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_GetPaymentMethodReport value)? getPaymentMethodReport, + required TResult orElse(), + }) { + if (getPaymentMethodReport != null) { + return getPaymentMethodReport(this); + } + return orElse(); + } +} + +abstract class _GetPaymentMethodReport implements PaymentMethodReportEvent { + const factory _GetPaymentMethodReport( + {required final String startDate, + required final String endDate}) = _$GetPaymentMethodReportImpl; + + @override + String get startDate; + @override + String get endDate; + + /// Create a copy of PaymentMethodReportEvent + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetPaymentMethodReportImplCopyWith<_$GetPaymentMethodReportImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$PaymentMethodReportState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PaymentMethodData data) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PaymentMethodData data)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PaymentMethodData data)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PaymentMethodReportStateCopyWith<$Res> { + factory $PaymentMethodReportStateCopyWith(PaymentMethodReportState value, + $Res Function(PaymentMethodReportState) then) = + _$PaymentMethodReportStateCopyWithImpl<$Res, PaymentMethodReportState>; +} + +/// @nodoc +class _$PaymentMethodReportStateCopyWithImpl<$Res, + $Val extends PaymentMethodReportState> + implements $PaymentMethodReportStateCopyWith<$Res> { + _$PaymentMethodReportStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$PaymentMethodReportStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'PaymentMethodReportState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PaymentMethodData data) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PaymentMethodData data)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PaymentMethodData data)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements PaymentMethodReportState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$PaymentMethodReportStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'PaymentMethodReportState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PaymentMethodData data) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PaymentMethodData data)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PaymentMethodData data)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements PaymentMethodReportState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({PaymentMethodData data}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$PaymentMethodReportStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? data = null, + }) { + return _then(_$LoadedImpl( + null == data + ? _value.data + : data // ignore: cast_nullable_to_non_nullable + as PaymentMethodData, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(this.data); + + @override + final PaymentMethodData data; + + @override + String toString() { + return 'PaymentMethodReportState.loaded(data: $data)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + (identical(other.data, data) || other.data == data)); + } + + @override + int get hashCode => Object.hash(runtimeType, data); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PaymentMethodData data) loaded, + required TResult Function(String message) error, + }) { + return loaded(data); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PaymentMethodData data)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(data); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PaymentMethodData data)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(data); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements PaymentMethodReportState { + const factory _Loaded(final PaymentMethodData data) = _$LoadedImpl; + + PaymentMethodData get data; + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$PaymentMethodReportStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'PaymentMethodReportState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PaymentMethodData data) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PaymentMethodData data)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PaymentMethodData data)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements PaymentMethodReportState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of PaymentMethodReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/report/blocs/payment_method_report/payment_method_report_event.dart b/lib/presentation/report/blocs/payment_method_report/payment_method_report_event.dart new file mode 100644 index 0000000..55cd10f --- /dev/null +++ b/lib/presentation/report/blocs/payment_method_report/payment_method_report_event.dart @@ -0,0 +1,9 @@ +part of 'payment_method_report_bloc.dart'; + +@freezed +class PaymentMethodReportEvent with _$PaymentMethodReportEvent { + const factory PaymentMethodReportEvent.getPaymentMethodReport({ + required String startDate, + required String endDate, + }) = _GetPaymentMethodReport; +} \ No newline at end of file diff --git a/lib/presentation/report/blocs/payment_method_report/payment_method_report_state.dart b/lib/presentation/report/blocs/payment_method_report/payment_method_report_state.dart new file mode 100644 index 0000000..70cb241 --- /dev/null +++ b/lib/presentation/report/blocs/payment_method_report/payment_method_report_state.dart @@ -0,0 +1,9 @@ +part of 'payment_method_report_bloc.dart'; + +@freezed +class PaymentMethodReportState with _$PaymentMethodReportState { + const factory PaymentMethodReportState.initial() = _Initial; + const factory PaymentMethodReportState.loading() = _Loading; + const factory PaymentMethodReportState.loaded(PaymentMethodData data) = _Loaded; + const factory PaymentMethodReportState.error(String message) = _Error; +} \ No newline at end of file diff --git a/lib/presentation/report/blocs/product_sales/product_sales_bloc.dart b/lib/presentation/report/blocs/product_sales/product_sales_bloc.dart new file mode 100644 index 0000000..0aaf866 --- /dev/null +++ b/lib/presentation/report/blocs/product_sales/product_sales_bloc.dart @@ -0,0 +1,22 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/order_item_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/product_sales_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'product_sales_event.dart'; +part 'product_sales_state.dart'; +part 'product_sales_bloc.freezed.dart'; + +class ProductSalesBloc extends Bloc { + final OrderItemRemoteDatasource datasource; + ProductSalesBloc( + this.datasource, + ) : super(const _Initial()) { + on<_GetProductSales>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getProductSalesByRangeDate( + event.startDate, event.endDate); + result.fold((l) => emit(_Error(l)), (r) => emit(_Success(r.data!))); + }); + } +} diff --git a/lib/presentation/report/blocs/product_sales/product_sales_bloc.freezed.dart b/lib/presentation/report/blocs/product_sales/product_sales_bloc.freezed.dart new file mode 100644 index 0000000..c44d742 --- /dev/null +++ b/lib/presentation/report/blocs/product_sales/product_sales_bloc.freezed.dart @@ -0,0 +1,956 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'product_sales_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$ProductSalesEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getProductSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getProductSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getProductSales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetProductSales value) getProductSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetProductSales value)? getProductSales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetProductSales value)? getProductSales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ProductSalesEventCopyWith<$Res> { + factory $ProductSalesEventCopyWith( + ProductSalesEvent value, $Res Function(ProductSalesEvent) then) = + _$ProductSalesEventCopyWithImpl<$Res, ProductSalesEvent>; +} + +/// @nodoc +class _$ProductSalesEventCopyWithImpl<$Res, $Val extends ProductSalesEvent> + implements $ProductSalesEventCopyWith<$Res> { + _$ProductSalesEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ProductSalesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$ProductSalesEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'ProductSalesEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getProductSales, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getProductSales, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getProductSales, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetProductSales value) getProductSales, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetProductSales value)? getProductSales, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetProductSales value)? getProductSales, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements ProductSalesEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetProductSalesImplCopyWith<$Res> { + factory _$$GetProductSalesImplCopyWith(_$GetProductSalesImpl value, + $Res Function(_$GetProductSalesImpl) then) = + __$$GetProductSalesImplCopyWithImpl<$Res>; + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class __$$GetProductSalesImplCopyWithImpl<$Res> + extends _$ProductSalesEventCopyWithImpl<$Res, _$GetProductSalesImpl> + implements _$$GetProductSalesImplCopyWith<$Res> { + __$$GetProductSalesImplCopyWithImpl( + _$GetProductSalesImpl _value, $Res Function(_$GetProductSalesImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_$GetProductSalesImpl( + null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetProductSalesImpl implements _GetProductSales { + const _$GetProductSalesImpl(this.startDate, this.endDate); + + @override + final String startDate; + @override + final String endDate; + + @override + String toString() { + return 'ProductSalesEvent.getProductSales(startDate: $startDate, endDate: $endDate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetProductSalesImpl && + (identical(other.startDate, startDate) || + other.startDate == startDate) && + (identical(other.endDate, endDate) || other.endDate == endDate)); + } + + @override + int get hashCode => Object.hash(runtimeType, startDate, endDate); + + /// Create a copy of ProductSalesEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetProductSalesImplCopyWith<_$GetProductSalesImpl> get copyWith => + __$$GetProductSalesImplCopyWithImpl<_$GetProductSalesImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getProductSales, + }) { + return getProductSales(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getProductSales, + }) { + return getProductSales?.call(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getProductSales, + required TResult orElse(), + }) { + if (getProductSales != null) { + return getProductSales(startDate, endDate); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetProductSales value) getProductSales, + }) { + return getProductSales(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetProductSales value)? getProductSales, + }) { + return getProductSales?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetProductSales value)? getProductSales, + required TResult orElse(), + }) { + if (getProductSales != null) { + return getProductSales(this); + } + return orElse(); + } +} + +abstract class _GetProductSales implements ProductSalesEvent { + const factory _GetProductSales(final String startDate, final String endDate) = + _$GetProductSalesImpl; + + String get startDate; + String get endDate; + + /// Create a copy of ProductSalesEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetProductSalesImplCopyWith<_$GetProductSalesImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$ProductSalesState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List productSales) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List productSales)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List productSales)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ProductSalesStateCopyWith<$Res> { + factory $ProductSalesStateCopyWith( + ProductSalesState value, $Res Function(ProductSalesState) then) = + _$ProductSalesStateCopyWithImpl<$Res, ProductSalesState>; +} + +/// @nodoc +class _$ProductSalesStateCopyWithImpl<$Res, $Val extends ProductSalesState> + implements $ProductSalesStateCopyWith<$Res> { + _$ProductSalesStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$ProductSalesStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'ProductSalesState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List productSales) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List productSales)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List productSales)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements ProductSalesState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$ProductSalesStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'ProductSalesState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List productSales) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List productSales)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List productSales)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements ProductSalesState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({List productSales}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$ProductSalesStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? productSales = null, + }) { + return _then(_$SuccessImpl( + null == productSales + ? _value._productSales + : productSales // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(final List productSales) + : _productSales = productSales; + + final List _productSales; + @override + List get productSales { + if (_productSales is EqualUnmodifiableListView) return _productSales; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_productSales); + } + + @override + String toString() { + return 'ProductSalesState.success(productSales: $productSales)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + const DeepCollectionEquality() + .equals(other._productSales, _productSales)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_productSales)); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List productSales) success, + required TResult Function(String message) error, + }) { + return success(productSales); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List productSales)? success, + TResult? Function(String message)? error, + }) { + return success?.call(productSales); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List productSales)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(productSales); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements ProductSalesState { + const factory _Success(final List productSales) = _$SuccessImpl; + + List get productSales; + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$ProductSalesStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'ProductSalesState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List productSales) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List productSales)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List productSales)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements ProductSalesState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of ProductSalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/report/blocs/product_sales/product_sales_event.dart b/lib/presentation/report/blocs/product_sales/product_sales_event.dart new file mode 100644 index 0000000..8ff24f2 --- /dev/null +++ b/lib/presentation/report/blocs/product_sales/product_sales_event.dart @@ -0,0 +1,10 @@ +part of 'product_sales_bloc.dart'; + +@freezed +class ProductSalesEvent with _$ProductSalesEvent { + const factory ProductSalesEvent.started() = _Started; + const factory ProductSalesEvent.getProductSales( + String startDate, + String endDate, + ) = _GetProductSales; +} diff --git a/lib/presentation/report/blocs/product_sales/product_sales_state.dart b/lib/presentation/report/blocs/product_sales/product_sales_state.dart new file mode 100644 index 0000000..ddf4a39 --- /dev/null +++ b/lib/presentation/report/blocs/product_sales/product_sales_state.dart @@ -0,0 +1,13 @@ +part of 'product_sales_bloc.dart'; + +@freezed +class ProductSalesState with _$ProductSalesState { + const factory ProductSalesState.initial() = _Initial; + + const factory ProductSalesState.loading() = _Loading; + + const factory ProductSalesState.success(List productSales) = + _Success; + + const factory ProductSalesState.error(String message) = _Error; +} diff --git a/lib/presentation/report/blocs/summary/summary_bloc.dart b/lib/presentation/report/blocs/summary/summary_bloc.dart new file mode 100644 index 0000000..f48e5c9 --- /dev/null +++ b/lib/presentation/report/blocs/summary/summary_bloc.dart @@ -0,0 +1,22 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/summary_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'summary_event.dart'; +part 'summary_state.dart'; +part 'summary_bloc.freezed.dart'; + +class SummaryBloc extends Bloc { + final OrderRemoteDatasource datasource; + SummaryBloc( + this.datasource, + ) : super(const _Initial()) { + on<_GetSummary>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getSummaryByRangeDate( + event.startDate, event.endDate); + result.fold((l) => emit(_Error(l)), (r) => emit(_Success(r.data!))); + }); + } +} diff --git a/lib/presentation/report/blocs/summary/summary_bloc.freezed.dart b/lib/presentation/report/blocs/summary/summary_bloc.freezed.dart new file mode 100644 index 0000000..7bc2fe5 --- /dev/null +++ b/lib/presentation/report/blocs/summary/summary_bloc.freezed.dart @@ -0,0 +1,947 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'summary_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$SummaryEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getSummary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetSummary value) getSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetSummary value)? getSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetSummary value)? getSummary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SummaryEventCopyWith<$Res> { + factory $SummaryEventCopyWith( + SummaryEvent value, $Res Function(SummaryEvent) then) = + _$SummaryEventCopyWithImpl<$Res, SummaryEvent>; +} + +/// @nodoc +class _$SummaryEventCopyWithImpl<$Res, $Val extends SummaryEvent> + implements $SummaryEventCopyWith<$Res> { + _$SummaryEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SummaryEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$SummaryEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'SummaryEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getSummary, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getSummary, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getSummary, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetSummary value) getSummary, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetSummary value)? getSummary, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetSummary value)? getSummary, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements SummaryEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetSummaryImplCopyWith<$Res> { + factory _$$GetSummaryImplCopyWith( + _$GetSummaryImpl value, $Res Function(_$GetSummaryImpl) then) = + __$$GetSummaryImplCopyWithImpl<$Res>; + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class __$$GetSummaryImplCopyWithImpl<$Res> + extends _$SummaryEventCopyWithImpl<$Res, _$GetSummaryImpl> + implements _$$GetSummaryImplCopyWith<$Res> { + __$$GetSummaryImplCopyWithImpl( + _$GetSummaryImpl _value, $Res Function(_$GetSummaryImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_$GetSummaryImpl( + null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetSummaryImpl implements _GetSummary { + const _$GetSummaryImpl(this.startDate, this.endDate); + + @override + final String startDate; + @override + final String endDate; + + @override + String toString() { + return 'SummaryEvent.getSummary(startDate: $startDate, endDate: $endDate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetSummaryImpl && + (identical(other.startDate, startDate) || + other.startDate == startDate) && + (identical(other.endDate, endDate) || other.endDate == endDate)); + } + + @override + int get hashCode => Object.hash(runtimeType, startDate, endDate); + + /// Create a copy of SummaryEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetSummaryImplCopyWith<_$GetSummaryImpl> get copyWith => + __$$GetSummaryImplCopyWithImpl<_$GetSummaryImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getSummary, + }) { + return getSummary(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getSummary, + }) { + return getSummary?.call(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getSummary, + required TResult orElse(), + }) { + if (getSummary != null) { + return getSummary(startDate, endDate); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetSummary value) getSummary, + }) { + return getSummary(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetSummary value)? getSummary, + }) { + return getSummary?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetSummary value)? getSummary, + required TResult orElse(), + }) { + if (getSummary != null) { + return getSummary(this); + } + return orElse(); + } +} + +abstract class _GetSummary implements SummaryEvent { + const factory _GetSummary(final String startDate, final String endDate) = + _$GetSummaryImpl; + + String get startDate; + String get endDate; + + /// Create a copy of SummaryEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetSummaryImplCopyWith<_$GetSummaryImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$SummaryState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(SummaryModel summary) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(SummaryModel summary)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(SummaryModel summary)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SummaryStateCopyWith<$Res> { + factory $SummaryStateCopyWith( + SummaryState value, $Res Function(SummaryState) then) = + _$SummaryStateCopyWithImpl<$Res, SummaryState>; +} + +/// @nodoc +class _$SummaryStateCopyWithImpl<$Res, $Val extends SummaryState> + implements $SummaryStateCopyWith<$Res> { + _$SummaryStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$SummaryStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'SummaryState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(SummaryModel summary) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(SummaryModel summary)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(SummaryModel summary)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements SummaryState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$SummaryStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'SummaryState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(SummaryModel summary) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(SummaryModel summary)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(SummaryModel summary)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements SummaryState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({SummaryModel summary}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$SummaryStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? summary = null, + }) { + return _then(_$SuccessImpl( + null == summary + ? _value.summary + : summary // ignore: cast_nullable_to_non_nullable + as SummaryModel, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.summary); + + @override + final SummaryModel summary; + + @override + String toString() { + return 'SummaryState.success(summary: $summary)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.summary, summary) || other.summary == summary)); + } + + @override + int get hashCode => Object.hash(runtimeType, summary); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(SummaryModel summary) success, + required TResult Function(String message) error, + }) { + return success(summary); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(SummaryModel summary)? success, + TResult? Function(String message)? error, + }) { + return success?.call(summary); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(SummaryModel summary)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(summary); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements SummaryState { + const factory _Success(final SummaryModel summary) = _$SuccessImpl; + + SummaryModel get summary; + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$SummaryStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'SummaryState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(SummaryModel summary) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(SummaryModel summary)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(SummaryModel summary)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements SummaryState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of SummaryState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/report/blocs/summary/summary_event.dart b/lib/presentation/report/blocs/summary/summary_event.dart new file mode 100644 index 0000000..febbb48 --- /dev/null +++ b/lib/presentation/report/blocs/summary/summary_event.dart @@ -0,0 +1,8 @@ +part of 'summary_bloc.dart'; + +@freezed +class SummaryEvent with _$SummaryEvent { + const factory SummaryEvent.started() = _Started; + const factory SummaryEvent.getSummary(String startDate, String endDate) = + _GetSummary; +} diff --git a/lib/presentation/report/blocs/summary/summary_state.dart b/lib/presentation/report/blocs/summary/summary_state.dart new file mode 100644 index 0000000..37dd6e8 --- /dev/null +++ b/lib/presentation/report/blocs/summary/summary_state.dart @@ -0,0 +1,9 @@ +part of 'summary_bloc.dart'; + +@freezed +class SummaryState with _$SummaryState { + const factory SummaryState.initial() = _Initial; + const factory SummaryState.loading() = _Loading; + const factory SummaryState.success(SummaryModel summary) = _Success; + const factory SummaryState.error(String message) = _Error; +} diff --git a/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.dart b/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.dart new file mode 100644 index 0000000..900ef15 --- /dev/null +++ b/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.dart @@ -0,0 +1,25 @@ + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'transaction_report_event.dart'; +part 'transaction_report_state.dart'; +part 'transaction_report_bloc.freezed.dart'; + +class TransactionReportBloc + extends Bloc { + final OrderRemoteDatasource datasource; + TransactionReportBloc(this.datasource) : super(const _Initial()) { + on<_GetReport>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getOrderByRangeDate( + event.startDate, + event.endDate, + ); + + result.fold((l) => emit(_Error(l)), (r) => emit(_Loaded(r.data!))); + }); + } +} diff --git a/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.freezed.dart b/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.freezed.dart new file mode 100644 index 0000000..08db8b8 --- /dev/null +++ b/lib/presentation/report/blocs/transaction_report/transaction_report_bloc.freezed.dart @@ -0,0 +1,959 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'transaction_report_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$TransactionReportEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getReport, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetReport value) getReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetReport value)? getReport, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetReport value)? getReport, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TransactionReportEventCopyWith<$Res> { + factory $TransactionReportEventCopyWith(TransactionReportEvent value, + $Res Function(TransactionReportEvent) then) = + _$TransactionReportEventCopyWithImpl<$Res, TransactionReportEvent>; +} + +/// @nodoc +class _$TransactionReportEventCopyWithImpl<$Res, + $Val extends TransactionReportEvent> + implements $TransactionReportEventCopyWith<$Res> { + _$TransactionReportEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TransactionReportEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$TransactionReportEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'TransactionReportEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getReport, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getReport, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getReport, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetReport value) getReport, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetReport value)? getReport, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetReport value)? getReport, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements TransactionReportEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetReportImplCopyWith<$Res> { + factory _$$GetReportImplCopyWith( + _$GetReportImpl value, $Res Function(_$GetReportImpl) then) = + __$$GetReportImplCopyWithImpl<$Res>; + @useResult + $Res call({String startDate, String endDate}); +} + +/// @nodoc +class __$$GetReportImplCopyWithImpl<$Res> + extends _$TransactionReportEventCopyWithImpl<$Res, _$GetReportImpl> + implements _$$GetReportImplCopyWith<$Res> { + __$$GetReportImplCopyWithImpl( + _$GetReportImpl _value, $Res Function(_$GetReportImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? startDate = null, + Object? endDate = null, + }) { + return _then(_$GetReportImpl( + startDate: null == startDate + ? _value.startDate + : startDate // ignore: cast_nullable_to_non_nullable + as String, + endDate: null == endDate + ? _value.endDate + : endDate // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$GetReportImpl implements _GetReport { + const _$GetReportImpl({required this.startDate, required this.endDate}); + + @override + final String startDate; + @override + final String endDate; + + @override + String toString() { + return 'TransactionReportEvent.getReport(startDate: $startDate, endDate: $endDate)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetReportImpl && + (identical(other.startDate, startDate) || + other.startDate == startDate) && + (identical(other.endDate, endDate) || other.endDate == endDate)); + } + + @override + int get hashCode => Object.hash(runtimeType, startDate, endDate); + + /// Create a copy of TransactionReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetReportImplCopyWith<_$GetReportImpl> get copyWith => + __$$GetReportImplCopyWithImpl<_$GetReportImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String startDate, String endDate) getReport, + }) { + return getReport(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String startDate, String endDate)? getReport, + }) { + return getReport?.call(startDate, endDate); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String startDate, String endDate)? getReport, + required TResult orElse(), + }) { + if (getReport != null) { + return getReport(startDate, endDate); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetReport value) getReport, + }) { + return getReport(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetReport value)? getReport, + }) { + return getReport?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetReport value)? getReport, + required TResult orElse(), + }) { + if (getReport != null) { + return getReport(this); + } + return orElse(); + } +} + +abstract class _GetReport implements TransactionReportEvent { + const factory _GetReport( + {required final String startDate, + required final String endDate}) = _$GetReportImpl; + + String get startDate; + String get endDate; + + /// Create a copy of TransactionReportEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetReportImplCopyWith<_$GetReportImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$TransactionReportState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function(List transactionReport) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function(List transactionReport)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function(List transactionReport)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Loaded value) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Loaded value)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TransactionReportStateCopyWith<$Res> { + factory $TransactionReportStateCopyWith(TransactionReportState value, + $Res Function(TransactionReportState) then) = + _$TransactionReportStateCopyWithImpl<$Res, TransactionReportState>; +} + +/// @nodoc +class _$TransactionReportStateCopyWithImpl<$Res, + $Val extends TransactionReportState> + implements $TransactionReportStateCopyWith<$Res> { + _$TransactionReportStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$TransactionReportStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'TransactionReportState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function(List transactionReport) loaded, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function(List transactionReport)? loaded, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function(List transactionReport)? loaded, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Loaded value) loaded, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Loaded value)? loaded, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements TransactionReportState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$TransactionReportStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'TransactionReportState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function(List transactionReport) loaded, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function(List transactionReport)? loaded, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function(List transactionReport)? loaded, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Loaded value) loaded, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Loaded value)? loaded, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements TransactionReportState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$TransactionReportStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'TransactionReportState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function(List transactionReport) loaded, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function(List transactionReport)? loaded, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function(List transactionReport)? loaded, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Loaded value) loaded, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Loaded value)? loaded, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements TransactionReportState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List transactionReport}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$TransactionReportStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? transactionReport = null, + }) { + return _then(_$LoadedImpl( + null == transactionReport + ? _value._transactionReport + : transactionReport // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List transactionReport) + : _transactionReport = transactionReport; + + final List _transactionReport; + @override + List get transactionReport { + if (_transactionReport is EqualUnmodifiableListView) + return _transactionReport; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_transactionReport); + } + + @override + String toString() { + return 'TransactionReportState.loaded(transactionReport: $transactionReport)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality() + .equals(other._transactionReport, _transactionReport)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_transactionReport)); + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function(List transactionReport) loaded, + }) { + return loaded(transactionReport); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function(List transactionReport)? loaded, + }) { + return loaded?.call(transactionReport); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function(List transactionReport)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(transactionReport); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Loaded value) loaded, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Loaded value)? loaded, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements TransactionReportState { + const factory _Loaded(final List transactionReport) = _$LoadedImpl; + + List get transactionReport; + + /// Create a copy of TransactionReportState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/report/blocs/transaction_report/transaction_report_event.dart b/lib/presentation/report/blocs/transaction_report/transaction_report_event.dart new file mode 100644 index 0000000..6be82bf --- /dev/null +++ b/lib/presentation/report/blocs/transaction_report/transaction_report_event.dart @@ -0,0 +1,10 @@ +part of 'transaction_report_bloc.dart'; + +@freezed +class TransactionReportEvent with _$TransactionReportEvent { + const factory TransactionReportEvent.started() = _Started; + const factory TransactionReportEvent.getReport({ + required String startDate, + required String endDate, + }) = _GetReport; +} diff --git a/lib/presentation/report/blocs/transaction_report/transaction_report_state.dart b/lib/presentation/report/blocs/transaction_report/transaction_report_state.dart new file mode 100644 index 0000000..7f8f81d --- /dev/null +++ b/lib/presentation/report/blocs/transaction_report/transaction_report_state.dart @@ -0,0 +1,10 @@ +part of 'transaction_report_bloc.dart'; + +@freezed +class TransactionReportState with _$TransactionReportState { + const factory TransactionReportState.initial() = _Initial; + const factory TransactionReportState.loading() = _Loading; + const factory TransactionReportState.error(String message) = _Error; + const factory TransactionReportState.loaded( + List transactionReport) = _Loaded; +} diff --git a/lib/presentation/report/pages/report_page.dart b/lib/presentation/report/pages/report_page.dart new file mode 100644 index 0000000..2bf9c10 --- /dev/null +++ b/lib/presentation/report/pages/report_page.dart @@ -0,0 +1,349 @@ +import 'dart:developer'; + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/custom_date_picker.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/utils/date_formatter.dart'; +import 'package:enaklo_pos/presentation/report/blocs/item_sales_report/item_sales_report_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/payment_method_report/payment_method_report_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/product_sales/product_sales_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/summary/summary_bloc.dart'; +import 'package:enaklo_pos/presentation/report/blocs/transaction_report/transaction_report_bloc.dart'; +import 'package:enaklo_pos/presentation/report/widgets/item_sales_report_widget.dart'; +import 'package:enaklo_pos/presentation/report/widgets/payment_method_report_widget.dart'; +import 'package:enaklo_pos/presentation/report/widgets/product_sales_chart_widget.dart'; +import 'package:enaklo_pos/presentation/report/widgets/report_menu.dart'; +import 'package:enaklo_pos/presentation/report/widgets/report_title.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/presentation/report/widgets/summary_report_widget.dart'; +import 'package:enaklo_pos/presentation/report/widgets/transaction_report_widget.dart'; + +import '../../../core/components/spaces.dart'; + +class ReportPage extends StatefulWidget { + const ReportPage({super.key}); + + @override + State createState() => _ReportPageState(); +} + +class _ReportPageState extends State { + int selectedMenu = 0; + String title = 'Transaction Report'; + DateTime fromDate = DateTime.now().subtract(const Duration(days: 30)); + DateTime toDate = DateTime.now(); + + @override + Widget build(BuildContext context) { + String searchDateFormatted = + '${fromDate.toFormattedDate2()} to ${toDate.toFormattedDate2()}'; + return Scaffold( + body: Row( + children: [ + // LEFT CONTENT + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topLeft, + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const ReportTitle(), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Flexible( + child: CustomDatePicker( + prefix: const Text('From: '), + initialDate: fromDate, + onDateSelected: (selectedDate) { + fromDate = selectedDate; + + setState(() {}); + }, + ), + ), + const SpaceWidth(24.0), + Flexible( + child: CustomDatePicker( + prefix: const Text('To: '), + initialDate: toDate, + onDateSelected: (selectedDate) { + toDate = selectedDate; + setState(() {}); + // context.read().add( + // TransactionReportEvent.getReport( + // startDate: + // DateFormatter.formatDateTime( + // fromDate), + // endDate: DateFormatter.formatDateTime( + // toDate)), + // ); + // context.read().add( + // ItemSalesReportEvent.getItemSales( + // startDate: + // DateFormatter.formatDateTime( + // fromDate), + // endDate: DateFormatter.formatDateTime( + // toDate)), + // ); + }, + ), + ), + ], + ), + Padding( + padding: const EdgeInsets.all(15.0), + child: Wrap( + children: [ + ReportMenu( + label: 'Transaction Report', + onPressed: () { + selectedMenu = 0; + title = 'Transaction Report'; + setState(() {}); + //enddate is 1 month before the current date + context.read().add( + TransactionReportEvent.getReport( + startDate: DateFormatter.formatDateTime( + fromDate), + endDate: DateFormatter.formatDateTime( + toDate)), + ); + }, + isActive: selectedMenu == 0, + ), + ReportMenu( + label: 'Item Sales Report', + onPressed: () { + selectedMenu = 1; + title = 'Item Sales Report'; + setState(() {}); + context.read().add( + ItemSalesReportEvent.getItemSales( + startDate: DateFormatter.formatDateTime( + fromDate), + endDate: DateFormatter.formatDateTime( + toDate)), + ); + }, + isActive: selectedMenu == 1, + ), + ReportMenu( + label: 'Product Sales Chart', + onPressed: () { + selectedMenu = 2; + title = 'Product Sales Chart'; + setState(() {}); + context.read().add( + ProductSalesEvent.getProductSales( + DateFormatter.formatDateTime(fromDate), + DateFormatter.formatDateTime(toDate)), + ); + }, + isActive: selectedMenu == 2, + ), + ReportMenu( + label: 'Summary Sales Report', + onPressed: () { + selectedMenu = 3; + title = 'Summary Sales Report'; + setState(() {}); + context.read().add( + SummaryEvent.getSummary( + DateFormatter.formatDateTime(fromDate), + DateFormatter.formatDateTime(toDate)), + ); + + log("Date ${DateFormatter.formatDateTime(fromDate)}"); + }, + isActive: selectedMenu == 3, + ), + ReportMenu( + label: 'Payment Method Report', + onPressed: () { + selectedMenu = 4; + title = 'Payment Method Report'; + setState(() {}); + context.read().add( + PaymentMethodReportEvent.getPaymentMethodReport( + startDate: DateFormatter.formatDateTime(fromDate), + endDate: DateFormatter.formatDateTime(toDate)), + ); + }, + isActive: selectedMenu == 4, + ), + ], + ), + ), + ], + ), + ), + ), + ), + + // RIGHT CONTENT + Expanded( + flex: 2, + child: selectedMenu == 0 + ? BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + error: (message) { + return Text(message); + }, + loaded: (transactionReport) { + return TransactionReportWidget( + transactionReport: transactionReport, + title: title, + searchDateFormatted: searchDateFormatted, + headerWidgets: _getTitleReportPageWidget(), + ); + }, + ); + }, + ) + : selectedMenu == 1 + ? BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + error: (message) { + return Text(message); + }, + loaded: (itemSales) { + return ItemSalesReportWidget( + itemSales: itemSales, + title: title, + searchDateFormatted: searchDateFormatted, + headerWidgets: _getItemSalesPageWidget(), + ); + }, + ); + }, + ) + : selectedMenu == 2 + ? BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + error: (message) { + return Text(message); + }, + success: (productSales) { + return ProductSalesChartWidgets( + title: title, + searchDateFormatted: searchDateFormatted, + productSales: productSales, + ); + }, + ); + }, + ) + : selectedMenu == 3 + ? BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + error: (message) { + return Text(message); + }, + success: (summary) { + return SummaryReportWidget( + summary: summary, + title: title, + searchDateFormatted: searchDateFormatted, + ); + }, + ); + }, + ) + : selectedMenu == 4 + ? BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + error: (message) { + return Text(message); + }, + loaded: (paymentMethodData) { + return PaymentMethodReportWidget( + paymentMethodData: paymentMethodData, + title: title, + searchDateFormatted: searchDateFormatted, + headerWidgets: _getPaymentMethodPageWidget(), + ); + }, + ); + }, + ) + : const SizedBox.shrink()), + ], + ), + ); + } + + List _getTitleReportPageWidget() { + return [ + _getTitleItemWidget('ID', 120), + _getTitleItemWidget('Total', 100), + _getTitleItemWidget('Sub Total', 100), + _getTitleItemWidget('Tax', 100), + _getTitleItemWidget('Disocunt', 100), + _getTitleItemWidget('Service', 100), + _getTitleItemWidget('Total Item', 100), + _getTitleItemWidget('Cashier', 180), + _getTitleItemWidget('Time', 200), + ]; + } + + List _getItemSalesPageWidget() { + return [ + _getTitleItemWidget('ID', 80), + _getTitleItemWidget('Order', 60), + _getTitleItemWidget('Product', 160), + _getTitleItemWidget('Qty', 60), + _getTitleItemWidget('Price', 140), + _getTitleItemWidget('Total Price', 140), + ]; + } + + List _getPaymentMethodPageWidget() { + return [ + _getTitleItemWidget('Payment Method', 180), + _getTitleItemWidget('Total Amount', 180), + _getTitleItemWidget('Transaction Count', 180), + ]; + } + + Widget _getTitleItemWidget(String label, double width) { + return Container( + width: width, + height: 56, + color: AppColors.primary, + alignment: Alignment.centerLeft, + child: Center( + child: Text( + label, + style: TextStyle( + color: Colors.white, + ), + ), + ), + ); + } +} diff --git a/lib/presentation/report/widgets/item_sales_report_widget.dart b/lib/presentation/report/widgets/item_sales_report_widget.dart new file mode 100644 index 0000000..be0fffc --- /dev/null +++ b/lib/presentation/report/widgets/item_sales_report_widget.dart @@ -0,0 +1,191 @@ +import 'dart:developer'; + +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/utils/item_sales_invoice.dart'; +import 'package:enaklo_pos/core/utils/permession_handler.dart'; +import 'package:enaklo_pos/data/models/response/item_sales_response_model.dart'; +import 'package:horizontal_data_table/horizontal_data_table.dart'; +import 'package:permission_handler/permission_handler.dart'; + +class ItemSalesReportWidget extends StatelessWidget { + final String title; + final String searchDateFormatted; + final List itemSales; + final List? headerWidgets; + const ItemSalesReportWidget({ + super.key, + required this.itemSales, + required this.title, + required this.searchDateFormatted, + required this.headerWidgets, + }); + + @override + Widget build(BuildContext context) { + return Card( + color: const Color.fromARGB(255, 255, 255, 255), + child: Column( + children: [ + const SpaceHeight(24.0), + Center( + child: Text( + title, + style: + const TextStyle(fontWeight: FontWeight.w800, fontSize: 16.0), + ), + ), + const SizedBox( + height: 8.0, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + searchDateFormatted, + style: const TextStyle(fontSize: 16.0), + ), + GestureDetector( + onTap: () async { + try { + final status = await PermessionHelper().checkPermission(); + if (status) { + final pdfFile = await ItemSalesInvoice.generate( + itemSales, searchDateFormatted); + log("pdfFile: $pdfFile"); + await HelperPdfService.openFile(pdfFile); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Storage permission is required to save PDF'), + backgroundColor: Colors.red, + ), + ); + } + } catch (e) { + log("Error generating PDF: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to generate PDF: $e'), + backgroundColor: Colors.red, + ), + ); + } + }, + child: const Row( + children: [ + Text( + "PDF", + style: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.bold, + color: AppColors.primary, + ), + ), + Icon( + Icons.download_outlined, + color: AppColors.primary, + ) + ], + ), + ), + ], + ), + ), + const SpaceHeight(16.0), + Expanded( + child: Padding( + padding: const EdgeInsets.all(12), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: HorizontalDataTable( + leftHandSideColumnWidth: 80, + rightHandSideColumnWidth: 560, + isFixedHeader: true, + headerWidgets: headerWidgets, + + // isFixedFooter: true, + // footerWidgets: _getTitleWidget(), + leftSideItemBuilder: (context, index) { + return Container( + width: 80, + height: 52, + alignment: Alignment.centerLeft, + child: + Center(child: Text(itemSales[index].id.toString())), + ); + }, + rightSideItemBuilder: (context, index) { + return Row( + children: [ + Container( + width: 60, + height: 52, + alignment: Alignment.centerLeft, + child: Center( + child: Text(itemSales[index].orderId.toString())), + ), + Container( + width: 160, + height: 52, + alignment: Alignment.centerLeft, + child: Center( + child: Text(itemSales[index].productName!)), + ), + Container( + width: 60, + height: 52, + alignment: Alignment.centerLeft, + child: Center( + child: + Text(itemSales[index].quantity.toString())), + ), + Container( + width: 140, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + itemSales[index].price!.currencyFormatRp, + )), + ), + Container( + width: 140, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + (itemSales[index].price! * + itemSales[index].quantity!) + .currencyFormatRp, + )), + ), + ], + ); + }, + itemCount: itemSales.length, + rowSeparatorWidget: const Divider( + color: Colors.black38, + height: 1.0, + thickness: 0.0, + ), + leftHandSideColBackgroundColor: AppColors.white, + rightHandSideColBackgroundColor: AppColors.white, + + itemExtent: 55, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/report/widgets/payment_method_report_widget.dart b/lib/presentation/report/widgets/payment_method_report_widget.dart new file mode 100644 index 0000000..337fcb7 --- /dev/null +++ b/lib/presentation/report/widgets/payment_method_report_widget.dart @@ -0,0 +1,153 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart'; +import 'package:enaklo_pos/presentation/report/widgets/report_title.dart'; + +import '../../../core/components/spaces.dart'; + +class PaymentMethodReportWidget extends StatelessWidget { + final PaymentMethodData paymentMethodData; + final String title; + final String searchDateFormatted; + final List headerWidgets; + + const PaymentMethodReportWidget({ + super.key, + required this.paymentMethodData, + required this.title, + required this.searchDateFormatted, + required this.headerWidgets, + }); + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.white, + body: Column( + children: [ + // HEADER + Container( + padding: const EdgeInsets.all(24.0), + decoration: const BoxDecoration( + color: AppColors.white, + border: Border( + bottom: BorderSide( + color: AppColors.stroke, + width: 1, + ), + ), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(8.0), + Text( + searchDateFormatted, + style: const TextStyle( + fontSize: 16, + color: AppColors.grey, + ), + ), + ], + ), + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 8.0, + ), + decoration: BoxDecoration( + color: AppColors.primary, + borderRadius: BorderRadius.circular(8.0), + ), + child: Text( + 'Total: ${paymentMethodData.total?.currencyFormatRpV2 ?? 'Rp 0'}', + style: const TextStyle( + color: AppColors.white, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ], + ), + ), + + // CONTENT + Expanded( + child: SingleChildScrollView( + child: Column( + children: [ + // TABLE HEADER + Row( + children: headerWidgets, + ), + + // TABLE BODY + ...paymentMethodData.paymentMethods?.map((item) { + return Container( + decoration: const BoxDecoration( + border: Border( + bottom: BorderSide( + color: AppColors.stroke, + width: 1, + ), + ), + ), + child: Row( + children: [ + _getBodyItemWidget( + item.paymentMethod ?? '-', + 180, + ), + _getBodyItemWidget( + item.totalAmount?.currencyFormatRpV2 ?? 'Rp 0', + 180, + ), + _getBodyItemWidget( + item.transactionCount?.toString() ?? '0', + 180, + ), + ], + ), + ); + }).toList() ?? + [], + ], + ), + ), + ), + ], + ), + ); + } + + Widget _getBodyItemWidget(String label, double width) { + return Container( + width: width, + height: 56, + alignment: Alignment.centerLeft, + padding: const EdgeInsets.symmetric(horizontal: 16.0), + child: Text( + label, + style: const TextStyle( + fontSize: 14, + ), + ), + ); + } +} \ No newline at end of file diff --git a/lib/presentation/report/widgets/product_sales_chart_widget.dart b/lib/presentation/report/widgets/product_sales_chart_widget.dart new file mode 100644 index 0000000..9170729 --- /dev/null +++ b/lib/presentation/report/widgets/product_sales_chart_widget.dart @@ -0,0 +1,125 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first + +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:flutter/material.dart'; +import 'package:pie_chart/pie_chart.dart'; + +import 'package:enaklo_pos/data/models/response/product_sales_response_model.dart'; + +class ProductSalesChartWidgets extends StatefulWidget { + final String title; + final String searchDateFormatted; + final List productSales; + const ProductSalesChartWidgets({ + super.key, + required this.title, + required this.searchDateFormatted, + required this.productSales, + }); + + @override + State createState() => + _ProductSalesChartWidgetsState(); +} + +class _ProductSalesChartWidgetsState extends State { + Map dataMap2 = {}; + + @override + void initState() { + loadData(); + super.initState(); + } + + loadData() { + for (var data in widget.productSales) { + dataMap2[data.productName ?? 'Unknown'] = + double.parse(data.totalQuantity!); + } + } + + final colorList = [ + const Color(0xfffdcb6e), + const Color(0xff0984e3), + const Color(0xfffd79a8), + const Color(0xffe17055), + const Color(0xff6c5ce7), + const Color(0xfff0932b), + const Color(0xff6ab04c), + const Color(0xfff8a5c2), + const Color(0xffe84393), + const Color(0xfffd79a8), + const Color(0xffa29bfe), + const Color(0xff00b894), + const Color(0xffe17055), + const Color(0xffd63031), + const Color(0xffa29bfe), + const Color(0xff6c5ce7), + const Color(0xff00cec9), + const Color(0xfffad390), + const Color(0xff686de0), + const Color(0xfffdcb6e), + const Color(0xff0984e3), + const Color(0xfffd79a8), + const Color(0xffe17055), + const Color(0xff6c5ce7), + ]; + + @override + Widget build(BuildContext context) { + return Card( + color: const Color.fromARGB(255, 255, 255, 255), + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 8, vertical: 16), + child: Column( + children: [ + const SpaceHeight(24.0), + Center( + child: Text( + widget.title, + style: const TextStyle( + fontWeight: FontWeight.w800, fontSize: 16.0), + ), + ), + Center( + child: Text( + widget.searchDateFormatted, + style: const TextStyle(fontSize: 16.0), + ), + ), + const SpaceHeight(16.0), + PieChart( + dataMap: dataMap2, + animationDuration: Duration(milliseconds: 800), + chartLegendSpacing: 32, + chartRadius: MediaQuery.of(context).size.width / 3.2, + colorList: colorList, + initialAngleInDegree: 0, + chartType: ChartType.disc, + ringStrokeWidth: 32, + // centerText: "HYBRID", + legendOptions: LegendOptions( + showLegendsInRow: false, + legendPosition: LegendPosition.right, + showLegends: true, + legendShape: BoxShape.circle, + legendTextStyle: TextStyle( + fontWeight: FontWeight.bold, + ), + ), + chartValuesOptions: ChartValuesOptions( + showChartValueBackground: true, + showChartValues: true, + showChartValuesInPercentage: false, + showChartValuesOutside: false, + decimalPlaces: 0, + ), + // gradientList: ---To add gradient colors--- + // emptyColorGradient: ---Empty Color gradient--- + ) + ], + ), + ), + ); + } +} diff --git a/lib/presentation/report/widgets/report_menu.dart b/lib/presentation/report/widgets/report_menu.dart new file mode 100644 index 0000000..9f36a7d --- /dev/null +++ b/lib/presentation/report/widgets/report_menu.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/assets/assets.gen.dart'; + +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + + + +class ReportMenu extends StatelessWidget { + final String label; + final VoidCallback onPressed; + final bool isActive; + + const ReportMenu({ + super.key, + required this.label, + required this.onPressed, + required this.isActive, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onPressed, + child: Container( + margin: const EdgeInsets.all(5.0), + width: 180.0, + height: 160.0, + alignment: Alignment.center, + decoration: BoxDecoration( + color: + isActive ? AppColors.primary.withOpacity(0.13) : AppColors.white, + borderRadius: BorderRadius.circular(18.0), + border: Border.all( + color: isActive ? AppColors.primary : AppColors.stroke, + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + Assets.icons.report.svg( + colorFilter: isActive + ? const ColorFilter.mode( + AppColors.primary, + BlendMode.srcIn, + ) + : null, + ), + const SpaceHeight(28.0), + Text( + label, + style: TextStyle( + color: isActive ? AppColors.primary : AppColors.black, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(24.0), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/report/widgets/report_title.dart b/lib/presentation/report/widgets/report_title.dart new file mode 100644 index 0000000..06e3f21 --- /dev/null +++ b/lib/presentation/report/widgets/report_title.dart @@ -0,0 +1,38 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; + +import '../../../core/constants/colors.dart'; + + + +class ReportTitle extends StatelessWidget { + const ReportTitle({super.key}); + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Report', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(4.0), + Text( + DateTime.now().toFormattedDate(), + style: const TextStyle( + color: AppColors.subtitle, + fontSize: 16, + ), + ), + const SpaceHeight(20.0), + const Divider(), + ], + ); + } +} diff --git a/lib/presentation/report/widgets/summary_report_widget.dart b/lib/presentation/report/widgets/summary_report_widget.dart new file mode 100644 index 0000000..677f51e --- /dev/null +++ b/lib/presentation/report/widgets/summary_report_widget.dart @@ -0,0 +1,193 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:enaklo_pos/core/components/dashed_line.dart'; +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:enaklo_pos/core/utils/permession_handler.dart'; +import 'package:enaklo_pos/data/models/response/summary_response_model.dart'; +import 'package:flutter/material.dart'; +import 'package:permission_handler/permission_handler.dart'; + +import '../../../core/utils/revenue_invoice.dart'; + +class SummaryReportWidget extends StatelessWidget { + final String title; + final String searchDateFormatted; + final SummaryModel summary; + const SummaryReportWidget({ + super.key, + required this.title, + required this.searchDateFormatted, + required this.summary, + }); + + @override + Widget build(BuildContext context) { + return Card( + color: const Color.fromARGB(255, 255, 255, 255), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SpaceHeight(24.0), + Center( + child: Text( + title, + style: const TextStyle( + fontWeight: FontWeight.w800, fontSize: 16.0), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + searchDateFormatted, + style: const TextStyle(fontSize: 16.0), + ), + GestureDetector( + onTap: () async { + log("PDF button clicked for summary report"); + try { + log("Checking permissions..."); + final status = await PermessionHelper().checkPermission(); + log("Permission status: $status"); + + if (status) { + log("Permission granted, starting PDF generation..."); + log("Summary data: ${summary.toMap()}"); + log("Search date: $searchDateFormatted"); + + final pdfFile = await RevenueInvoice.generate( + summary, searchDateFormatted); + log("PDF file generated: ${pdfFile.path}"); + log("PDF file exists: ${await pdfFile.exists()}"); + log("PDF file size: ${await pdfFile.length()} bytes"); + + log("Attempting to open PDF file..."); + await HelperPdfService.openFile(pdfFile); + log("PDF file opened successfully"); + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('PDF saved successfully: ${pdfFile.path}'), + backgroundColor: Colors.green, + ), + ); + } else { + log("Permission denied"); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Storage permission is required to save PDF'), + backgroundColor: Colors.red, + ), + ); + } + } catch (e) { + log("Error generating PDF: $e"); + log("Error stack trace: ${StackTrace.current}"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to generate PDF: $e'), + backgroundColor: Colors.red, + ), + ); + } + }, + child: const Row( + children: [ + Text( + "PDF", + style: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.bold, + color: AppColors.primary, + ), + ), + Icon( + Icons.download_outlined, + color: AppColors.primary, + ) + ], + ), + ), + ], + ), + ), + const SpaceHeight(16.0), + Text( + 'REVENUE : ${int.parse(summary.totalRevenue!).currencyFormatRp}', + style: const TextStyle(fontWeight: FontWeight.bold), + ), + const SpaceHeight(8.0), + const DashedLine(), + const DashedLine(), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Subtotal'), + Text( + int.parse(summary.totalSubtotal!).currencyFormatRp, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Discount'), + Text( + "- ${int.parse(summary.totalDiscount!.replaceAll('.00', '')).currencyFormatRp}", + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Tax'), + Text( + "- ${int.parse(summary.totalTax!).currencyFormatRp}", + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ], + ), + const SpaceHeight(4.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('Service Charge'), + Text( + int.parse(summary.totalServiceCharge!).currencyFormatRp, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ], + ), + const SpaceHeight(8.0), + const DashedLine(), + const DashedLine(), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('TOTAL'), + Text( + summary.total!.currencyFormatRp, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/report/widgets/transaction_report_widget.dart b/lib/presentation/report/widgets/transaction_report_widget.dart new file mode 100644 index 0000000..9665ab1 --- /dev/null +++ b/lib/presentation/report/widgets/transaction_report_widget.dart @@ -0,0 +1,234 @@ +import 'dart:developer'; + +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/utils/helper_pdf_service.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/utils/permession_handler.dart'; +import 'package:enaklo_pos/core/utils/transaction_sales_invoice.dart'; +import 'package:enaklo_pos/data/models/response/order_remote_datasource.dart'; +import 'package:horizontal_data_table/horizontal_data_table.dart'; +import 'package:permission_handler/permission_handler.dart'; + +class TransactionReportWidget extends StatelessWidget { + final String title; + final String searchDateFormatted; + final List transactionReport; + final List? headerWidgets; + const TransactionReportWidget({ + super.key, + required this.transactionReport, + required this.title, + required this.searchDateFormatted, + required this.headerWidgets, + }); + + @override + Widget build(BuildContext context) { + return Card( + color: const Color.fromARGB(255, 255, 255, 255), + child: Column( + children: [ + const SpaceHeight(24.0), + Center( + child: Text( + title, + style: + const TextStyle(fontWeight: FontWeight.w800, fontSize: 16.0), + ), + ), + const SizedBox( + height: 8.0, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + searchDateFormatted, + style: const TextStyle(fontSize: 16.0), + ), + GestureDetector( + onTap: () async { + try { + final status = await PermessionHelper().checkPermission(); + if (status) { + final pdfFile = await TransactionSalesInvoice.generate( + transactionReport, searchDateFormatted); + log("pdfFile: $pdfFile"); + await HelperPdfService.openFile(pdfFile); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Storage permission is required to save PDF'), + backgroundColor: Colors.red, + ), + ); + } + } catch (e) { + log("Error generating PDF: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Failed to generate PDF: $e'), + backgroundColor: Colors.red, + ), + ); + } + }, + child: const Row( + children: [ + Text( + "PDF", + style: TextStyle( + fontSize: 14.0, + fontWeight: FontWeight.bold, + color: AppColors.primary, + ), + ), + Icon( + Icons.download_outlined, + color: AppColors.primary, + ) + ], + ), + ), + ], + ), + ), + const SpaceHeight(16.0), + Expanded( + child: Padding( + padding: const EdgeInsets.all(12), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: HorizontalDataTable( + leftHandSideColumnWidth: 50, + rightHandSideColumnWidth: 1020, + isFixedHeader: true, + headerWidgets: headerWidgets, + // isFixedFooter: true, + // footerWidgets: _getTitleWidget(), + leftSideItemBuilder: (context, index) { + return Container( + width: 40, + height: 52, + alignment: Alignment.centerLeft, + child: Center( + child: Text(transactionReport[index].id.toString())), + ); + }, + rightSideItemBuilder: (context, index) { + return Row( + children: [ + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + transactionReport[index].total!.currencyFormatRp, + )), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + transactionReport[index].subTotal!.currencyFormatRp, + )), + ), + Container( + width: 100, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + transactionReport[index].tax!.currencyFormatRp, + )), + ), + Container( + width: 100, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + int.parse(transactionReport[index] + .discountAmount! + .replaceAll('.00', '')) + .currencyFormatRp, + ), + ), + ), + Container( + width: 100, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + transactionReport[index] + .serviceCharge! + .currencyFormatRp, + ), + ), + ), + Container( + width: 100, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + transactionReport[index].totalItem.toString()), + ), + ), + Container( + width: 150, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(transactionReport[index].namaKasir!), + ), + ), + Container( + width: 230, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(transactionReport[index] + .transactionTime! + .toFormattedDate()), + ), + ), + ], + ); + }, + itemCount: transactionReport.length, + rowSeparatorWidget: const Divider( + color: Colors.black38, + height: 1.0, + thickness: 0.0, + ), + leftHandSideColBackgroundColor: AppColors.white, + rightHandSideColBackgroundColor: AppColors.white, + + itemExtent: 55, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/sales/blocs/bloc/last_order_table_bloc.dart b/lib/presentation/sales/blocs/bloc/last_order_table_bloc.dart new file mode 100644 index 0000000..9cb2460 --- /dev/null +++ b/lib/presentation/sales/blocs/bloc/last_order_table_bloc.dart @@ -0,0 +1,23 @@ + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/home/models/order_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'last_order_table_event.dart'; +part 'last_order_table_state.dart'; +part 'last_order_table_bloc.freezed.dart'; + +class LastOrderTableBloc + extends Bloc { + final ProductLocalDatasource datasource; + LastOrderTableBloc(this.datasource) + : super(const LastOrderTableState.initial()) { + on<_LastOrderTable>((event, emit) async { + emit(_Loading()); + final order = await datasource.getLastOrderTable(event.tableNumber); + + emit(_Success(order)); + }); + } +} diff --git a/lib/presentation/sales/blocs/bloc/last_order_table_bloc.freezed.dart b/lib/presentation/sales/blocs/bloc/last_order_table_bloc.freezed.dart new file mode 100644 index 0000000..3042d60 --- /dev/null +++ b/lib/presentation/sales/blocs/bloc/last_order_table_bloc.freezed.dart @@ -0,0 +1,762 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'last_order_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$LastOrderTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableNumber) lastOrderTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableNumber)? lastOrderTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableNumber)? lastOrderTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_LastOrderTable value) lastOrderTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_LastOrderTable value)? lastOrderTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_LastOrderTable value)? lastOrderTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LastOrderTableEventCopyWith<$Res> { + factory $LastOrderTableEventCopyWith( + LastOrderTableEvent value, $Res Function(LastOrderTableEvent) then) = + _$LastOrderTableEventCopyWithImpl<$Res, LastOrderTableEvent>; +} + +/// @nodoc +class _$LastOrderTableEventCopyWithImpl<$Res, $Val extends LastOrderTableEvent> + implements $LastOrderTableEventCopyWith<$Res> { + _$LastOrderTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LastOrderTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$LastOrderTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of LastOrderTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'LastOrderTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableNumber) lastOrderTable, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableNumber)? lastOrderTable, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableNumber)? lastOrderTable, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_LastOrderTable value) lastOrderTable, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_LastOrderTable value)? lastOrderTable, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_LastOrderTable value)? lastOrderTable, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements LastOrderTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$LastOrderTableImplCopyWith<$Res> { + factory _$$LastOrderTableImplCopyWith(_$LastOrderTableImpl value, + $Res Function(_$LastOrderTableImpl) then) = + __$$LastOrderTableImplCopyWithImpl<$Res>; + @useResult + $Res call({int tableNumber}); +} + +/// @nodoc +class __$$LastOrderTableImplCopyWithImpl<$Res> + extends _$LastOrderTableEventCopyWithImpl<$Res, _$LastOrderTableImpl> + implements _$$LastOrderTableImplCopyWith<$Res> { + __$$LastOrderTableImplCopyWithImpl( + _$LastOrderTableImpl _value, $Res Function(_$LastOrderTableImpl) _then) + : super(_value, _then); + + /// Create a copy of LastOrderTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tableNumber = null, + }) { + return _then(_$LastOrderTableImpl( + null == tableNumber + ? _value.tableNumber + : tableNumber // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$LastOrderTableImpl implements _LastOrderTable { + const _$LastOrderTableImpl(this.tableNumber); + + @override + final int tableNumber; + + @override + String toString() { + return 'LastOrderTableEvent.lastOrderTable(tableNumber: $tableNumber)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LastOrderTableImpl && + (identical(other.tableNumber, tableNumber) || + other.tableNumber == tableNumber)); + } + + @override + int get hashCode => Object.hash(runtimeType, tableNumber); + + /// Create a copy of LastOrderTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LastOrderTableImplCopyWith<_$LastOrderTableImpl> get copyWith => + __$$LastOrderTableImplCopyWithImpl<_$LastOrderTableImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableNumber) lastOrderTable, + }) { + return lastOrderTable(tableNumber); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableNumber)? lastOrderTable, + }) { + return lastOrderTable?.call(tableNumber); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableNumber)? lastOrderTable, + required TResult orElse(), + }) { + if (lastOrderTable != null) { + return lastOrderTable(tableNumber); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_LastOrderTable value) lastOrderTable, + }) { + return lastOrderTable(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_LastOrderTable value)? lastOrderTable, + }) { + return lastOrderTable?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_LastOrderTable value)? lastOrderTable, + required TResult orElse(), + }) { + if (lastOrderTable != null) { + return lastOrderTable(this); + } + return orElse(); + } +} + +abstract class _LastOrderTable implements LastOrderTableEvent { + const factory _LastOrderTable(final int tableNumber) = _$LastOrderTableImpl; + + int get tableNumber; + + /// Create a copy of LastOrderTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LastOrderTableImplCopyWith<_$LastOrderTableImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$LastOrderTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel? order) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel? order)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel? order)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $LastOrderTableStateCopyWith<$Res> { + factory $LastOrderTableStateCopyWith( + LastOrderTableState value, $Res Function(LastOrderTableState) then) = + _$LastOrderTableStateCopyWithImpl<$Res, LastOrderTableState>; +} + +/// @nodoc +class _$LastOrderTableStateCopyWithImpl<$Res, $Val extends LastOrderTableState> + implements $LastOrderTableStateCopyWith<$Res> { + _$LastOrderTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$LastOrderTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'LastOrderTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel? order) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel? order)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel? order)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements LastOrderTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$LastOrderTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'LastOrderTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel? order) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel? order)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel? order)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements LastOrderTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({OrderModel? order}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$LastOrderTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? order = freezed, + }) { + return _then(_$SuccessImpl( + freezed == order + ? _value.order + : order // ignore: cast_nullable_to_non_nullable + as OrderModel?, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.order); + + @override + final OrderModel? order; + + @override + String toString() { + return 'LastOrderTableState.success(order: $order)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.order, order) || other.order == order)); + } + + @override + int get hashCode => Object.hash(runtimeType, order); + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(OrderModel? order) success, + }) { + return success(order); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(OrderModel? order)? success, + }) { + return success?.call(order); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(OrderModel? order)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(order); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements LastOrderTableState { + const factory _Success(final OrderModel? order) = _$SuccessImpl; + + OrderModel? get order; + + /// Create a copy of LastOrderTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/sales/blocs/bloc/last_order_table_event.dart b/lib/presentation/sales/blocs/bloc/last_order_table_event.dart new file mode 100644 index 0000000..a89a759 --- /dev/null +++ b/lib/presentation/sales/blocs/bloc/last_order_table_event.dart @@ -0,0 +1,8 @@ +part of 'last_order_table_bloc.dart'; + +@freezed +class LastOrderTableEvent with _$LastOrderTableEvent { + const factory LastOrderTableEvent.started() = _Started; + const factory LastOrderTableEvent.lastOrderTable(int tableNumber) = + _LastOrderTable; +} diff --git a/lib/presentation/sales/blocs/bloc/last_order_table_state.dart b/lib/presentation/sales/blocs/bloc/last_order_table_state.dart new file mode 100644 index 0000000..e7f0651 --- /dev/null +++ b/lib/presentation/sales/blocs/bloc/last_order_table_state.dart @@ -0,0 +1,8 @@ +part of 'last_order_table_bloc.dart'; + +@freezed +class LastOrderTableState with _$LastOrderTableState { + const factory LastOrderTableState.initial() = _Initial; + const factory LastOrderTableState.loading() = _Loading; + const factory LastOrderTableState.success(OrderModel? order) = _Success; +} diff --git a/lib/presentation/sales/blocs/day_sales/day_sales_bloc.dart b/lib/presentation/sales/blocs/day_sales/day_sales_bloc.dart new file mode 100644 index 0000000..d8f045b --- /dev/null +++ b/lib/presentation/sales/blocs/day_sales/day_sales_bloc.dart @@ -0,0 +1,21 @@ + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/home/models/order_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'day_sales_event.dart'; +part 'day_sales_state.dart'; +part 'day_sales_bloc.freezed.dart'; + +class DaySalesBloc extends Bloc { + final ProductLocalDatasource datasource; + DaySalesBloc(this.datasource) : super(const _Initial()) { + on<_GetDaySales>((event, emit) async { + emit(const _Loading()); + final result = + await datasource.getAllOrder(event.date); + emit(_Loaded(result)); + }); + } +} diff --git a/lib/presentation/sales/blocs/day_sales/day_sales_bloc.freezed.dart b/lib/presentation/sales/blocs/day_sales/day_sales_bloc.freezed.dart new file mode 100644 index 0000000..75464d8 --- /dev/null +++ b/lib/presentation/sales/blocs/day_sales/day_sales_bloc.freezed.dart @@ -0,0 +1,766 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'day_sales_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$DaySalesEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(DateTime date) getDaySales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(DateTime date)? getDaySales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(DateTime date)? getDaySales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDaySales value) getDaySales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDaySales value)? getDaySales, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDaySales value)? getDaySales, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DaySalesEventCopyWith<$Res> { + factory $DaySalesEventCopyWith( + DaySalesEvent value, $Res Function(DaySalesEvent) then) = + _$DaySalesEventCopyWithImpl<$Res, DaySalesEvent>; +} + +/// @nodoc +class _$DaySalesEventCopyWithImpl<$Res, $Val extends DaySalesEvent> + implements $DaySalesEventCopyWith<$Res> { + _$DaySalesEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of DaySalesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$DaySalesEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of DaySalesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'DaySalesEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(DateTime date) getDaySales, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(DateTime date)? getDaySales, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(DateTime date)? getDaySales, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDaySales value) getDaySales, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDaySales value)? getDaySales, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDaySales value)? getDaySales, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements DaySalesEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetDaySalesImplCopyWith<$Res> { + factory _$$GetDaySalesImplCopyWith( + _$GetDaySalesImpl value, $Res Function(_$GetDaySalesImpl) then) = + __$$GetDaySalesImplCopyWithImpl<$Res>; + @useResult + $Res call({DateTime date}); +} + +/// @nodoc +class __$$GetDaySalesImplCopyWithImpl<$Res> + extends _$DaySalesEventCopyWithImpl<$Res, _$GetDaySalesImpl> + implements _$$GetDaySalesImplCopyWith<$Res> { + __$$GetDaySalesImplCopyWithImpl( + _$GetDaySalesImpl _value, $Res Function(_$GetDaySalesImpl) _then) + : super(_value, _then); + + /// Create a copy of DaySalesEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? date = null, + }) { + return _then(_$GetDaySalesImpl( + null == date + ? _value.date + : date // ignore: cast_nullable_to_non_nullable + as DateTime, + )); + } +} + +/// @nodoc + +class _$GetDaySalesImpl implements _GetDaySales { + const _$GetDaySalesImpl(this.date); + + @override + final DateTime date; + + @override + String toString() { + return 'DaySalesEvent.getDaySales(date: $date)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GetDaySalesImpl && + (identical(other.date, date) || other.date == date)); + } + + @override + int get hashCode => Object.hash(runtimeType, date); + + /// Create a copy of DaySalesEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GetDaySalesImplCopyWith<_$GetDaySalesImpl> get copyWith => + __$$GetDaySalesImplCopyWithImpl<_$GetDaySalesImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(DateTime date) getDaySales, + }) { + return getDaySales(date); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(DateTime date)? getDaySales, + }) { + return getDaySales?.call(date); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(DateTime date)? getDaySales, + required TResult orElse(), + }) { + if (getDaySales != null) { + return getDaySales(date); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDaySales value) getDaySales, + }) { + return getDaySales(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDaySales value)? getDaySales, + }) { + return getDaySales?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDaySales value)? getDaySales, + required TResult orElse(), + }) { + if (getDaySales != null) { + return getDaySales(this); + } + return orElse(); + } +} + +abstract class _GetDaySales implements DaySalesEvent { + const factory _GetDaySales(final DateTime date) = _$GetDaySalesImpl; + + DateTime get date; + + /// Create a copy of DaySalesEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GetDaySalesImplCopyWith<_$GetDaySalesImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$DaySalesState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List orders) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List orders)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List orders)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DaySalesStateCopyWith<$Res> { + factory $DaySalesStateCopyWith( + DaySalesState value, $Res Function(DaySalesState) then) = + _$DaySalesStateCopyWithImpl<$Res, DaySalesState>; +} + +/// @nodoc +class _$DaySalesStateCopyWithImpl<$Res, $Val extends DaySalesState> + implements $DaySalesStateCopyWith<$Res> { + _$DaySalesStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$DaySalesStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'DaySalesState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List orders) loaded, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List orders)? loaded, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List orders)? loaded, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements DaySalesState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$DaySalesStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'DaySalesState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List orders) loaded, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List orders)? loaded, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List orders)? loaded, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements DaySalesState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List orders}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$DaySalesStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? orders = null, + }) { + return _then(_$LoadedImpl( + null == orders + ? _value._orders + : orders // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List orders) : _orders = orders; + + final List _orders; + @override + List get orders { + if (_orders is EqualUnmodifiableListView) return _orders; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_orders); + } + + @override + String toString() { + return 'DaySalesState.loaded(orders: $orders)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality().equals(other._orders, _orders)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_orders)); + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List orders) loaded, + }) { + return loaded(orders); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List orders)? loaded, + }) { + return loaded?.call(orders); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List orders)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(orders); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements DaySalesState { + const factory _Loaded(final List orders) = _$LoadedImpl; + + List get orders; + + /// Create a copy of DaySalesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/sales/blocs/day_sales/day_sales_event.dart b/lib/presentation/sales/blocs/day_sales/day_sales_event.dart new file mode 100644 index 0000000..05b1184 --- /dev/null +++ b/lib/presentation/sales/blocs/day_sales/day_sales_event.dart @@ -0,0 +1,9 @@ +part of 'day_sales_bloc.dart'; + +@freezed +class DaySalesEvent with _$DaySalesEvent { + const factory DaySalesEvent.started() = _Started; + const factory DaySalesEvent.getDaySales( + DateTime date, + ) = _GetDaySales; +} diff --git a/lib/presentation/sales/blocs/day_sales/day_sales_state.dart b/lib/presentation/sales/blocs/day_sales/day_sales_state.dart new file mode 100644 index 0000000..698ee6a --- /dev/null +++ b/lib/presentation/sales/blocs/day_sales/day_sales_state.dart @@ -0,0 +1,8 @@ +part of 'day_sales_bloc.dart'; + +@freezed +class DaySalesState with _$DaySalesState { + const factory DaySalesState.initial() = _Initial; + const factory DaySalesState.loading() = _Loading; + const factory DaySalesState.loaded(List orders) = _Loaded; +} diff --git a/lib/presentation/sales/pages/sales_page.dart b/lib/presentation/sales/pages/sales_page.dart new file mode 100644 index 0000000..648ef0a --- /dev/null +++ b/lib/presentation/sales/pages/sales_page.dart @@ -0,0 +1,127 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/presentation/sales/blocs/day_sales/day_sales_bloc.dart'; + +import '../widgets/sales_widget.dart'; + +class SalesPage extends StatefulWidget { + const SalesPage({super.key}); + + @override + State createState() => _SalesPageState(); +} + +class _SalesPageState extends State { + @override + void initState() { + context.read().add(DaySalesEvent.getDaySales(DateTime.now())); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(32), + child: Column( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Enaklo POS ', + style: TextStyle( + color: AppColors.primary, + fontSize: 22, + fontWeight: FontWeight.w600, + ), + ), + Text( + "${DateTime.now().toFormattedDate()}", + style: const TextStyle( + color: AppColors.subtitle, + fontSize: 16, + ), + ), + ], + ), + const SizedBox( + height: 12.0, + ), + Expanded( + child: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + loaded: (orders) { + log("message: ${orders.length}"); + if (orders.isEmpty) { + return Center( + child: Text( + "Belum ada transaksi saat ini. ", + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold, + ), + ), + ); + } else { + return SalesWidget( + headerWidgets: _getTitleHeaderWidget(), + orders: orders, + ); + } + }, + ); + }, + ), + ), + ], + ), + ); + } + + List _getTitleHeaderWidget() { + return [ + _getTitleItemWidget('ID', 40), + _getTitleItemWidget('Customer', 120), + _getTitleItemWidget('Status', 120), + _getTitleItemWidget('Sync', 60), + _getTitleItemWidget('Payment Status', 120), + _getTitleItemWidget('Payment Method', 120), + _getTitleItemWidget('Payment Amount', 120), + _getTitleItemWidget('Sub Total', 120), + _getTitleItemWidget('Tax', 120), + _getTitleItemWidget('Discount', 60), + _getTitleItemWidget('Service Charge', 120), + _getTitleItemWidget('Total', 120), + _getTitleItemWidget('Payment', 60), + _getTitleItemWidget('Item', 60), + _getTitleItemWidget('Cashier', 150), + _getTitleItemWidget('Time', 230), + _getTitleItemWidget('Action', 230), + ]; + } + + Widget _getTitleItemWidget(String label, double width) { + return Container( + width: width, + height: 56, + color: AppColors.primary, + alignment: Alignment.centerLeft, + child: Center( + child: Text( + label, + style: const TextStyle( + color: Colors.white, + ), + ), + ), + ); + } +} diff --git a/lib/presentation/sales/widgets/sales_widget.dart b/lib/presentation/sales/widgets/sales_widget.dart new file mode 100644 index 0000000..fbe9bd3 --- /dev/null +++ b/lib/presentation/sales/widgets/sales_widget.dart @@ -0,0 +1,210 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/presentation/home/models/order_model.dart'; +import 'package:horizontal_data_table/horizontal_data_table.dart'; + +class SalesWidget extends StatelessWidget { + final List orders; + final List? headerWidgets; + const SalesWidget({ + super.key, + required this.orders, + required this.headerWidgets, + }); + + @override + Widget build(BuildContext context) { + return Column( + children: [ + const SpaceHeight(16.0), + Expanded( + child: Padding( + padding: const EdgeInsets.all(12), + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: HorizontalDataTable( + leftHandSideColumnWidth: 40, + rightHandSideColumnWidth: 1700, + isFixedHeader: true, + headerWidgets: headerWidgets, + leftSideItemBuilder: (context, index) { + return Container( + width: 40, + height: 52, + alignment: Alignment.centerLeft, + child: Center(child: Text(orders[index].id.toString())), + ); + }, + rightSideItemBuilder: (context, index) { + return Row( + children: [ + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].customerName == '' + ? '-' + : orders[index].customerName, + )), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].status, + )), + ), + Container( + width: 60, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].isSync == 0 + ? 'Belum' //belum sync + : 'Sudah', //sudah sync + )), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center(child: Text(orders[index].paymentStatus)), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center(child: Text(orders[index].paymentMethod)), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].paymentAmount.currencyFormatRp, + )), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].subTotal.currencyFormatRp, + )), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].tax.currencyFormatRp, + ), + ), + ), + Container( + width: 60, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].discountAmount.currencyFormatRp, + ), + ), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + orders[index].serviceCharge.currencyFormatRp), + ), + ), + Container( + width: 120, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(orders[index].total.currencyFormatRp), + ), + ), + Container( + width: 60, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(orders[index].paymentMethod), + ), + ), + Container( + width: 60, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(orders[index].totalItem.toString()), + ), + ), + Container( + width: 150, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text(orders[index].namaKasir), + ), + ), + Container( + width: 230, + height: 52, + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0), + alignment: Alignment.centerLeft, + child: Center( + child: Text( + DateTime.parse(orders[index].transactionTime) + .toFormattedDate2(), + ), + ), + ), + ], + ); + }, + itemCount: orders.length, + rowSeparatorWidget: const Divider( + color: Colors.black38, + height: 1.0, + thickness: 0.0, + ), + leftHandSideColBackgroundColor: const Color(0xFFFFFFFF), + rightHandSideColBackgroundColor: const Color(0xFFFFFFFF), + itemExtent: 55, + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/presentation/setting/bloc/add_discount/add_discount_bloc.dart b/lib/presentation/setting/bloc/add_discount/add_discount_bloc.dart new file mode 100644 index 0000000..2e71caa --- /dev/null +++ b/lib/presentation/setting/bloc/add_discount/add_discount_bloc.dart @@ -0,0 +1,29 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/discount_remote_datasource.dart'; + +part 'add_discount_bloc.freezed.dart'; +part 'add_discount_event.dart'; +part 'add_discount_state.dart'; + +class AddDiscountBloc extends Bloc { + final DiscountRemoteDatasource discountRemoteDatasource; + AddDiscountBloc( + this.discountRemoteDatasource, + ) : super(const _Initial()) { + on<_AddDiscount>((event, emit) async { + emit(const _Loading()); + final result = await discountRemoteDatasource.addDiscount( + event.name, + event.description, + event.value, + ); + + result.fold( + (l) => emit(_Error(l)), + (r) => emit(const _Success()), + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/add_discount/add_discount_bloc.freezed.dart b/lib/presentation/setting/bloc/add_discount/add_discount_bloc.freezed.dart new file mode 100644 index 0000000..4057f47 --- /dev/null +++ b/lib/presentation/setting/bloc/add_discount/add_discount_bloc.freezed.dart @@ -0,0 +1,927 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'add_discount_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$AddDiscountEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String name, String description, int value) + addDiscount, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String name, String description, int value)? addDiscount, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String name, String description, int value)? addDiscount, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddDiscount value) addDiscount, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddDiscount value)? addDiscount, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddDiscount value)? addDiscount, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddDiscountEventCopyWith<$Res> { + factory $AddDiscountEventCopyWith( + AddDiscountEvent value, $Res Function(AddDiscountEvent) then) = + _$AddDiscountEventCopyWithImpl<$Res, AddDiscountEvent>; +} + +/// @nodoc +class _$AddDiscountEventCopyWithImpl<$Res, $Val extends AddDiscountEvent> + implements $AddDiscountEventCopyWith<$Res> { + _$AddDiscountEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddDiscountEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$AddDiscountEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'AddDiscountEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String name, String description, int value) + addDiscount, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String name, String description, int value)? addDiscount, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String name, String description, int value)? addDiscount, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddDiscount value) addDiscount, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddDiscount value)? addDiscount, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddDiscount value)? addDiscount, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements AddDiscountEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$AddDiscountImplCopyWith<$Res> { + factory _$$AddDiscountImplCopyWith( + _$AddDiscountImpl value, $Res Function(_$AddDiscountImpl) then) = + __$$AddDiscountImplCopyWithImpl<$Res>; + @useResult + $Res call({String name, String description, int value}); +} + +/// @nodoc +class __$$AddDiscountImplCopyWithImpl<$Res> + extends _$AddDiscountEventCopyWithImpl<$Res, _$AddDiscountImpl> + implements _$$AddDiscountImplCopyWith<$Res> { + __$$AddDiscountImplCopyWithImpl( + _$AddDiscountImpl _value, $Res Function(_$AddDiscountImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? description = null, + Object? value = null, + }) { + return _then(_$AddDiscountImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _value.description + : description // ignore: cast_nullable_to_non_nullable + as String, + value: null == value + ? _value.value + : value // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$AddDiscountImpl implements _AddDiscount { + const _$AddDiscountImpl( + {required this.name, required this.description, required this.value}); + + @override + final String name; + @override + final String description; + @override + final int value; + + @override + String toString() { + return 'AddDiscountEvent.addDiscount(name: $name, description: $description, value: $value)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddDiscountImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.description, description) || + other.description == description) && + (identical(other.value, value) || other.value == value)); + } + + @override + int get hashCode => Object.hash(runtimeType, name, description, value); + + /// Create a copy of AddDiscountEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddDiscountImplCopyWith<_$AddDiscountImpl> get copyWith => + __$$AddDiscountImplCopyWithImpl<_$AddDiscountImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String name, String description, int value) + addDiscount, + }) { + return addDiscount(name, description, value); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String name, String description, int value)? addDiscount, + }) { + return addDiscount?.call(name, description, value); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String name, String description, int value)? addDiscount, + required TResult orElse(), + }) { + if (addDiscount != null) { + return addDiscount(name, description, value); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddDiscount value) addDiscount, + }) { + return addDiscount(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddDiscount value)? addDiscount, + }) { + return addDiscount?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddDiscount value)? addDiscount, + required TResult orElse(), + }) { + if (addDiscount != null) { + return addDiscount(this); + } + return orElse(); + } +} + +abstract class _AddDiscount implements AddDiscountEvent { + const factory _AddDiscount( + {required final String name, + required final String description, + required final int value}) = _$AddDiscountImpl; + + String get name; + String get description; + int get value; + + /// Create a copy of AddDiscountEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddDiscountImplCopyWith<_$AddDiscountImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$AddDiscountState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function() success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function()? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function()? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddDiscountStateCopyWith<$Res> { + factory $AddDiscountStateCopyWith( + AddDiscountState value, $Res Function(AddDiscountState) then) = + _$AddDiscountStateCopyWithImpl<$Res, AddDiscountState>; +} + +/// @nodoc +class _$AddDiscountStateCopyWithImpl<$Res, $Val extends AddDiscountState> + implements $AddDiscountStateCopyWith<$Res> { + _$AddDiscountStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$AddDiscountStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'AddDiscountState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function() success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function()? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function()? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements AddDiscountState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$AddDiscountStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'AddDiscountState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function() success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function()? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function()? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements AddDiscountState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$AddDiscountStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'AddDiscountState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function() success, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function()? success, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function()? success, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Success value) success, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Success value)? success, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements AddDiscountState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$AddDiscountStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of AddDiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(); + + @override + String toString() { + return 'AddDiscountState.success()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SuccessImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) error, + required TResult Function() success, + }) { + return success(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? error, + TResult? Function()? success, + }) { + return success?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? error, + TResult Function()? success, + required TResult orElse(), + }) { + if (success != null) { + return success(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Error value) error, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Error value)? error, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Error value)? error, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements AddDiscountState { + const factory _Success() = _$SuccessImpl; +} diff --git a/lib/presentation/setting/bloc/add_discount/add_discount_event.dart b/lib/presentation/setting/bloc/add_discount/add_discount_event.dart new file mode 100644 index 0000000..35ef725 --- /dev/null +++ b/lib/presentation/setting/bloc/add_discount/add_discount_event.dart @@ -0,0 +1,11 @@ +part of 'add_discount_bloc.dart'; + +@freezed +class AddDiscountEvent with _$AddDiscountEvent { + const factory AddDiscountEvent.started() = _Started; + const factory AddDiscountEvent.addDiscount({ + required String name, + required String description, + required int value, + }) = _AddDiscount; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/add_discount/add_discount_state.dart b/lib/presentation/setting/bloc/add_discount/add_discount_state.dart new file mode 100644 index 0000000..c0f4d85 --- /dev/null +++ b/lib/presentation/setting/bloc/add_discount/add_discount_state.dart @@ -0,0 +1,9 @@ +part of 'add_discount_bloc.dart'; + +@freezed +class AddDiscountState with _$AddDiscountState { + const factory AddDiscountState.initial() = _Initial; + const factory AddDiscountState.loading() = _Loading; + const factory AddDiscountState.error(String message) = _Error; + const factory AddDiscountState.success() = _Success; +} diff --git a/lib/presentation/setting/bloc/add_product/add_product_bloc.dart b/lib/presentation/setting/bloc/add_product/add_product_bloc.dart new file mode 100644 index 0000000..5efe3f9 --- /dev/null +++ b/lib/presentation/setting/bloc/add_product/add_product_bloc.dart @@ -0,0 +1,40 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/request/product_request_model.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:image_picker/image_picker.dart'; + +part 'add_product_event.dart'; +part 'add_product_state.dart'; +part 'add_product_bloc.freezed.dart'; + +class AddProductBloc extends Bloc { + final ProductRemoteDatasource datasource; + AddProductBloc( + this.datasource, + ) : super(const _Initial()) { + on<_AddProduct>((event, emit) async { + emit(const _Loading()); + final requestData = ProductRequestModel( + name: event.product.name!, + price: int.parse(event.product.price!), + stock: event.product.stock!, + categoryId: event.product.categoryId!, + isBestSeller: event.product.isFavorite!, + image: event.image, + ); + log("requestData: ${requestData.toString()}"); + final response = await datasource.addProduct(requestData); + // products.add(newProduct); + response.fold( + (l) => emit(_Error(l)), + (r) { + emit(_Success('Add Product Success')); + }, + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/add_product/add_product_bloc.freezed.dart b/lib/presentation/setting/bloc/add_product/add_product_bloc.freezed.dart new file mode 100644 index 0000000..a910a8e --- /dev/null +++ b/lib/presentation/setting/bloc/add_product/add_product_bloc.freezed.dart @@ -0,0 +1,946 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'add_product_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$AddProductEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product, XFile image) addProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product, XFile image)? addProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product, XFile image)? addProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddProduct value) addProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddProduct value)? addProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddProduct value)? addProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddProductEventCopyWith<$Res> { + factory $AddProductEventCopyWith( + AddProductEvent value, $Res Function(AddProductEvent) then) = + _$AddProductEventCopyWithImpl<$Res, AddProductEvent>; +} + +/// @nodoc +class _$AddProductEventCopyWithImpl<$Res, $Val extends AddProductEvent> + implements $AddProductEventCopyWith<$Res> { + _$AddProductEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$AddProductEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'AddProductEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product, XFile image) addProduct, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product, XFile image)? addProduct, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product, XFile image)? addProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddProduct value) addProduct, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddProduct value)? addProduct, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddProduct value)? addProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements AddProductEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$AddProductImplCopyWith<$Res> { + factory _$$AddProductImplCopyWith( + _$AddProductImpl value, $Res Function(_$AddProductImpl) then) = + __$$AddProductImplCopyWithImpl<$Res>; + @useResult + $Res call({Product product, XFile image}); +} + +/// @nodoc +class __$$AddProductImplCopyWithImpl<$Res> + extends _$AddProductEventCopyWithImpl<$Res, _$AddProductImpl> + implements _$$AddProductImplCopyWith<$Res> { + __$$AddProductImplCopyWithImpl( + _$AddProductImpl _value, $Res Function(_$AddProductImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + Object? image = null, + }) { + return _then(_$AddProductImpl( + null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + null == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as XFile, + )); + } +} + +/// @nodoc + +class _$AddProductImpl implements _AddProduct { + const _$AddProductImpl(this.product, this.image); + + @override + final Product product; + @override + final XFile image; + + @override + String toString() { + return 'AddProductEvent.addProduct(product: $product, image: $image)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$AddProductImpl && + (identical(other.product, product) || other.product == product) && + (identical(other.image, image) || other.image == image)); + } + + @override + int get hashCode => Object.hash(runtimeType, product, image); + + /// Create a copy of AddProductEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$AddProductImplCopyWith<_$AddProductImpl> get copyWith => + __$$AddProductImplCopyWithImpl<_$AddProductImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(Product product, XFile image) addProduct, + }) { + return addProduct(product, image); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(Product product, XFile image)? addProduct, + }) { + return addProduct?.call(product, image); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(Product product, XFile image)? addProduct, + required TResult orElse(), + }) { + if (addProduct != null) { + return addProduct(product, image); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_AddProduct value) addProduct, + }) { + return addProduct(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_AddProduct value)? addProduct, + }) { + return addProduct?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_AddProduct value)? addProduct, + required TResult orElse(), + }) { + if (addProduct != null) { + return addProduct(this); + } + return orElse(); + } +} + +abstract class _AddProduct implements AddProductEvent { + const factory _AddProduct(final Product product, final XFile image) = + _$AddProductImpl; + + Product get product; + XFile get image; + + /// Create a copy of AddProductEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$AddProductImplCopyWith<_$AddProductImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$AddProductState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $AddProductStateCopyWith<$Res> { + factory $AddProductStateCopyWith( + AddProductState value, $Res Function(AddProductState) then) = + _$AddProductStateCopyWithImpl<$Res, AddProductState>; +} + +/// @nodoc +class _$AddProductStateCopyWithImpl<$Res, $Val extends AddProductState> + implements $AddProductStateCopyWith<$Res> { + _$AddProductStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$AddProductStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'AddProductState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements AddProductState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$AddProductStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'AddProductState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements AddProductState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$AddProductStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'AddProductState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements AddProductState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$AddProductStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'AddProductState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements AddProductState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of AddProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/add_product/add_product_event.dart b/lib/presentation/setting/bloc/add_product/add_product_event.dart new file mode 100644 index 0000000..39e69b7 --- /dev/null +++ b/lib/presentation/setting/bloc/add_product/add_product_event.dart @@ -0,0 +1,8 @@ +part of 'add_product_bloc.dart'; + +@freezed +class AddProductEvent with _$AddProductEvent { + const factory AddProductEvent.started() = _Started; + const factory AddProductEvent.addProduct(Product product, XFile image) = + _AddProduct; +} diff --git a/lib/presentation/setting/bloc/add_product/add_product_state.dart b/lib/presentation/setting/bloc/add_product/add_product_state.dart new file mode 100644 index 0000000..e10c6b4 --- /dev/null +++ b/lib/presentation/setting/bloc/add_product/add_product_state.dart @@ -0,0 +1,9 @@ +part of 'add_product_bloc.dart'; + +@freezed +class AddProductState with _$AddProductState { + const factory AddProductState.initial() = _Initial; + const factory AddProductState.loading() = _Loading; + const factory AddProductState.success(String message) = _Success; + const factory AddProductState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/create_printer/create_printer_bloc.dart b/lib/presentation/setting/bloc/create_printer/create_printer_bloc.dart new file mode 100644 index 0000000..9a17c77 --- /dev/null +++ b/lib/presentation/setting/bloc/create_printer/create_printer_bloc.dart @@ -0,0 +1,22 @@ +import 'dart:async'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'create_printer_event.dart'; +part 'create_printer_state.dart'; +part 'create_printer_bloc.freezed.dart'; + +class CreatePrinterBloc extends Bloc { + CreatePrinterBloc() : super(_Initial()) { + on<_CreatePrinter>((event, emit) async { + emit(_Loading()); + await ProductLocalDatasource.instance.createPrinter( + event.print, + ); + emit(_Success('Create Table Success')); + }); + } +} diff --git a/lib/presentation/setting/bloc/create_printer/create_printer_bloc.freezed.dart b/lib/presentation/setting/bloc/create_printer/create_printer_bloc.freezed.dart new file mode 100644 index 0000000..5d37737 --- /dev/null +++ b/lib/presentation/setting/bloc/create_printer/create_printer_bloc.freezed.dart @@ -0,0 +1,760 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'create_printer_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$CreatePrinterEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) createPrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? createPrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? createPrinter, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreatePrinter value) createPrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreatePrinter value)? createPrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreatePrinter value)? createPrinter, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CreatePrinterEventCopyWith<$Res> { + factory $CreatePrinterEventCopyWith( + CreatePrinterEvent value, $Res Function(CreatePrinterEvent) then) = + _$CreatePrinterEventCopyWithImpl<$Res, CreatePrinterEvent>; +} + +/// @nodoc +class _$CreatePrinterEventCopyWithImpl<$Res, $Val extends CreatePrinterEvent> + implements $CreatePrinterEventCopyWith<$Res> { + _$CreatePrinterEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CreatePrinterEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$CreatePrinterEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of CreatePrinterEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'CreatePrinterEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) createPrinter, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? createPrinter, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? createPrinter, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreatePrinter value) createPrinter, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreatePrinter value)? createPrinter, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreatePrinter value)? createPrinter, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements CreatePrinterEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$CreatePrinterImplCopyWith<$Res> { + factory _$$CreatePrinterImplCopyWith( + _$CreatePrinterImpl value, $Res Function(_$CreatePrinterImpl) then) = + __$$CreatePrinterImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel print}); +} + +/// @nodoc +class __$$CreatePrinterImplCopyWithImpl<$Res> + extends _$CreatePrinterEventCopyWithImpl<$Res, _$CreatePrinterImpl> + implements _$$CreatePrinterImplCopyWith<$Res> { + __$$CreatePrinterImplCopyWithImpl( + _$CreatePrinterImpl _value, $Res Function(_$CreatePrinterImpl) _then) + : super(_value, _then); + + /// Create a copy of CreatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? print = null, + }) { + return _then(_$CreatePrinterImpl( + null == print + ? _value.print + : print // ignore: cast_nullable_to_non_nullable + as PrintModel, + )); + } +} + +/// @nodoc + +class _$CreatePrinterImpl implements _CreatePrinter { + const _$CreatePrinterImpl(this.print); + + @override + final PrintModel print; + + @override + String toString() { + return 'CreatePrinterEvent.createPrinter(print: $print)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CreatePrinterImpl && + (identical(other.print, print) || other.print == print)); + } + + @override + int get hashCode => Object.hash(runtimeType, print); + + /// Create a copy of CreatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$CreatePrinterImplCopyWith<_$CreatePrinterImpl> get copyWith => + __$$CreatePrinterImplCopyWithImpl<_$CreatePrinterImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) createPrinter, + }) { + return createPrinter(print); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? createPrinter, + }) { + return createPrinter?.call(print); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? createPrinter, + required TResult orElse(), + }) { + if (createPrinter != null) { + return createPrinter(print); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreatePrinter value) createPrinter, + }) { + return createPrinter(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreatePrinter value)? createPrinter, + }) { + return createPrinter?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreatePrinter value)? createPrinter, + required TResult orElse(), + }) { + if (createPrinter != null) { + return createPrinter(this); + } + return orElse(); + } +} + +abstract class _CreatePrinter implements CreatePrinterEvent { + const factory _CreatePrinter(final PrintModel print) = _$CreatePrinterImpl; + + PrintModel get print; + + /// Create a copy of CreatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$CreatePrinterImplCopyWith<_$CreatePrinterImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$CreatePrinterState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CreatePrinterStateCopyWith<$Res> { + factory $CreatePrinterStateCopyWith( + CreatePrinterState value, $Res Function(CreatePrinterState) then) = + _$CreatePrinterStateCopyWithImpl<$Res, CreatePrinterState>; +} + +/// @nodoc +class _$CreatePrinterStateCopyWithImpl<$Res, $Val extends CreatePrinterState> + implements $CreatePrinterStateCopyWith<$Res> { + _$CreatePrinterStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$CreatePrinterStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'CreatePrinterState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements CreatePrinterState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$CreatePrinterStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'CreatePrinterState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements CreatePrinterState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$CreatePrinterStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'CreatePrinterState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements CreatePrinterState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of CreatePrinterState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/create_printer/create_printer_event.dart b/lib/presentation/setting/bloc/create_printer/create_printer_event.dart new file mode 100644 index 0000000..ae3f040 --- /dev/null +++ b/lib/presentation/setting/bloc/create_printer/create_printer_event.dart @@ -0,0 +1,9 @@ +part of 'create_printer_bloc.dart'; + +@freezed +class CreatePrinterEvent with _$CreatePrinterEvent { + const factory CreatePrinterEvent.started() = _Started; + + const factory CreatePrinterEvent.createPrinter(PrintModel print) = + _CreatePrinter; +} diff --git a/lib/presentation/setting/bloc/create_printer/create_printer_state.dart b/lib/presentation/setting/bloc/create_printer/create_printer_state.dart new file mode 100644 index 0000000..2a54d5c --- /dev/null +++ b/lib/presentation/setting/bloc/create_printer/create_printer_state.dart @@ -0,0 +1,8 @@ +part of 'create_printer_bloc.dart'; + +@freezed +class CreatePrinterState with _$CreatePrinterState { + const factory CreatePrinterState.initial() = _Initial; + const factory CreatePrinterState.loading() = _Loading; + const factory CreatePrinterState.success(String message) = _Success; +} diff --git a/lib/presentation/setting/bloc/discount/discount_bloc.dart b/lib/presentation/setting/bloc/discount/discount_bloc.dart new file mode 100644 index 0000000..1320843 --- /dev/null +++ b/lib/presentation/setting/bloc/discount/discount_bloc.dart @@ -0,0 +1,25 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../../../data/datasources/discount_remote_datasource.dart'; +import '../../../../data/models/response/discount_response_model.dart'; + +part 'discount_bloc.freezed.dart'; +part 'discount_event.dart'; +part 'discount_state.dart'; + +class DiscountBloc extends Bloc { + final DiscountRemoteDatasource discountRemoteDatasource; + DiscountBloc( + this.discountRemoteDatasource, + ) : super(const _Initial()) { + on<_GetDiscounts>((event, emit) async { + emit(const _Loading()); + final result = await discountRemoteDatasource.getDiscounts(); + result.fold( + (l) => emit(_Error(l)), + (r) => emit(_Loaded(r.data!)), + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/discount/discount_bloc.freezed.dart b/lib/presentation/setting/bloc/discount/discount_bloc.freezed.dart new file mode 100644 index 0000000..c82a1c3 --- /dev/null +++ b/lib/presentation/setting/bloc/discount/discount_bloc.freezed.dart @@ -0,0 +1,908 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'discount_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$DiscountEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getDiscounts, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getDiscounts, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getDiscounts, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDiscounts value) getDiscounts, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDiscounts value)? getDiscounts, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDiscounts value)? getDiscounts, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DiscountEventCopyWith<$Res> { + factory $DiscountEventCopyWith( + DiscountEvent value, $Res Function(DiscountEvent) then) = + _$DiscountEventCopyWithImpl<$Res, DiscountEvent>; +} + +/// @nodoc +class _$DiscountEventCopyWithImpl<$Res, $Val extends DiscountEvent> + implements $DiscountEventCopyWith<$Res> { + _$DiscountEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of DiscountEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$DiscountEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'DiscountEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getDiscounts, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getDiscounts, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getDiscounts, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDiscounts value) getDiscounts, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDiscounts value)? getDiscounts, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDiscounts value)? getDiscounts, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements DiscountEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetDiscountsImplCopyWith<$Res> { + factory _$$GetDiscountsImplCopyWith( + _$GetDiscountsImpl value, $Res Function(_$GetDiscountsImpl) then) = + __$$GetDiscountsImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetDiscountsImplCopyWithImpl<$Res> + extends _$DiscountEventCopyWithImpl<$Res, _$GetDiscountsImpl> + implements _$$GetDiscountsImplCopyWith<$Res> { + __$$GetDiscountsImplCopyWithImpl( + _$GetDiscountsImpl _value, $Res Function(_$GetDiscountsImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetDiscountsImpl implements _GetDiscounts { + const _$GetDiscountsImpl(); + + @override + String toString() { + return 'DiscountEvent.getDiscounts()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetDiscountsImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getDiscounts, + }) { + return getDiscounts(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getDiscounts, + }) { + return getDiscounts?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getDiscounts, + required TResult orElse(), + }) { + if (getDiscounts != null) { + return getDiscounts(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetDiscounts value) getDiscounts, + }) { + return getDiscounts(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetDiscounts value)? getDiscounts, + }) { + return getDiscounts?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetDiscounts value)? getDiscounts, + required TResult orElse(), + }) { + if (getDiscounts != null) { + return getDiscounts(this); + } + return orElse(); + } +} + +abstract class _GetDiscounts implements DiscountEvent { + const factory _GetDiscounts() = _$GetDiscountsImpl; +} + +/// @nodoc +mixin _$DiscountState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List discounts) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List discounts)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List discounts)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DiscountStateCopyWith<$Res> { + factory $DiscountStateCopyWith( + DiscountState value, $Res Function(DiscountState) then) = + _$DiscountStateCopyWithImpl<$Res, DiscountState>; +} + +/// @nodoc +class _$DiscountStateCopyWithImpl<$Res, $Val extends DiscountState> + implements $DiscountStateCopyWith<$Res> { + _$DiscountStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$DiscountStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'DiscountState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List discounts) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List discounts)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List discounts)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements DiscountState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$DiscountStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'DiscountState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List discounts) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List discounts)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List discounts)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements DiscountState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({List discounts}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$DiscountStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? discounts = null, + }) { + return _then(_$LoadedImpl( + null == discounts + ? _value._discounts + : discounts // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(final List discounts) : _discounts = discounts; + + final List _discounts; + @override + List get discounts { + if (_discounts is EqualUnmodifiableListView) return _discounts; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_discounts); + } + + @override + String toString() { + return 'DiscountState.loaded(discounts: $discounts)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + const DeepCollectionEquality() + .equals(other._discounts, _discounts)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_discounts)); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List discounts) loaded, + required TResult Function(String message) error, + }) { + return loaded(discounts); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List discounts)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(discounts); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List discounts)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(discounts); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements DiscountState { + const factory _Loaded(final List discounts) = _$LoadedImpl; + + List get discounts; + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$DiscountStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'DiscountState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List discounts) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List discounts)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List discounts)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements DiscountState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of DiscountState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/discount/discount_event.dart b/lib/presentation/setting/bloc/discount/discount_event.dart new file mode 100644 index 0000000..8439b4a --- /dev/null +++ b/lib/presentation/setting/bloc/discount/discount_event.dart @@ -0,0 +1,7 @@ +part of 'discount_bloc.dart'; + +@freezed +class DiscountEvent with _$DiscountEvent { + const factory DiscountEvent.started() = _Started; + const factory DiscountEvent.getDiscounts() = _GetDiscounts; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/discount/discount_state.dart b/lib/presentation/setting/bloc/discount/discount_state.dart new file mode 100644 index 0000000..1197172 --- /dev/null +++ b/lib/presentation/setting/bloc/discount/discount_state.dart @@ -0,0 +1,9 @@ +part of 'discount_bloc.dart'; + +@freezed +class DiscountState with _$DiscountState { + const factory DiscountState.initial() = _Initial; + const factory DiscountState.loading() = _Loading; + const factory DiscountState.loaded(List discounts) = _Loaded; + const factory DiscountState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/get_categories/get_categories_bloc.dart b/lib/presentation/setting/bloc/get_categories/get_categories_bloc.dart new file mode 100644 index 0000000..18fdc6b --- /dev/null +++ b/lib/presentation/setting/bloc/get_categories/get_categories_bloc.dart @@ -0,0 +1,27 @@ + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/category_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/category_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_categories_event.dart'; +part 'get_categories_state.dart'; +part 'get_categories_bloc.freezed.dart'; + +class GetCategoriesBloc extends Bloc { + final CategoryRemoteDatasource datasource; + GetCategoriesBloc( + this.datasource, + ) : super(const _Initial()) { + on<_Fetch>((event, emit) async { + emit(const _Loading()); + final result = await datasource.getCategories(); + result.fold( + (l) => emit(_Error(l)), + (r) async { + emit(_Success(r.data)); + }, + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_categories/get_categories_bloc.freezed.dart b/lib/presentation/setting/bloc/get_categories/get_categories_bloc.freezed.dart new file mode 100644 index 0000000..8d1d67b --- /dev/null +++ b/lib/presentation/setting/bloc/get_categories/get_categories_bloc.freezed.dart @@ -0,0 +1,909 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_categories_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetCategoriesEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetCategoriesEventCopyWith<$Res> { + factory $GetCategoriesEventCopyWith( + GetCategoriesEvent value, $Res Function(GetCategoriesEvent) then) = + _$GetCategoriesEventCopyWithImpl<$Res, GetCategoriesEvent>; +} + +/// @nodoc +class _$GetCategoriesEventCopyWithImpl<$Res, $Val extends GetCategoriesEvent> + implements $GetCategoriesEventCopyWith<$Res> { + _$GetCategoriesEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetCategoriesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetCategoriesEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetCategoriesEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetCategoriesEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$FetchImplCopyWith<$Res> { + factory _$$FetchImplCopyWith( + _$FetchImpl value, $Res Function(_$FetchImpl) then) = + __$$FetchImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$FetchImplCopyWithImpl<$Res> + extends _$GetCategoriesEventCopyWithImpl<$Res, _$FetchImpl> + implements _$$FetchImplCopyWith<$Res> { + __$$FetchImplCopyWithImpl( + _$FetchImpl _value, $Res Function(_$FetchImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$FetchImpl implements _Fetch { + const _$FetchImpl(); + + @override + String toString() { + return 'GetCategoriesEvent.fetch()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FetchImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) { + return fetch(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) { + return fetch?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) { + if (fetch != null) { + return fetch(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) { + return fetch(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) { + return fetch?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) { + if (fetch != null) { + return fetch(this); + } + return orElse(); + } +} + +abstract class _Fetch implements GetCategoriesEvent { + const factory _Fetch() = _$FetchImpl; +} + +/// @nodoc +mixin _$GetCategoriesState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List categories) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List categories)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List categories)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetCategoriesStateCopyWith<$Res> { + factory $GetCategoriesStateCopyWith( + GetCategoriesState value, $Res Function(GetCategoriesState) then) = + _$GetCategoriesStateCopyWithImpl<$Res, GetCategoriesState>; +} + +/// @nodoc +class _$GetCategoriesStateCopyWithImpl<$Res, $Val extends GetCategoriesState> + implements $GetCategoriesStateCopyWith<$Res> { + _$GetCategoriesStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetCategoriesStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetCategoriesState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List categories) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List categories)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List categories)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetCategoriesState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetCategoriesStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetCategoriesState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List categories) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List categories)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List categories)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetCategoriesState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({List categories}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetCategoriesStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? categories = null, + }) { + return _then(_$SuccessImpl( + null == categories + ? _value._categories + : categories // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(final List categories) + : _categories = categories; + + final List _categories; + @override + List get categories { + if (_categories is EqualUnmodifiableListView) return _categories; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_categories); + } + + @override + String toString() { + return 'GetCategoriesState.success(categories: $categories)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + const DeepCollectionEquality() + .equals(other._categories, _categories)); + } + + @override + int get hashCode => Object.hash( + runtimeType, const DeepCollectionEquality().hash(_categories)); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List categories) success, + required TResult Function(String message) error, + }) { + return success(categories); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List categories)? success, + TResult? Function(String message)? error, + }) { + return success?.call(categories); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List categories)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(categories); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetCategoriesState { + const factory _Success(final List categories) = _$SuccessImpl; + + List get categories; + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$GetCategoriesStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'GetCategoriesState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List categories) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List categories)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List categories)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements GetCategoriesState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of GetCategoriesState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_categories/get_categories_event.dart b/lib/presentation/setting/bloc/get_categories/get_categories_event.dart new file mode 100644 index 0000000..a7c4f28 --- /dev/null +++ b/lib/presentation/setting/bloc/get_categories/get_categories_event.dart @@ -0,0 +1,7 @@ +part of 'get_categories_bloc.dart'; + +@freezed +class GetCategoriesEvent with _$GetCategoriesEvent { + const factory GetCategoriesEvent.started() = _Started; + const factory GetCategoriesEvent.fetch() = _Fetch; +} diff --git a/lib/presentation/setting/bloc/get_categories/get_categories_state.dart b/lib/presentation/setting/bloc/get_categories/get_categories_state.dart new file mode 100644 index 0000000..c75db9e --- /dev/null +++ b/lib/presentation/setting/bloc/get_categories/get_categories_state.dart @@ -0,0 +1,10 @@ +part of 'get_categories_bloc.dart'; + +@freezed +class GetCategoriesState with _$GetCategoriesState { + const factory GetCategoriesState.initial() = _Initial; + const factory GetCategoriesState.loading() = _Loading; + const factory GetCategoriesState.success(List categories) = + _Success; + const factory GetCategoriesState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart new file mode 100644 index 0000000..08a51ae --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart @@ -0,0 +1,20 @@ + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_printer_bar_event.dart'; +part 'get_printer_bar_state.dart'; +part 'get_printer_bar_bloc.freezed.dart'; + +class GetPrinterBarBloc extends Bloc { + GetPrinterBarBloc() : super(_Initial()) { + on<_Get>((event, emit) async { + emit(_Loading()); + final result = + await ProductLocalDatasource.instance.getPrinterByCode('bar'); + emit(_Success(result)); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.freezed.dart b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.freezed.dart new file mode 100644 index 0000000..e3d4f0a --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.freezed.dart @@ -0,0 +1,723 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_printer_bar_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetPrinterBarEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterBarEventCopyWith<$Res> { + factory $GetPrinterBarEventCopyWith( + GetPrinterBarEvent value, $Res Function(GetPrinterBarEvent) then) = + _$GetPrinterBarEventCopyWithImpl<$Res, GetPrinterBarEvent>; +} + +/// @nodoc +class _$GetPrinterBarEventCopyWithImpl<$Res, $Val extends GetPrinterBarEvent> + implements $GetPrinterBarEventCopyWith<$Res> { + _$GetPrinterBarEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterBarEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetPrinterBarEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterBarEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetPrinterBarEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetPrinterBarEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetImplCopyWith<$Res> { + factory _$$GetImplCopyWith(_$GetImpl value, $Res Function(_$GetImpl) then) = + __$$GetImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetImplCopyWithImpl<$Res> + extends _$GetPrinterBarEventCopyWithImpl<$Res, _$GetImpl> + implements _$$GetImplCopyWith<$Res> { + __$$GetImplCopyWithImpl(_$GetImpl _value, $Res Function(_$GetImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterBarEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetImpl implements _Get { + const _$GetImpl(); + + @override + String toString() { + return 'GetPrinterBarEvent.get()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return get(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return get?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (get != null) { + return get(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return get(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return get?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (get != null) { + return get(this); + } + return orElse(); + } +} + +abstract class _Get implements GetPrinterBarEvent { + const factory _Get() = _$GetImpl; +} + +/// @nodoc +mixin _$GetPrinterBarState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterBarStateCopyWith<$Res> { + factory $GetPrinterBarStateCopyWith( + GetPrinterBarState value, $Res Function(GetPrinterBarState) then) = + _$GetPrinterBarStateCopyWithImpl<$Res, GetPrinterBarState>; +} + +/// @nodoc +class _$GetPrinterBarStateCopyWithImpl<$Res, $Val extends GetPrinterBarState> + implements $GetPrinterBarStateCopyWith<$Res> { + _$GetPrinterBarStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetPrinterBarStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetPrinterBarState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetPrinterBarState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetPrinterBarStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetPrinterBarState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetPrinterBarState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel? printer}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetPrinterBarStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? printer = freezed, + }) { + return _then(_$SuccessImpl( + freezed == printer + ? _value.printer + : printer // ignore: cast_nullable_to_non_nullable + as PrintModel?, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.printer); + + @override + final PrintModel? printer; + + @override + String toString() { + return 'GetPrinterBarState.success(printer: $printer)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.printer, printer) || other.printer == printer)); + } + + @override + int get hashCode => Object.hash(runtimeType, printer); + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return success(printer); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return success?.call(printer); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(printer); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetPrinterBarState { + const factory _Success(final PrintModel? printer) = _$SuccessImpl; + + PrintModel? get printer; + + /// Create a copy of GetPrinterBarState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_event.dart b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_event.dart new file mode 100644 index 0000000..001395b --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_event.dart @@ -0,0 +1,7 @@ +part of 'get_printer_bar_bloc.dart'; + +@freezed +class GetPrinterBarEvent with _$GetPrinterBarEvent { + const factory GetPrinterBarEvent.started() = _Started; + const factory GetPrinterBarEvent.get() = _Get; +} diff --git a/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_state.dart b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_state.dart new file mode 100644 index 0000000..5050f17 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_bar/get_printer_bar_state.dart @@ -0,0 +1,8 @@ +part of 'get_printer_bar_bloc.dart'; + +@freezed +class GetPrinterBarState with _$GetPrinterBarState { + const factory GetPrinterBarState.initial() = _Initial; + const factory GetPrinterBarState.loading() = _Loading; + const factory GetPrinterBarState.success(PrintModel? printer) = _Success; +} diff --git a/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart new file mode 100644 index 0000000..3622cd0 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../../../data/datasources/product_local_datasource.dart'; + +part 'get_printer_checker_event.dart'; +part 'get_printer_checker_state.dart'; +part 'get_printer_checker_bloc.freezed.dart'; + +class GetPrinterCheckerBloc + extends Bloc { + GetPrinterCheckerBloc() : super(_Initial()) { + on<_Get>((event, emit) async { + emit(_Loading()); + final result = + await ProductLocalDatasource.instance.getPrinterByCode('checker'); + emit(_Success(result)); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.freezed.dart b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.freezed.dart new file mode 100644 index 0000000..b0a154d --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.freezed.dart @@ -0,0 +1,725 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_printer_checker_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetPrinterCheckerEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterCheckerEventCopyWith<$Res> { + factory $GetPrinterCheckerEventCopyWith(GetPrinterCheckerEvent value, + $Res Function(GetPrinterCheckerEvent) then) = + _$GetPrinterCheckerEventCopyWithImpl<$Res, GetPrinterCheckerEvent>; +} + +/// @nodoc +class _$GetPrinterCheckerEventCopyWithImpl<$Res, + $Val extends GetPrinterCheckerEvent> + implements $GetPrinterCheckerEventCopyWith<$Res> { + _$GetPrinterCheckerEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterCheckerEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetPrinterCheckerEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterCheckerEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetPrinterCheckerEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetPrinterCheckerEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetImplCopyWith<$Res> { + factory _$$GetImplCopyWith(_$GetImpl value, $Res Function(_$GetImpl) then) = + __$$GetImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetImplCopyWithImpl<$Res> + extends _$GetPrinterCheckerEventCopyWithImpl<$Res, _$GetImpl> + implements _$$GetImplCopyWith<$Res> { + __$$GetImplCopyWithImpl(_$GetImpl _value, $Res Function(_$GetImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterCheckerEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetImpl implements _Get { + const _$GetImpl(); + + @override + String toString() { + return 'GetPrinterCheckerEvent.get()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return get(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return get?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (get != null) { + return get(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return get(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return get?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (get != null) { + return get(this); + } + return orElse(); + } +} + +abstract class _Get implements GetPrinterCheckerEvent { + const factory _Get() = _$GetImpl; +} + +/// @nodoc +mixin _$GetPrinterCheckerState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterCheckerStateCopyWith<$Res> { + factory $GetPrinterCheckerStateCopyWith(GetPrinterCheckerState value, + $Res Function(GetPrinterCheckerState) then) = + _$GetPrinterCheckerStateCopyWithImpl<$Res, GetPrinterCheckerState>; +} + +/// @nodoc +class _$GetPrinterCheckerStateCopyWithImpl<$Res, + $Val extends GetPrinterCheckerState> + implements $GetPrinterCheckerStateCopyWith<$Res> { + _$GetPrinterCheckerStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetPrinterCheckerStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetPrinterCheckerState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetPrinterCheckerState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetPrinterCheckerStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetPrinterCheckerState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetPrinterCheckerState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel? printer}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetPrinterCheckerStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? printer = freezed, + }) { + return _then(_$SuccessImpl( + freezed == printer + ? _value.printer + : printer // ignore: cast_nullable_to_non_nullable + as PrintModel?, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.printer); + + @override + final PrintModel? printer; + + @override + String toString() { + return 'GetPrinterCheckerState.success(printer: $printer)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.printer, printer) || other.printer == printer)); + } + + @override + int get hashCode => Object.hash(runtimeType, printer); + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return success(printer); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return success?.call(printer); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(printer); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetPrinterCheckerState { + const factory _Success(final PrintModel? printer) = _$SuccessImpl; + + PrintModel? get printer; + + /// Create a copy of GetPrinterCheckerState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_event.dart b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_event.dart new file mode 100644 index 0000000..b47c250 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_event.dart @@ -0,0 +1,7 @@ +part of 'get_printer_checker_bloc.dart'; + +@freezed +class GetPrinterCheckerEvent with _$GetPrinterCheckerEvent { + const factory GetPrinterCheckerEvent.started() = _Started; + const factory GetPrinterCheckerEvent.get() = _Get; +} diff --git a/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_state.dart b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_state.dart new file mode 100644 index 0000000..0ea122b --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_checker/get_printer_checker_state.dart @@ -0,0 +1,8 @@ +part of 'get_printer_checker_bloc.dart'; + +@freezed +class GetPrinterCheckerState with _$GetPrinterCheckerState { + const factory GetPrinterCheckerState.initial() = _Initial; + const factory GetPrinterCheckerState.loading() = _Loading; + const factory GetPrinterCheckerState.success(PrintModel? printer) = _Success; +} diff --git a/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart new file mode 100644 index 0000000..5c820de --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart @@ -0,0 +1,20 @@ +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_printer_kitchen_event.dart'; +part 'get_printer_kitchen_state.dart'; +part 'get_printer_kitchen_bloc.freezed.dart'; + +class GetPrinterKitchenBloc + extends Bloc { + GetPrinterKitchenBloc() : super(_Initial()) { + on<_Get>((event, emit) async { + emit(_Loading()); + final result = + await ProductLocalDatasource.instance.getPrinterByCode('kitchen'); + emit(_Success(result)); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.freezed.dart b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.freezed.dart new file mode 100644 index 0000000..df83b07 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.freezed.dart @@ -0,0 +1,725 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_printer_kitchen_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetPrinterKitchenEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterKitchenEventCopyWith<$Res> { + factory $GetPrinterKitchenEventCopyWith(GetPrinterKitchenEvent value, + $Res Function(GetPrinterKitchenEvent) then) = + _$GetPrinterKitchenEventCopyWithImpl<$Res, GetPrinterKitchenEvent>; +} + +/// @nodoc +class _$GetPrinterKitchenEventCopyWithImpl<$Res, + $Val extends GetPrinterKitchenEvent> + implements $GetPrinterKitchenEventCopyWith<$Res> { + _$GetPrinterKitchenEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterKitchenEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetPrinterKitchenEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterKitchenEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetPrinterKitchenEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetPrinterKitchenEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetImplCopyWith<$Res> { + factory _$$GetImplCopyWith(_$GetImpl value, $Res Function(_$GetImpl) then) = + __$$GetImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetImplCopyWithImpl<$Res> + extends _$GetPrinterKitchenEventCopyWithImpl<$Res, _$GetImpl> + implements _$$GetImplCopyWith<$Res> { + __$$GetImplCopyWithImpl(_$GetImpl _value, $Res Function(_$GetImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterKitchenEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetImpl implements _Get { + const _$GetImpl(); + + @override + String toString() { + return 'GetPrinterKitchenEvent.get()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return get(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return get?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (get != null) { + return get(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return get(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return get?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (get != null) { + return get(this); + } + return orElse(); + } +} + +abstract class _Get implements GetPrinterKitchenEvent { + const factory _Get() = _$GetImpl; +} + +/// @nodoc +mixin _$GetPrinterKitchenState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterKitchenStateCopyWith<$Res> { + factory $GetPrinterKitchenStateCopyWith(GetPrinterKitchenState value, + $Res Function(GetPrinterKitchenState) then) = + _$GetPrinterKitchenStateCopyWithImpl<$Res, GetPrinterKitchenState>; +} + +/// @nodoc +class _$GetPrinterKitchenStateCopyWithImpl<$Res, + $Val extends GetPrinterKitchenState> + implements $GetPrinterKitchenStateCopyWith<$Res> { + _$GetPrinterKitchenStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetPrinterKitchenStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetPrinterKitchenState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetPrinterKitchenState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetPrinterKitchenStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetPrinterKitchenState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetPrinterKitchenState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel? printer}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetPrinterKitchenStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? printer = freezed, + }) { + return _then(_$SuccessImpl( + freezed == printer + ? _value.printer + : printer // ignore: cast_nullable_to_non_nullable + as PrintModel?, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.printer); + + @override + final PrintModel? printer; + + @override + String toString() { + return 'GetPrinterKitchenState.success(printer: $printer)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.printer, printer) || other.printer == printer)); + } + + @override + int get hashCode => Object.hash(runtimeType, printer); + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return success(printer); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return success?.call(printer); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(printer); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetPrinterKitchenState { + const factory _Success(final PrintModel? printer) = _$SuccessImpl; + + PrintModel? get printer; + + /// Create a copy of GetPrinterKitchenState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_event.dart b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_event.dart new file mode 100644 index 0000000..040d5e5 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_event.dart @@ -0,0 +1,7 @@ +part of 'get_printer_kitchen_bloc.dart'; + +@freezed +class GetPrinterKitchenEvent with _$GetPrinterKitchenEvent { + const factory GetPrinterKitchenEvent.started() = _Started; + const factory GetPrinterKitchenEvent.get() = _Get; +} diff --git a/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_state.dart b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_state.dart new file mode 100644 index 0000000..fe6ec31 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_state.dart @@ -0,0 +1,8 @@ +part of 'get_printer_kitchen_bloc.dart'; + +@freezed +class GetPrinterKitchenState with _$GetPrinterKitchenState { + const factory GetPrinterKitchenState.initial() = _Initial; + const factory GetPrinterKitchenState.loading() = _Loading; + const factory GetPrinterKitchenState.success(PrintModel? printer) = _Success; +} diff --git a/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart new file mode 100644 index 0000000..d31516a --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart @@ -0,0 +1,20 @@ +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_printer_receipt_event.dart'; +part 'get_printer_receipt_state.dart'; +part 'get_printer_receipt_bloc.freezed.dart'; + +class GetPrinterReceiptBloc + extends Bloc { + GetPrinterReceiptBloc() : super(_Initial()) { + on<_Get>((event, emit) async { + emit(_Loading()); + final result = + await ProductLocalDatasource.instance.getPrinterByCode('receipt'); + emit(_Success(result)); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.freezed.dart b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.freezed.dart new file mode 100644 index 0000000..e1a7ee4 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.freezed.dart @@ -0,0 +1,725 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_printer_receipt_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetPrinterReceiptEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterReceiptEventCopyWith<$Res> { + factory $GetPrinterReceiptEventCopyWith(GetPrinterReceiptEvent value, + $Res Function(GetPrinterReceiptEvent) then) = + _$GetPrinterReceiptEventCopyWithImpl<$Res, GetPrinterReceiptEvent>; +} + +/// @nodoc +class _$GetPrinterReceiptEventCopyWithImpl<$Res, + $Val extends GetPrinterReceiptEvent> + implements $GetPrinterReceiptEventCopyWith<$Res> { + _$GetPrinterReceiptEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterReceiptEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetPrinterReceiptEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterReceiptEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetPrinterReceiptEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetPrinterReceiptEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetImplCopyWith<$Res> { + factory _$$GetImplCopyWith(_$GetImpl value, $Res Function(_$GetImpl) then) = + __$$GetImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetImplCopyWithImpl<$Res> + extends _$GetPrinterReceiptEventCopyWithImpl<$Res, _$GetImpl> + implements _$$GetImplCopyWith<$Res> { + __$$GetImplCopyWithImpl(_$GetImpl _value, $Res Function(_$GetImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterReceiptEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetImpl implements _Get { + const _$GetImpl(); + + @override + String toString() { + return 'GetPrinterReceiptEvent.get()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() get, + }) { + return get(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? get, + }) { + return get?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? get, + required TResult orElse(), + }) { + if (get != null) { + return get(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Get value) get, + }) { + return get(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Get value)? get, + }) { + return get?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Get value)? get, + required TResult orElse(), + }) { + if (get != null) { + return get(this); + } + return orElse(); + } +} + +abstract class _Get implements GetPrinterReceiptEvent { + const factory _Get() = _$GetImpl; +} + +/// @nodoc +mixin _$GetPrinterReceiptState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetPrinterReceiptStateCopyWith<$Res> { + factory $GetPrinterReceiptStateCopyWith(GetPrinterReceiptState value, + $Res Function(GetPrinterReceiptState) then) = + _$GetPrinterReceiptStateCopyWithImpl<$Res, GetPrinterReceiptState>; +} + +/// @nodoc +class _$GetPrinterReceiptStateCopyWithImpl<$Res, + $Val extends GetPrinterReceiptState> + implements $GetPrinterReceiptStateCopyWith<$Res> { + _$GetPrinterReceiptStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetPrinterReceiptStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetPrinterReceiptState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetPrinterReceiptState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetPrinterReceiptStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetPrinterReceiptState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetPrinterReceiptState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel? printer}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetPrinterReceiptStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? printer = freezed, + }) { + return _then(_$SuccessImpl( + freezed == printer + ? _value.printer + : printer // ignore: cast_nullable_to_non_nullable + as PrintModel?, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.printer); + + @override + final PrintModel? printer; + + @override + String toString() { + return 'GetPrinterReceiptState.success(printer: $printer)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.printer, printer) || other.printer == printer)); + } + + @override + int get hashCode => Object.hash(runtimeType, printer); + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(PrintModel? printer) success, + }) { + return success(printer); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(PrintModel? printer)? success, + }) { + return success?.call(printer); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(PrintModel? printer)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(printer); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetPrinterReceiptState { + const factory _Success(final PrintModel? printer) = _$SuccessImpl; + + PrintModel? get printer; + + /// Create a copy of GetPrinterReceiptState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_event.dart b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_event.dart new file mode 100644 index 0000000..16a3c62 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_event.dart @@ -0,0 +1,7 @@ +part of 'get_printer_receipt_bloc.dart'; + +@freezed +class GetPrinterReceiptEvent with _$GetPrinterReceiptEvent { + const factory GetPrinterReceiptEvent.started() = _Started; + const factory GetPrinterReceiptEvent.get() = _Get; +} diff --git a/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_state.dart b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_state.dart new file mode 100644 index 0000000..2c144d5 --- /dev/null +++ b/lib/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_state.dart @@ -0,0 +1,8 @@ +part of 'get_printer_receipt_bloc.dart'; + +@freezed +class GetPrinterReceiptState with _$GetPrinterReceiptState { + const factory GetPrinterReceiptState.initial() = _Initial; + const factory GetPrinterReceiptState.loading() = _Loading; + const factory GetPrinterReceiptState.success(PrintModel? printer) = _Success; +} diff --git a/lib/presentation/setting/bloc/get_products/get_products_bloc.dart b/lib/presentation/setting/bloc/get_products/get_products_bloc.dart new file mode 100644 index 0000000..bf492ce --- /dev/null +++ b/lib/presentation/setting/bloc/get_products/get_products_bloc.dart @@ -0,0 +1,27 @@ + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_products_event.dart'; +part 'get_products_state.dart'; +part 'get_products_bloc.freezed.dart'; + +class GetProductsBloc extends Bloc { + final ProductRemoteDatasource datasource; + GetProductsBloc( + this.datasource, + ) : super(const _Initial()) { + on<_Fetch>((event, emit) async { + emit(const _Loading()); + final response = await datasource.getProducts(); + response.fold( + (l) => emit(_Error(l)), + (r) { + emit(_Success(r.data!)); + }, + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/get_products/get_products_bloc.freezed.dart b/lib/presentation/setting/bloc/get_products/get_products_bloc.freezed.dart new file mode 100644 index 0000000..8872dee --- /dev/null +++ b/lib/presentation/setting/bloc/get_products/get_products_bloc.freezed.dart @@ -0,0 +1,907 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_products_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetProductsEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetProductsEventCopyWith<$Res> { + factory $GetProductsEventCopyWith( + GetProductsEvent value, $Res Function(GetProductsEvent) then) = + _$GetProductsEventCopyWithImpl<$Res, GetProductsEvent>; +} + +/// @nodoc +class _$GetProductsEventCopyWithImpl<$Res, $Val extends GetProductsEvent> + implements $GetProductsEventCopyWith<$Res> { + _$GetProductsEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetProductsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetProductsEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetProductsEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetProductsEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$FetchImplCopyWith<$Res> { + factory _$$FetchImplCopyWith( + _$FetchImpl value, $Res Function(_$FetchImpl) then) = + __$$FetchImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$FetchImplCopyWithImpl<$Res> + extends _$GetProductsEventCopyWithImpl<$Res, _$FetchImpl> + implements _$$FetchImplCopyWith<$Res> { + __$$FetchImplCopyWithImpl( + _$FetchImpl _value, $Res Function(_$FetchImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$FetchImpl implements _Fetch { + const _$FetchImpl(); + + @override + String toString() { + return 'GetProductsEvent.fetch()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$FetchImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() fetch, + }) { + return fetch(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? fetch, + }) { + return fetch?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? fetch, + required TResult orElse(), + }) { + if (fetch != null) { + return fetch(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Fetch value) fetch, + }) { + return fetch(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Fetch value)? fetch, + }) { + return fetch?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Fetch value)? fetch, + required TResult orElse(), + }) { + if (fetch != null) { + return fetch(this); + } + return orElse(); + } +} + +abstract class _Fetch implements GetProductsEvent { + const factory _Fetch() = _$FetchImpl; +} + +/// @nodoc +mixin _$GetProductsState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetProductsStateCopyWith<$Res> { + factory $GetProductsStateCopyWith( + GetProductsState value, $Res Function(GetProductsState) then) = + _$GetProductsStateCopyWithImpl<$Res, GetProductsState>; +} + +/// @nodoc +class _$GetProductsStateCopyWithImpl<$Res, $Val extends GetProductsState> + implements $GetProductsStateCopyWith<$Res> { + _$GetProductsStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetProductsStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetProductsState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetProductsState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetProductsStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetProductsState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetProductsState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({List products}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetProductsStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? products = null, + }) { + return _then(_$SuccessImpl( + null == products + ? _value._products + : products // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(final List products) : _products = products; + + final List _products; + @override + List get products { + if (_products is EqualUnmodifiableListView) return _products; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_products); + } + + @override + String toString() { + return 'GetProductsState.success(products: $products)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + const DeepCollectionEquality().equals(other._products, _products)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_products)); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) success, + required TResult Function(String message) error, + }) { + return success(products); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? success, + TResult? Function(String message)? error, + }) { + return success?.call(products); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(products); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetProductsState { + const factory _Success(final List products) = _$SuccessImpl; + + List get products; + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$GetProductsStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'GetProductsState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List products) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List products)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List products)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements GetProductsState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of GetProductsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/get_products/get_products_event.dart b/lib/presentation/setting/bloc/get_products/get_products_event.dart new file mode 100644 index 0000000..18fe6d2 --- /dev/null +++ b/lib/presentation/setting/bloc/get_products/get_products_event.dart @@ -0,0 +1,7 @@ +part of 'get_products_bloc.dart'; + +@freezed +class GetProductsEvent with _$GetProductsEvent { + const factory GetProductsEvent.started() = _Started; + const factory GetProductsEvent.fetch() = _Fetch; +} diff --git a/lib/presentation/setting/bloc/get_products/get_products_state.dart b/lib/presentation/setting/bloc/get_products/get_products_state.dart new file mode 100644 index 0000000..a0b9636 --- /dev/null +++ b/lib/presentation/setting/bloc/get_products/get_products_state.dart @@ -0,0 +1,9 @@ +part of 'get_products_bloc.dart'; + +@freezed +class GetProductsState with _$GetProductsState { + const factory GetProductsState.initial() = _Initial; + const factory GetProductsState.loading() = _Loading; + const factory GetProductsState.success(List products) = _Success; + const factory GetProductsState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/sync_order/sync_order_bloc.dart b/lib/presentation/setting/bloc/sync_order/sync_order_bloc.dart new file mode 100644 index 0000000..d1d0f1a --- /dev/null +++ b/lib/presentation/setting/bloc/sync_order/sync_order_bloc.dart @@ -0,0 +1,42 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/order_remote_datasource.dart'; + +part 'sync_order_bloc.freezed.dart'; +part 'sync_order_event.dart'; +part 'sync_order_state.dart'; + +class SyncOrderBloc extends Bloc { + final OrderRemoteDatasource orderRemoteDatasource; + SyncOrderBloc( + this.orderRemoteDatasource, + ) : super(const _Initial()) { + on<_SyncOrder>((event, emit) async { + emit(const _Loading()); + log("🔄 SyncOrderBloc: Starting sync process"); + final dataOrderNotSynced = + await ProductLocalDatasource.instance.getOrderByIsNotSync(); + log("🔄 SyncOrderBloc: Found ${dataOrderNotSynced.length} orders to sync"); + for (var order in dataOrderNotSynced) { + final orderItem = await ProductLocalDatasource.instance + .getOrderItemByOrderId(order.id!); + + final newOrder = order.copyWith(orderItems: orderItem); + log("🔄 SyncOrderBloc: Syncing order ${order.id} to API"); + log("Order: ${newOrder.toMap()}"); + final result = await orderRemoteDatasource.saveOrder(newOrder); + if (result) { + await ProductLocalDatasource.instance.updateOrderIsSync(order.id!); + } else { + emit(const _Error('Sync Order Failed')); + return; + } + } + emit(const _Loaded()); + }); + } +} diff --git a/lib/presentation/setting/bloc/sync_order/sync_order_bloc.freezed.dart b/lib/presentation/setting/bloc/sync_order/sync_order_bloc.freezed.dart new file mode 100644 index 0000000..271f7e2 --- /dev/null +++ b/lib/presentation/setting/bloc/sync_order/sync_order_bloc.freezed.dart @@ -0,0 +1,866 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'sync_order_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$SyncOrderEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncOrder value) syncOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncOrder value)? syncOrder, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncOrder value)? syncOrder, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SyncOrderEventCopyWith<$Res> { + factory $SyncOrderEventCopyWith( + SyncOrderEvent value, $Res Function(SyncOrderEvent) then) = + _$SyncOrderEventCopyWithImpl<$Res, SyncOrderEvent>; +} + +/// @nodoc +class _$SyncOrderEventCopyWithImpl<$Res, $Val extends SyncOrderEvent> + implements $SyncOrderEventCopyWith<$Res> { + _$SyncOrderEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SyncOrderEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$SyncOrderEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'SyncOrderEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncOrder, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncOrder, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncOrder, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncOrder value) syncOrder, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncOrder value)? syncOrder, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncOrder value)? syncOrder, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements SyncOrderEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$SyncOrderImplCopyWith<$Res> { + factory _$$SyncOrderImplCopyWith( + _$SyncOrderImpl value, $Res Function(_$SyncOrderImpl) then) = + __$$SyncOrderImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SyncOrderImplCopyWithImpl<$Res> + extends _$SyncOrderEventCopyWithImpl<$Res, _$SyncOrderImpl> + implements _$$SyncOrderImplCopyWith<$Res> { + __$$SyncOrderImplCopyWithImpl( + _$SyncOrderImpl _value, $Res Function(_$SyncOrderImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SyncOrderImpl implements _SyncOrder { + const _$SyncOrderImpl(); + + @override + String toString() { + return 'SyncOrderEvent.syncOrder()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SyncOrderImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncOrder, + }) { + return syncOrder(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncOrder, + }) { + return syncOrder?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncOrder, + required TResult orElse(), + }) { + if (syncOrder != null) { + return syncOrder(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncOrder value) syncOrder, + }) { + return syncOrder(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncOrder value)? syncOrder, + }) { + return syncOrder?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncOrder value)? syncOrder, + required TResult orElse(), + }) { + if (syncOrder != null) { + return syncOrder(this); + } + return orElse(); + } +} + +abstract class _SyncOrder implements SyncOrderEvent { + const factory _SyncOrder() = _$SyncOrderImpl; +} + +/// @nodoc +mixin _$SyncOrderState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SyncOrderStateCopyWith<$Res> { + factory $SyncOrderStateCopyWith( + SyncOrderState value, $Res Function(SyncOrderState) then) = + _$SyncOrderStateCopyWithImpl<$Res, SyncOrderState>; +} + +/// @nodoc +class _$SyncOrderStateCopyWithImpl<$Res, $Val extends SyncOrderState> + implements $SyncOrderStateCopyWith<$Res> { + _$SyncOrderStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$SyncOrderStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'SyncOrderState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements SyncOrderState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$SyncOrderStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'SyncOrderState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements SyncOrderState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$SyncOrderStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(); + + @override + String toString() { + return 'SyncOrderState.loaded()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() loaded, + required TResult Function(String message) error, + }) { + return loaded(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements SyncOrderState { + const factory _Loaded() = _$LoadedImpl; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$SyncOrderStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'SyncOrderState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function() loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function()? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function()? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements SyncOrderState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of SyncOrderState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/sync_order/sync_order_event.dart b/lib/presentation/setting/bloc/sync_order/sync_order_event.dart new file mode 100644 index 0000000..fedb95a --- /dev/null +++ b/lib/presentation/setting/bloc/sync_order/sync_order_event.dart @@ -0,0 +1,7 @@ +part of 'sync_order_bloc.dart'; + +@freezed +class SyncOrderEvent with _$SyncOrderEvent { + const factory SyncOrderEvent.started() = _Started; + const factory SyncOrderEvent.syncOrder() = _SyncOrder; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/sync_order/sync_order_state.dart b/lib/presentation/setting/bloc/sync_order/sync_order_state.dart new file mode 100644 index 0000000..0a17fde --- /dev/null +++ b/lib/presentation/setting/bloc/sync_order/sync_order_state.dart @@ -0,0 +1,10 @@ +part of 'sync_order_bloc.dart'; + +@freezed +class SyncOrderState with _$SyncOrderState { + const factory SyncOrderState.initial() = _Initial; + const factory SyncOrderState.loading() = _Loading; + const factory SyncOrderState.loaded() = + _Loaded; + const factory SyncOrderState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/sync_product/sync_product_bloc.dart b/lib/presentation/setting/bloc/sync_product/sync_product_bloc.dart new file mode 100644 index 0000000..56ab4a8 --- /dev/null +++ b/lib/presentation/setting/bloc/sync_product/sync_product_bloc.dart @@ -0,0 +1,25 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +part 'sync_product_bloc.freezed.dart'; +part 'sync_product_event.dart'; +part 'sync_product_state.dart'; + +class SyncProductBloc extends Bloc { + final ProductRemoteDatasource productRemoteDatasource; + SyncProductBloc( + this.productRemoteDatasource, + ) : super(const _Initial()) { + on<_SyncProduct>((event, emit) async{ + emit(const _Loading()); + final result = await productRemoteDatasource.getProducts(); + result.fold( + (l) => emit(_Error(l)), + (r) => emit(_Loaded(r)), + ); + }); + } +} diff --git a/lib/presentation/setting/bloc/sync_product/sync_product_bloc.freezed.dart b/lib/presentation/setting/bloc/sync_product/sync_product_bloc.freezed.dart new file mode 100644 index 0000000..b503276 --- /dev/null +++ b/lib/presentation/setting/bloc/sync_product/sync_product_bloc.freezed.dart @@ -0,0 +1,903 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'sync_product_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$SyncProductEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncProduct value) syncProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncProduct value)? syncProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncProduct value)? syncProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SyncProductEventCopyWith<$Res> { + factory $SyncProductEventCopyWith( + SyncProductEvent value, $Res Function(SyncProductEvent) then) = + _$SyncProductEventCopyWithImpl<$Res, SyncProductEvent>; +} + +/// @nodoc +class _$SyncProductEventCopyWithImpl<$Res, $Val extends SyncProductEvent> + implements $SyncProductEventCopyWith<$Res> { + _$SyncProductEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SyncProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$SyncProductEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'SyncProductEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncProduct, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncProduct, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncProduct value) syncProduct, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncProduct value)? syncProduct, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncProduct value)? syncProduct, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements SyncProductEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$SyncProductImplCopyWith<$Res> { + factory _$$SyncProductImplCopyWith( + _$SyncProductImpl value, $Res Function(_$SyncProductImpl) then) = + __$$SyncProductImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$SyncProductImplCopyWithImpl<$Res> + extends _$SyncProductEventCopyWithImpl<$Res, _$SyncProductImpl> + implements _$$SyncProductImplCopyWith<$Res> { + __$$SyncProductImplCopyWithImpl( + _$SyncProductImpl _value, $Res Function(_$SyncProductImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$SyncProductImpl implements _SyncProduct { + const _$SyncProductImpl(); + + @override + String toString() { + return 'SyncProductEvent.syncProduct()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$SyncProductImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() syncProduct, + }) { + return syncProduct(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? syncProduct, + }) { + return syncProduct?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? syncProduct, + required TResult orElse(), + }) { + if (syncProduct != null) { + return syncProduct(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_SyncProduct value) syncProduct, + }) { + return syncProduct(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_SyncProduct value)? syncProduct, + }) { + return syncProduct?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_SyncProduct value)? syncProduct, + required TResult orElse(), + }) { + if (syncProduct != null) { + return syncProduct(this); + } + return orElse(); + } +} + +abstract class _SyncProduct implements SyncProductEvent { + const factory _SyncProduct() = _$SyncProductImpl; +} + +/// @nodoc +mixin _$SyncProductState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(ProductResponseModel productResponseModel) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(ProductResponseModel productResponseModel)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(ProductResponseModel productResponseModel)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SyncProductStateCopyWith<$Res> { + factory $SyncProductStateCopyWith( + SyncProductState value, $Res Function(SyncProductState) then) = + _$SyncProductStateCopyWithImpl<$Res, SyncProductState>; +} + +/// @nodoc +class _$SyncProductStateCopyWithImpl<$Res, $Val extends SyncProductState> + implements $SyncProductStateCopyWith<$Res> { + _$SyncProductStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$SyncProductStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'SyncProductState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(ProductResponseModel productResponseModel) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(ProductResponseModel productResponseModel)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(ProductResponseModel productResponseModel)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements SyncProductState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$SyncProductStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'SyncProductState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(ProductResponseModel productResponseModel) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(ProductResponseModel productResponseModel)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(ProductResponseModel productResponseModel)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements SyncProductState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({ProductResponseModel productResponseModel}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$SyncProductStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? productResponseModel = null, + }) { + return _then(_$LoadedImpl( + null == productResponseModel + ? _value.productResponseModel + : productResponseModel // ignore: cast_nullable_to_non_nullable + as ProductResponseModel, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl(this.productResponseModel); + + @override + final ProductResponseModel productResponseModel; + + @override + String toString() { + return 'SyncProductState.loaded(productResponseModel: $productResponseModel)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + (identical(other.productResponseModel, productResponseModel) || + other.productResponseModel == productResponseModel)); + } + + @override + int get hashCode => Object.hash(runtimeType, productResponseModel); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(ProductResponseModel productResponseModel) loaded, + required TResult Function(String message) error, + }) { + return loaded(productResponseModel); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(ProductResponseModel productResponseModel)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(productResponseModel); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(ProductResponseModel productResponseModel)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(productResponseModel); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements SyncProductState { + const factory _Loaded(final ProductResponseModel productResponseModel) = + _$LoadedImpl; + + ProductResponseModel get productResponseModel; + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$SyncProductStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'SyncProductState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(ProductResponseModel productResponseModel) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(ProductResponseModel productResponseModel)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(ProductResponseModel productResponseModel)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements SyncProductState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of SyncProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/sync_product/sync_product_event.dart b/lib/presentation/setting/bloc/sync_product/sync_product_event.dart new file mode 100644 index 0000000..aff5b20 --- /dev/null +++ b/lib/presentation/setting/bloc/sync_product/sync_product_event.dart @@ -0,0 +1,7 @@ +part of 'sync_product_bloc.dart'; + +@freezed +class SyncProductEvent with _$SyncProductEvent { + const factory SyncProductEvent.started() = _Started; + const factory SyncProductEvent.syncProduct() = _SyncProduct; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/sync_product/sync_product_state.dart b/lib/presentation/setting/bloc/sync_product/sync_product_state.dart new file mode 100644 index 0000000..b5ccaa1 --- /dev/null +++ b/lib/presentation/setting/bloc/sync_product/sync_product_state.dart @@ -0,0 +1,9 @@ +part of 'sync_product_bloc.dart'; + +@freezed +class SyncProductState with _$SyncProductState { + const factory SyncProductState.initial() = _Initial; + const factory SyncProductState.loading() = _Loading; + const factory SyncProductState.loaded(ProductResponseModel productResponseModel) = _Loaded; + const factory SyncProductState.error(String message) = _Error; +} diff --git a/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.dart b/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.dart new file mode 100644 index 0000000..f2f9fcb --- /dev/null +++ b/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.dart @@ -0,0 +1,82 @@ +import 'package:bloc/bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../../../data/datasources/settings_local_datasource.dart'; +import '../../models/tax_model.dart'; + +part 'tax_settings_event.dart'; +part 'tax_settings_state.dart'; +part 'tax_settings_bloc.freezed.dart'; + +class TaxSettingsBloc extends Bloc { + final SettingsLocalDatasource settingsLocalDatasource; + + TaxSettingsBloc(this.settingsLocalDatasource) : super(const _Initial()) { + on<_LoadSettings>((event, emit) async { + emit(const _Loading()); + try { + final tax = await settingsLocalDatasource.getTax(); + final serviceCharge = await settingsLocalDatasource.getServiceCharge(); + + emit(_Loaded( + taxModel: tax, + serviceChargeValue: serviceCharge, + )); + } catch (e) { + emit(_Error(e.toString())); + } + }); + + on<_SaveTax>((event, emit) async { + emit(const _Loading()); + try { + await settingsLocalDatasource.saveTax(event.taxModel); + final serviceCharge = await settingsLocalDatasource.getServiceCharge(); + + emit(_Loaded( + taxModel: event.taxModel, + serviceChargeValue: serviceCharge, + )); + } catch (e) { + emit(_Error(e.toString())); + } + }); + + on<_SaveServiceCharge>((event, emit) async { + emit(const _Loading()); + try { + await settingsLocalDatasource.saveServiceCharge(event.serviceCharge); + final tax = await settingsLocalDatasource.getTax(); + + emit(_Loaded( + taxModel: tax, + serviceChargeValue: event.serviceCharge, + )); + } catch (e) { + emit(_Error(e.toString())); + } + }); + + on<_UpdateSettings>((event, emit) async { + emit(const _Loading()); + try { + // Create tax model + final taxModel = TaxModel( + name: 'Pajak PB1', + type: TaxType.pajak, + value: event.taxValue, + ); + + await settingsLocalDatasource.saveTax(taxModel); + await settingsLocalDatasource.saveServiceCharge(event.serviceChargeValue); + + emit(_Loaded( + taxModel: taxModel, + serviceChargeValue: event.serviceChargeValue, + )); + } catch (e) { + emit(_Error(e.toString())); + } + }); + } +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.freezed.dart b/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.freezed.dart new file mode 100644 index 0000000..19fd26d --- /dev/null +++ b/lib/presentation/setting/bloc/tax_settings/tax_settings_bloc.freezed.dart @@ -0,0 +1,1314 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'tax_settings_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$TaxSettingsEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() loadSettings, + required TResult Function(TaxModel taxModel) saveTax, + required TResult Function(int serviceCharge) saveServiceCharge, + required TResult Function(int taxValue, int serviceChargeValue) + updateSettings, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loadSettings, + TResult? Function(TaxModel taxModel)? saveTax, + TResult? Function(int serviceCharge)? saveServiceCharge, + TResult? Function(int taxValue, int serviceChargeValue)? updateSettings, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loadSettings, + TResult Function(TaxModel taxModel)? saveTax, + TResult Function(int serviceCharge)? saveServiceCharge, + TResult Function(int taxValue, int serviceChargeValue)? updateSettings, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_LoadSettings value) loadSettings, + required TResult Function(_SaveTax value) saveTax, + required TResult Function(_SaveServiceCharge value) saveServiceCharge, + required TResult Function(_UpdateSettings value) updateSettings, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_LoadSettings value)? loadSettings, + TResult? Function(_SaveTax value)? saveTax, + TResult? Function(_SaveServiceCharge value)? saveServiceCharge, + TResult? Function(_UpdateSettings value)? updateSettings, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_LoadSettings value)? loadSettings, + TResult Function(_SaveTax value)? saveTax, + TResult Function(_SaveServiceCharge value)? saveServiceCharge, + TResult Function(_UpdateSettings value)? updateSettings, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TaxSettingsEventCopyWith<$Res> { + factory $TaxSettingsEventCopyWith( + TaxSettingsEvent value, $Res Function(TaxSettingsEvent) then) = + _$TaxSettingsEventCopyWithImpl<$Res, TaxSettingsEvent>; +} + +/// @nodoc +class _$TaxSettingsEventCopyWithImpl<$Res, $Val extends TaxSettingsEvent> + implements $TaxSettingsEventCopyWith<$Res> { + _$TaxSettingsEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$LoadSettingsImplCopyWith<$Res> { + factory _$$LoadSettingsImplCopyWith( + _$LoadSettingsImpl value, $Res Function(_$LoadSettingsImpl) then) = + __$$LoadSettingsImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadSettingsImplCopyWithImpl<$Res> + extends _$TaxSettingsEventCopyWithImpl<$Res, _$LoadSettingsImpl> + implements _$$LoadSettingsImplCopyWith<$Res> { + __$$LoadSettingsImplCopyWithImpl( + _$LoadSettingsImpl _value, $Res Function(_$LoadSettingsImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadSettingsImpl implements _LoadSettings { + const _$LoadSettingsImpl(); + + @override + String toString() { + return 'TaxSettingsEvent.loadSettings()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadSettingsImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loadSettings, + required TResult Function(TaxModel taxModel) saveTax, + required TResult Function(int serviceCharge) saveServiceCharge, + required TResult Function(int taxValue, int serviceChargeValue) + updateSettings, + }) { + return loadSettings(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loadSettings, + TResult? Function(TaxModel taxModel)? saveTax, + TResult? Function(int serviceCharge)? saveServiceCharge, + TResult? Function(int taxValue, int serviceChargeValue)? updateSettings, + }) { + return loadSettings?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loadSettings, + TResult Function(TaxModel taxModel)? saveTax, + TResult Function(int serviceCharge)? saveServiceCharge, + TResult Function(int taxValue, int serviceChargeValue)? updateSettings, + required TResult orElse(), + }) { + if (loadSettings != null) { + return loadSettings(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_LoadSettings value) loadSettings, + required TResult Function(_SaveTax value) saveTax, + required TResult Function(_SaveServiceCharge value) saveServiceCharge, + required TResult Function(_UpdateSettings value) updateSettings, + }) { + return loadSettings(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_LoadSettings value)? loadSettings, + TResult? Function(_SaveTax value)? saveTax, + TResult? Function(_SaveServiceCharge value)? saveServiceCharge, + TResult? Function(_UpdateSettings value)? updateSettings, + }) { + return loadSettings?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_LoadSettings value)? loadSettings, + TResult Function(_SaveTax value)? saveTax, + TResult Function(_SaveServiceCharge value)? saveServiceCharge, + TResult Function(_UpdateSettings value)? updateSettings, + required TResult orElse(), + }) { + if (loadSettings != null) { + return loadSettings(this); + } + return orElse(); + } +} + +abstract class _LoadSettings implements TaxSettingsEvent { + const factory _LoadSettings() = _$LoadSettingsImpl; +} + +/// @nodoc +abstract class _$$SaveTaxImplCopyWith<$Res> { + factory _$$SaveTaxImplCopyWith( + _$SaveTaxImpl value, $Res Function(_$SaveTaxImpl) then) = + __$$SaveTaxImplCopyWithImpl<$Res>; + @useResult + $Res call({TaxModel taxModel}); +} + +/// @nodoc +class __$$SaveTaxImplCopyWithImpl<$Res> + extends _$TaxSettingsEventCopyWithImpl<$Res, _$SaveTaxImpl> + implements _$$SaveTaxImplCopyWith<$Res> { + __$$SaveTaxImplCopyWithImpl( + _$SaveTaxImpl _value, $Res Function(_$SaveTaxImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? taxModel = null, + }) { + return _then(_$SaveTaxImpl( + null == taxModel + ? _value.taxModel + : taxModel // ignore: cast_nullable_to_non_nullable + as TaxModel, + )); + } +} + +/// @nodoc + +class _$SaveTaxImpl implements _SaveTax { + const _$SaveTaxImpl(this.taxModel); + + @override + final TaxModel taxModel; + + @override + String toString() { + return 'TaxSettingsEvent.saveTax(taxModel: $taxModel)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SaveTaxImpl && + (identical(other.taxModel, taxModel) || + other.taxModel == taxModel)); + } + + @override + int get hashCode => Object.hash(runtimeType, taxModel); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SaveTaxImplCopyWith<_$SaveTaxImpl> get copyWith => + __$$SaveTaxImplCopyWithImpl<_$SaveTaxImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loadSettings, + required TResult Function(TaxModel taxModel) saveTax, + required TResult Function(int serviceCharge) saveServiceCharge, + required TResult Function(int taxValue, int serviceChargeValue) + updateSettings, + }) { + return saveTax(taxModel); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loadSettings, + TResult? Function(TaxModel taxModel)? saveTax, + TResult? Function(int serviceCharge)? saveServiceCharge, + TResult? Function(int taxValue, int serviceChargeValue)? updateSettings, + }) { + return saveTax?.call(taxModel); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loadSettings, + TResult Function(TaxModel taxModel)? saveTax, + TResult Function(int serviceCharge)? saveServiceCharge, + TResult Function(int taxValue, int serviceChargeValue)? updateSettings, + required TResult orElse(), + }) { + if (saveTax != null) { + return saveTax(taxModel); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_LoadSettings value) loadSettings, + required TResult Function(_SaveTax value) saveTax, + required TResult Function(_SaveServiceCharge value) saveServiceCharge, + required TResult Function(_UpdateSettings value) updateSettings, + }) { + return saveTax(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_LoadSettings value)? loadSettings, + TResult? Function(_SaveTax value)? saveTax, + TResult? Function(_SaveServiceCharge value)? saveServiceCharge, + TResult? Function(_UpdateSettings value)? updateSettings, + }) { + return saveTax?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_LoadSettings value)? loadSettings, + TResult Function(_SaveTax value)? saveTax, + TResult Function(_SaveServiceCharge value)? saveServiceCharge, + TResult Function(_UpdateSettings value)? updateSettings, + required TResult orElse(), + }) { + if (saveTax != null) { + return saveTax(this); + } + return orElse(); + } +} + +abstract class _SaveTax implements TaxSettingsEvent { + const factory _SaveTax(final TaxModel taxModel) = _$SaveTaxImpl; + + TaxModel get taxModel; + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SaveTaxImplCopyWith<_$SaveTaxImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$SaveServiceChargeImplCopyWith<$Res> { + factory _$$SaveServiceChargeImplCopyWith(_$SaveServiceChargeImpl value, + $Res Function(_$SaveServiceChargeImpl) then) = + __$$SaveServiceChargeImplCopyWithImpl<$Res>; + @useResult + $Res call({int serviceCharge}); +} + +/// @nodoc +class __$$SaveServiceChargeImplCopyWithImpl<$Res> + extends _$TaxSettingsEventCopyWithImpl<$Res, _$SaveServiceChargeImpl> + implements _$$SaveServiceChargeImplCopyWith<$Res> { + __$$SaveServiceChargeImplCopyWithImpl(_$SaveServiceChargeImpl _value, + $Res Function(_$SaveServiceChargeImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? serviceCharge = null, + }) { + return _then(_$SaveServiceChargeImpl( + null == serviceCharge + ? _value.serviceCharge + : serviceCharge // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$SaveServiceChargeImpl implements _SaveServiceCharge { + const _$SaveServiceChargeImpl(this.serviceCharge); + + @override + final int serviceCharge; + + @override + String toString() { + return 'TaxSettingsEvent.saveServiceCharge(serviceCharge: $serviceCharge)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SaveServiceChargeImpl && + (identical(other.serviceCharge, serviceCharge) || + other.serviceCharge == serviceCharge)); + } + + @override + int get hashCode => Object.hash(runtimeType, serviceCharge); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SaveServiceChargeImplCopyWith<_$SaveServiceChargeImpl> get copyWith => + __$$SaveServiceChargeImplCopyWithImpl<_$SaveServiceChargeImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loadSettings, + required TResult Function(TaxModel taxModel) saveTax, + required TResult Function(int serviceCharge) saveServiceCharge, + required TResult Function(int taxValue, int serviceChargeValue) + updateSettings, + }) { + return saveServiceCharge(serviceCharge); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loadSettings, + TResult? Function(TaxModel taxModel)? saveTax, + TResult? Function(int serviceCharge)? saveServiceCharge, + TResult? Function(int taxValue, int serviceChargeValue)? updateSettings, + }) { + return saveServiceCharge?.call(serviceCharge); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loadSettings, + TResult Function(TaxModel taxModel)? saveTax, + TResult Function(int serviceCharge)? saveServiceCharge, + TResult Function(int taxValue, int serviceChargeValue)? updateSettings, + required TResult orElse(), + }) { + if (saveServiceCharge != null) { + return saveServiceCharge(serviceCharge); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_LoadSettings value) loadSettings, + required TResult Function(_SaveTax value) saveTax, + required TResult Function(_SaveServiceCharge value) saveServiceCharge, + required TResult Function(_UpdateSettings value) updateSettings, + }) { + return saveServiceCharge(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_LoadSettings value)? loadSettings, + TResult? Function(_SaveTax value)? saveTax, + TResult? Function(_SaveServiceCharge value)? saveServiceCharge, + TResult? Function(_UpdateSettings value)? updateSettings, + }) { + return saveServiceCharge?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_LoadSettings value)? loadSettings, + TResult Function(_SaveTax value)? saveTax, + TResult Function(_SaveServiceCharge value)? saveServiceCharge, + TResult Function(_UpdateSettings value)? updateSettings, + required TResult orElse(), + }) { + if (saveServiceCharge != null) { + return saveServiceCharge(this); + } + return orElse(); + } +} + +abstract class _SaveServiceCharge implements TaxSettingsEvent { + const factory _SaveServiceCharge(final int serviceCharge) = + _$SaveServiceChargeImpl; + + int get serviceCharge; + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SaveServiceChargeImplCopyWith<_$SaveServiceChargeImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$UpdateSettingsImplCopyWith<$Res> { + factory _$$UpdateSettingsImplCopyWith(_$UpdateSettingsImpl value, + $Res Function(_$UpdateSettingsImpl) then) = + __$$UpdateSettingsImplCopyWithImpl<$Res>; + @useResult + $Res call({int taxValue, int serviceChargeValue}); +} + +/// @nodoc +class __$$UpdateSettingsImplCopyWithImpl<$Res> + extends _$TaxSettingsEventCopyWithImpl<$Res, _$UpdateSettingsImpl> + implements _$$UpdateSettingsImplCopyWith<$Res> { + __$$UpdateSettingsImplCopyWithImpl( + _$UpdateSettingsImpl _value, $Res Function(_$UpdateSettingsImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? taxValue = null, + Object? serviceChargeValue = null, + }) { + return _then(_$UpdateSettingsImpl( + taxValue: null == taxValue + ? _value.taxValue + : taxValue // ignore: cast_nullable_to_non_nullable + as int, + serviceChargeValue: null == serviceChargeValue + ? _value.serviceChargeValue + : serviceChargeValue // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$UpdateSettingsImpl implements _UpdateSettings { + const _$UpdateSettingsImpl( + {required this.taxValue, required this.serviceChargeValue}); + + @override + final int taxValue; + @override + final int serviceChargeValue; + + @override + String toString() { + return 'TaxSettingsEvent.updateSettings(taxValue: $taxValue, serviceChargeValue: $serviceChargeValue)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdateSettingsImpl && + (identical(other.taxValue, taxValue) || + other.taxValue == taxValue) && + (identical(other.serviceChargeValue, serviceChargeValue) || + other.serviceChargeValue == serviceChargeValue)); + } + + @override + int get hashCode => Object.hash(runtimeType, taxValue, serviceChargeValue); + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdateSettingsImplCopyWith<_$UpdateSettingsImpl> get copyWith => + __$$UpdateSettingsImplCopyWithImpl<_$UpdateSettingsImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loadSettings, + required TResult Function(TaxModel taxModel) saveTax, + required TResult Function(int serviceCharge) saveServiceCharge, + required TResult Function(int taxValue, int serviceChargeValue) + updateSettings, + }) { + return updateSettings(taxValue, serviceChargeValue); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loadSettings, + TResult? Function(TaxModel taxModel)? saveTax, + TResult? Function(int serviceCharge)? saveServiceCharge, + TResult? Function(int taxValue, int serviceChargeValue)? updateSettings, + }) { + return updateSettings?.call(taxValue, serviceChargeValue); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loadSettings, + TResult Function(TaxModel taxModel)? saveTax, + TResult Function(int serviceCharge)? saveServiceCharge, + TResult Function(int taxValue, int serviceChargeValue)? updateSettings, + required TResult orElse(), + }) { + if (updateSettings != null) { + return updateSettings(taxValue, serviceChargeValue); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_LoadSettings value) loadSettings, + required TResult Function(_SaveTax value) saveTax, + required TResult Function(_SaveServiceCharge value) saveServiceCharge, + required TResult Function(_UpdateSettings value) updateSettings, + }) { + return updateSettings(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_LoadSettings value)? loadSettings, + TResult? Function(_SaveTax value)? saveTax, + TResult? Function(_SaveServiceCharge value)? saveServiceCharge, + TResult? Function(_UpdateSettings value)? updateSettings, + }) { + return updateSettings?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_LoadSettings value)? loadSettings, + TResult Function(_SaveTax value)? saveTax, + TResult Function(_SaveServiceCharge value)? saveServiceCharge, + TResult Function(_UpdateSettings value)? updateSettings, + required TResult orElse(), + }) { + if (updateSettings != null) { + return updateSettings(this); + } + return orElse(); + } +} + +abstract class _UpdateSettings implements TaxSettingsEvent { + const factory _UpdateSettings( + {required final int taxValue, + required final int serviceChargeValue}) = _$UpdateSettingsImpl; + + int get taxValue; + int get serviceChargeValue; + + /// Create a copy of TaxSettingsEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdateSettingsImplCopyWith<_$UpdateSettingsImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$TaxSettingsState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(TaxModel taxModel, int serviceChargeValue) loaded, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $TaxSettingsStateCopyWith<$Res> { + factory $TaxSettingsStateCopyWith( + TaxSettingsState value, $Res Function(TaxSettingsState) then) = + _$TaxSettingsStateCopyWithImpl<$Res, TaxSettingsState>; +} + +/// @nodoc +class _$TaxSettingsStateCopyWithImpl<$Res, $Val extends TaxSettingsState> + implements $TaxSettingsStateCopyWith<$Res> { + _$TaxSettingsStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$TaxSettingsStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'TaxSettingsState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(TaxModel taxModel, int serviceChargeValue) loaded, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements TaxSettingsState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$TaxSettingsStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'TaxSettingsState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(TaxModel taxModel, int serviceChargeValue) loaded, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements TaxSettingsState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$LoadedImplCopyWith<$Res> { + factory _$$LoadedImplCopyWith( + _$LoadedImpl value, $Res Function(_$LoadedImpl) then) = + __$$LoadedImplCopyWithImpl<$Res>; + @useResult + $Res call({TaxModel taxModel, int serviceChargeValue}); +} + +/// @nodoc +class __$$LoadedImplCopyWithImpl<$Res> + extends _$TaxSettingsStateCopyWithImpl<$Res, _$LoadedImpl> + implements _$$LoadedImplCopyWith<$Res> { + __$$LoadedImplCopyWithImpl( + _$LoadedImpl _value, $Res Function(_$LoadedImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? taxModel = null, + Object? serviceChargeValue = null, + }) { + return _then(_$LoadedImpl( + taxModel: null == taxModel + ? _value.taxModel + : taxModel // ignore: cast_nullable_to_non_nullable + as TaxModel, + serviceChargeValue: null == serviceChargeValue + ? _value.serviceChargeValue + : serviceChargeValue // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$LoadedImpl implements _Loaded { + const _$LoadedImpl( + {required this.taxModel, required this.serviceChargeValue}); + + @override + final TaxModel taxModel; + @override + final int serviceChargeValue; + + @override + String toString() { + return 'TaxSettingsState.loaded(taxModel: $taxModel, serviceChargeValue: $serviceChargeValue)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$LoadedImpl && + (identical(other.taxModel, taxModel) || + other.taxModel == taxModel) && + (identical(other.serviceChargeValue, serviceChargeValue) || + other.serviceChargeValue == serviceChargeValue)); + } + + @override + int get hashCode => Object.hash(runtimeType, taxModel, serviceChargeValue); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + __$$LoadedImplCopyWithImpl<_$LoadedImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(TaxModel taxModel, int serviceChargeValue) loaded, + required TResult Function(String message) error, + }) { + return loaded(taxModel, serviceChargeValue); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult? Function(String message)? error, + }) { + return loaded?.call(taxModel, serviceChargeValue); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(taxModel, serviceChargeValue); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return loaded(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return loaded?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loaded != null) { + return loaded(this); + } + return orElse(); + } +} + +abstract class _Loaded implements TaxSettingsState { + const factory _Loaded( + {required final TaxModel taxModel, + required final int serviceChargeValue}) = _$LoadedImpl; + + TaxModel get taxModel; + int get serviceChargeValue; + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$LoadedImplCopyWith<_$LoadedImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$TaxSettingsStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'TaxSettingsState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(TaxModel taxModel, int serviceChargeValue) loaded, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(TaxModel taxModel, int serviceChargeValue)? loaded, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Loaded value) loaded, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Loaded value)? loaded, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Loaded value)? loaded, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements TaxSettingsState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of TaxSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/tax_settings/tax_settings_event.dart b/lib/presentation/setting/bloc/tax_settings/tax_settings_event.dart new file mode 100644 index 0000000..fe3ad47 --- /dev/null +++ b/lib/presentation/setting/bloc/tax_settings/tax_settings_event.dart @@ -0,0 +1,12 @@ +part of 'tax_settings_bloc.dart'; + +@freezed +class TaxSettingsEvent with _$TaxSettingsEvent { + const factory TaxSettingsEvent.loadSettings() = _LoadSettings; + const factory TaxSettingsEvent.saveTax(TaxModel taxModel) = _SaveTax; + const factory TaxSettingsEvent.saveServiceCharge(int serviceCharge) = _SaveServiceCharge; + const factory TaxSettingsEvent.updateSettings({ + required int taxValue, + required int serviceChargeValue, + }) = _UpdateSettings; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/tax_settings/tax_settings_state.dart b/lib/presentation/setting/bloc/tax_settings/tax_settings_state.dart new file mode 100644 index 0000000..63583f5 --- /dev/null +++ b/lib/presentation/setting/bloc/tax_settings/tax_settings_state.dart @@ -0,0 +1,12 @@ +part of 'tax_settings_bloc.dart'; + +@freezed +class TaxSettingsState with _$TaxSettingsState { + const factory TaxSettingsState.initial() = _Initial; + const factory TaxSettingsState.loading() = _Loading; + const factory TaxSettingsState.loaded({ + required TaxModel taxModel, + required int serviceChargeValue, + }) = _Loaded; + const factory TaxSettingsState.error(String message) = _Error; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/update_printer/update_printer_bloc.dart b/lib/presentation/setting/bloc/update_printer/update_printer_bloc.dart new file mode 100644 index 0000000..214d4cd --- /dev/null +++ b/lib/presentation/setting/bloc/update_printer/update_printer_bloc.dart @@ -0,0 +1,21 @@ +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'update_printer_event.dart'; +part 'update_printer_state.dart'; +part 'update_printer_bloc.freezed.dart'; + +class UpdatePrinterBloc extends Bloc { + UpdatePrinterBloc() : super(_Initial()) { + on<_UpdatePrinter>((event, emit) async { + emit(_Loading()); + await ProductLocalDatasource.instance.updatePrinter( + event.print, + event.print.id!, + ); + emit(_Success('Update Table Success')); + }); + } +} diff --git a/lib/presentation/setting/bloc/update_printer/update_printer_bloc.freezed.dart b/lib/presentation/setting/bloc/update_printer/update_printer_bloc.freezed.dart new file mode 100644 index 0000000..ba2d7d5 --- /dev/null +++ b/lib/presentation/setting/bloc/update_printer/update_printer_bloc.freezed.dart @@ -0,0 +1,760 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'update_printer_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$UpdatePrinterEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) updatePrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? updatePrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? updatePrinter, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdatePrinter value) updatePrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdatePrinter value)? updatePrinter, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdatePrinter value)? updatePrinter, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdatePrinterEventCopyWith<$Res> { + factory $UpdatePrinterEventCopyWith( + UpdatePrinterEvent value, $Res Function(UpdatePrinterEvent) then) = + _$UpdatePrinterEventCopyWithImpl<$Res, UpdatePrinterEvent>; +} + +/// @nodoc +class _$UpdatePrinterEventCopyWithImpl<$Res, $Val extends UpdatePrinterEvent> + implements $UpdatePrinterEventCopyWith<$Res> { + _$UpdatePrinterEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdatePrinterEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$UpdatePrinterEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdatePrinterEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'UpdatePrinterEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) updatePrinter, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? updatePrinter, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? updatePrinter, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdatePrinter value) updatePrinter, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdatePrinter value)? updatePrinter, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdatePrinter value)? updatePrinter, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements UpdatePrinterEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$UpdatePrinterImplCopyWith<$Res> { + factory _$$UpdatePrinterImplCopyWith( + _$UpdatePrinterImpl value, $Res Function(_$UpdatePrinterImpl) then) = + __$$UpdatePrinterImplCopyWithImpl<$Res>; + @useResult + $Res call({PrintModel print}); +} + +/// @nodoc +class __$$UpdatePrinterImplCopyWithImpl<$Res> + extends _$UpdatePrinterEventCopyWithImpl<$Res, _$UpdatePrinterImpl> + implements _$$UpdatePrinterImplCopyWith<$Res> { + __$$UpdatePrinterImplCopyWithImpl( + _$UpdatePrinterImpl _value, $Res Function(_$UpdatePrinterImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? print = null, + }) { + return _then(_$UpdatePrinterImpl( + null == print + ? _value.print + : print // ignore: cast_nullable_to_non_nullable + as PrintModel, + )); + } +} + +/// @nodoc + +class _$UpdatePrinterImpl implements _UpdatePrinter { + const _$UpdatePrinterImpl(this.print); + + @override + final PrintModel print; + + @override + String toString() { + return 'UpdatePrinterEvent.updatePrinter(print: $print)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdatePrinterImpl && + (identical(other.print, print) || other.print == print)); + } + + @override + int get hashCode => Object.hash(runtimeType, print); + + /// Create a copy of UpdatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdatePrinterImplCopyWith<_$UpdatePrinterImpl> get copyWith => + __$$UpdatePrinterImplCopyWithImpl<_$UpdatePrinterImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(PrintModel print) updatePrinter, + }) { + return updatePrinter(print); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(PrintModel print)? updatePrinter, + }) { + return updatePrinter?.call(print); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(PrintModel print)? updatePrinter, + required TResult orElse(), + }) { + if (updatePrinter != null) { + return updatePrinter(print); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdatePrinter value) updatePrinter, + }) { + return updatePrinter(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdatePrinter value)? updatePrinter, + }) { + return updatePrinter?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdatePrinter value)? updatePrinter, + required TResult orElse(), + }) { + if (updatePrinter != null) { + return updatePrinter(this); + } + return orElse(); + } +} + +abstract class _UpdatePrinter implements UpdatePrinterEvent { + const factory _UpdatePrinter(final PrintModel print) = _$UpdatePrinterImpl; + + PrintModel get print; + + /// Create a copy of UpdatePrinterEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdatePrinterImplCopyWith<_$UpdatePrinterImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$UpdatePrinterState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdatePrinterStateCopyWith<$Res> { + factory $UpdatePrinterStateCopyWith( + UpdatePrinterState value, $Res Function(UpdatePrinterState) then) = + _$UpdatePrinterStateCopyWithImpl<$Res, UpdatePrinterState>; +} + +/// @nodoc +class _$UpdatePrinterStateCopyWithImpl<$Res, $Val extends UpdatePrinterState> + implements $UpdatePrinterStateCopyWith<$Res> { + _$UpdatePrinterStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$UpdatePrinterStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'UpdatePrinterState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements UpdatePrinterState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$UpdatePrinterStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'UpdatePrinterState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements UpdatePrinterState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$UpdatePrinterStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'UpdatePrinterState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements UpdatePrinterState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of UpdatePrinterState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/update_printer/update_printer_event.dart b/lib/presentation/setting/bloc/update_printer/update_printer_event.dart new file mode 100644 index 0000000..bb9f616 --- /dev/null +++ b/lib/presentation/setting/bloc/update_printer/update_printer_event.dart @@ -0,0 +1,8 @@ +part of 'update_printer_bloc.dart'; + +@freezed +class UpdatePrinterEvent with _$UpdatePrinterEvent { + const factory UpdatePrinterEvent.started() = _Started; + const factory UpdatePrinterEvent.updatePrinter(PrintModel print) = + _UpdatePrinter; +} diff --git a/lib/presentation/setting/bloc/update_printer/update_printer_state.dart b/lib/presentation/setting/bloc/update_printer/update_printer_state.dart new file mode 100644 index 0000000..64cffff --- /dev/null +++ b/lib/presentation/setting/bloc/update_printer/update_printer_state.dart @@ -0,0 +1,8 @@ +part of 'update_printer_bloc.dart'; + +@freezed +class UpdatePrinterState with _$UpdatePrinterState { + const factory UpdatePrinterState.initial() = _Initial; + const factory UpdatePrinterState.loading() = _Loading; + const factory UpdatePrinterState.success(String message) = _Success; +} diff --git a/lib/presentation/setting/bloc/update_product/update_product_bloc.dart b/lib/presentation/setting/bloc/update_product/update_product_bloc.dart new file mode 100644 index 0000000..ace0614 --- /dev/null +++ b/lib/presentation/setting/bloc/update_product/update_product_bloc.dart @@ -0,0 +1,86 @@ +import 'dart:developer'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/data/models/request/product_request_model.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:image_picker/image_picker.dart'; + +part 'update_product_event.dart'; +part 'update_product_state.dart'; +part 'update_product_bloc.freezed.dart'; + +class UpdateProductBloc extends Bloc { + final ProductRemoteDatasource datasource; + UpdateProductBloc( + this.datasource, + ) : super(const _Initial()) { + on<_UpdateProduct>((event, emit) async { + emit(const _Loading()); + + try { + // Validate required fields + if (event.product.name == null || event.product.name!.isEmpty) { + emit(_Error('Product name is required')); + return; + } + + if (event.product.price == null || event.product.price!.isEmpty) { + emit(_Error('Product price is required')); + return; + } + + if (event.product.stock == null) { + emit(_Error('Product stock is required')); + return; + } + + if (event.product.categoryId == null) { + emit(_Error('Product category is required')); + return; + } + + // Parse price safely + final price = int.tryParse(event.product.price!); + if (price == null) { + emit(_Error('Invalid price format')); + return; + } + + final requestData = ProductRequestModel( + id: event.product.id, + name: event.product.name!, + price: price, + stock: event.product.stock!, + categoryId: event.product.categoryId!, + isBestSeller: event.product.isFavorite ?? 0, // Default to 0 if null + image: event.image, + printerType: event.product.printerType ?? 'kitchen', // Default to kitchen if null + ); + + log("Update requestData: ${requestData.toString()}"); + log("Request map: ${requestData.toMap()}"); + + final response = await datasource.updateProduct(requestData); + response.fold( + (l) => emit(_Error(l)), + (r) async { + // Update local database after successful API update + try { + await ProductLocalDatasource.instance.updateProduct(event.product); + log("Local product updated successfully"); + } catch (e) { + log("Error updating local product: $e"); + } + emit(_Success('Update Product Success')); + }, + ); + } catch (e) { + log("Error in UpdateProductBloc: $e"); + emit(_Error('An error occurred: $e')); + } + }); + } +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/update_product/update_product_bloc.freezed.dart b/lib/presentation/setting/bloc/update_product/update_product_bloc.freezed.dart new file mode 100644 index 0000000..ad1c03a --- /dev/null +++ b/lib/presentation/setting/bloc/update_product/update_product_bloc.freezed.dart @@ -0,0 +1,861 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'update_product_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$UpdateProductEvent { + Product get product => throw _privateConstructorUsedError; + XFile? get image => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function(Product product, XFile? image) updateProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(Product product, XFile? image)? updateProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(Product product, XFile? image)? updateProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_UpdateProduct value) updateProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_UpdateProduct value)? updateProduct, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_UpdateProduct value)? updateProduct, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + /// Create a copy of UpdateProductEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $UpdateProductEventCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdateProductEventCopyWith<$Res> { + factory $UpdateProductEventCopyWith( + UpdateProductEvent value, $Res Function(UpdateProductEvent) then) = + _$UpdateProductEventCopyWithImpl<$Res, UpdateProductEvent>; + @useResult + $Res call({Product product, XFile? image}); +} + +/// @nodoc +class _$UpdateProductEventCopyWithImpl<$Res, $Val extends UpdateProductEvent> + implements $UpdateProductEventCopyWith<$Res> { + _$UpdateProductEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdateProductEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + Object? image = freezed, + }) { + return _then(_value.copyWith( + product: null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + image: freezed == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as XFile?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$UpdateProductImplCopyWith<$Res> + implements $UpdateProductEventCopyWith<$Res> { + factory _$$UpdateProductImplCopyWith( + _$UpdateProductImpl value, $Res Function(_$UpdateProductImpl) then) = + __$$UpdateProductImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({Product product, XFile? image}); +} + +/// @nodoc +class __$$UpdateProductImplCopyWithImpl<$Res> + extends _$UpdateProductEventCopyWithImpl<$Res, _$UpdateProductImpl> + implements _$$UpdateProductImplCopyWith<$Res> { + __$$UpdateProductImplCopyWithImpl( + _$UpdateProductImpl _value, $Res Function(_$UpdateProductImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateProductEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? product = null, + Object? image = freezed, + }) { + return _then(_$UpdateProductImpl( + null == product + ? _value.product + : product // ignore: cast_nullable_to_non_nullable + as Product, + freezed == image + ? _value.image + : image // ignore: cast_nullable_to_non_nullable + as XFile?, + )); + } +} + +/// @nodoc + +class _$UpdateProductImpl implements _UpdateProduct { + const _$UpdateProductImpl(this.product, this.image); + + @override + final Product product; + @override + final XFile? image; + + @override + String toString() { + return 'UpdateProductEvent.updateProduct(product: $product, image: $image)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdateProductImpl && + (identical(other.product, product) || other.product == product) && + (identical(other.image, image) || other.image == image)); + } + + @override + int get hashCode => Object.hash(runtimeType, product, image); + + /// Create a copy of UpdateProductEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdateProductImplCopyWith<_$UpdateProductImpl> get copyWith => + __$$UpdateProductImplCopyWithImpl<_$UpdateProductImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(Product product, XFile? image) updateProduct, + }) { + return updateProduct(product, image); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(Product product, XFile? image)? updateProduct, + }) { + return updateProduct?.call(product, image); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(Product product, XFile? image)? updateProduct, + required TResult orElse(), + }) { + if (updateProduct != null) { + return updateProduct(product, image); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_UpdateProduct value) updateProduct, + }) { + return updateProduct(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_UpdateProduct value)? updateProduct, + }) { + return updateProduct?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_UpdateProduct value)? updateProduct, + required TResult orElse(), + }) { + if (updateProduct != null) { + return updateProduct(this); + } + return orElse(); + } +} + +abstract class _UpdateProduct implements UpdateProductEvent { + const factory _UpdateProduct(final Product product, final XFile? image) = + _$UpdateProductImpl; + + @override + Product get product; + @override + XFile? get image; + + /// Create a copy of UpdateProductEvent + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdateProductImplCopyWith<_$UpdateProductImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$UpdateProductState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdateProductStateCopyWith<$Res> { + factory $UpdateProductStateCopyWith( + UpdateProductState value, $Res Function(UpdateProductState) then) = + _$UpdateProductStateCopyWithImpl<$Res, UpdateProductState>; +} + +/// @nodoc +class _$UpdateProductStateCopyWithImpl<$Res, $Val extends UpdateProductState> + implements $UpdateProductStateCopyWith<$Res> { + _$UpdateProductStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$UpdateProductStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'UpdateProductState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements UpdateProductState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$UpdateProductStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'UpdateProductState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements UpdateProductState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$UpdateProductStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'UpdateProductState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements UpdateProductState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ErrorImplCopyWith<$Res> { + factory _$$ErrorImplCopyWith( + _$ErrorImpl value, $Res Function(_$ErrorImpl) then) = + __$$ErrorImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$ErrorImplCopyWithImpl<$Res> + extends _$UpdateProductStateCopyWithImpl<$Res, _$ErrorImpl> + implements _$$ErrorImplCopyWith<$Res> { + __$$ErrorImplCopyWithImpl( + _$ErrorImpl _value, $Res Function(_$ErrorImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$ErrorImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$ErrorImpl implements _Error { + const _$ErrorImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'UpdateProductState.error(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ErrorImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + __$$ErrorImplCopyWithImpl<_$ErrorImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + required TResult Function(String message) error, + }) { + return error(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + TResult? Function(String message)? error, + }) { + return error?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + TResult Function(String message)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + required TResult Function(_Error value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + TResult? Function(_Error value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + TResult Function(_Error value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class _Error implements UpdateProductState { + const factory _Error(final String message) = _$ErrorImpl; + + String get message; + + /// Create a copy of UpdateProductState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ErrorImplCopyWith<_$ErrorImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/setting/bloc/update_product/update_product_event.dart b/lib/presentation/setting/bloc/update_product/update_product_event.dart new file mode 100644 index 0000000..5fa93b6 --- /dev/null +++ b/lib/presentation/setting/bloc/update_product/update_product_event.dart @@ -0,0 +1,6 @@ +part of 'update_product_bloc.dart'; + +@freezed +class UpdateProductEvent with _$UpdateProductEvent { + const factory UpdateProductEvent.updateProduct(Product product, XFile? image) = _UpdateProduct; +} \ No newline at end of file diff --git a/lib/presentation/setting/bloc/update_product/update_product_state.dart b/lib/presentation/setting/bloc/update_product/update_product_state.dart new file mode 100644 index 0000000..7906faa --- /dev/null +++ b/lib/presentation/setting/bloc/update_product/update_product_state.dart @@ -0,0 +1,9 @@ +part of 'update_product_bloc.dart'; + +@freezed +class UpdateProductState with _$UpdateProductState { + const factory UpdateProductState.initial() = _Initial; + const factory UpdateProductState.loading() = _Loading; + const factory UpdateProductState.success(String message) = _Success; + const factory UpdateProductState.error(String message) = _Error; +} \ No newline at end of file diff --git a/lib/presentation/setting/dialogs/form_discount_dialog.dart b/lib/presentation/setting/dialogs/form_discount_dialog.dart new file mode 100644 index 0000000..78fa5d8 --- /dev/null +++ b/lib/presentation/setting/dialogs/form_discount_dialog.dart @@ -0,0 +1,121 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/custom_text_field.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/add_discount/add_discount_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/discount/discount_bloc.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../models/discount_model.dart'; + +class FormDiscountDialog extends StatefulWidget { + final DiscountModel? data; + const FormDiscountDialog({super.key, this.data}); + + @override + State createState() => _FormDiscountDialogState(); +} + +class _FormDiscountDialogState extends State { + final nameController = TextEditingController(); + final descriptionController = TextEditingController(); + final discountController = TextEditingController(); + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + onPressed: () => context.pop(), + icon: const Icon(Icons.close), + ), + const Text('Tambah Diskon'), + const Spacer(), + ], + ), + content: SingleChildScrollView( + child: SizedBox( + width: context.deviceWidth / 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CustomTextField( + controller: nameController, + label: 'Nama Diskon', + onChanged: (value) {}, + ), + const SpaceHeight(24.0), + CustomTextField( + controller: descriptionController, + label: 'Deskripsi (Opsional)', + onChanged: (value) {}, + ), + const SpaceHeight(24.0), + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Flexible( + child: CustomTextField( + controller: TextEditingController(text: 'Presentase'), + label: 'Nilai', + suffixIcon: const Icon(Icons.chevron_right), + onChanged: (value) {}, + readOnly: true, + ), + ), + const SpaceWidth(14.0), + Flexible( + child: CustomTextField( + showLabel: false, + controller: discountController, + label: 'Percent', + prefixIcon: const Icon(Icons.percent), + onChanged: (value) {}, + keyboardType: TextInputType.number, + ), + ), + ], + ), + const SpaceHeight(24.0), + BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: () { + context + .read() + .add(const DiscountEvent.getDiscounts()); + context.pop(); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen(orElse: () { + return Button.filled( + onPressed: () { + context.read().add( + AddDiscountEvent.addDiscount( + name: nameController.text, + description: descriptionController.text, + value: int.parse(discountController.text), + ), + ); + }, + label: 'Simpan Diskon', + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }); + }, + ) + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/setting/dialogs/form_printer_dialog.dart b/lib/presentation/setting/dialogs/form_printer_dialog.dart new file mode 100644 index 0000000..a2f429e --- /dev/null +++ b/lib/presentation/setting/dialogs/form_printer_dialog.dart @@ -0,0 +1,149 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + + +import '../../../core/components/buttons.dart'; +import '../../../core/components/custom_dropdown.dart'; +import '../../../core/components/custom_text_field.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../models/printer_model.dart'; + +class FormPrinterDialog extends StatelessWidget { + final PrinterModel? data; + const FormPrinterDialog({super.key, this.data}); + + @override + Widget build(BuildContext context) { + final nameController = TextEditingController(text: data?.name ?? ''); + final ipAddressController = + TextEditingController(text: data?.ipAddress ?? ''); + final sizeController = ValueNotifier(data?.size ?? '58mm'); + final typeController = + ValueNotifier(data?.type ?? PrinterType.wifi); + final isCutReceipt = ValueNotifier(false); + final isOpenLychee = ValueNotifier(false); + return AlertDialog( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + onPressed: () => context.pop(), + icon: const Icon(Icons.close), + ), + Text(data == null ? 'Tambah Printer' : 'Edit Printer'), + const Spacer(), + ], + ), + content: SingleChildScrollView( + child: SizedBox( + width: context.deviceWidth / 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CustomTextField( + controller: nameController, + label: 'Nama Printer', + onChanged: (value) {}, + ), + const SpaceHeight(24.0), + CustomTextField( + controller: ipAddressController, + label: 'Alamat IP', + onChanged: (value) {}, + ), + const SpaceHeight(24.0), + ValueListenableBuilder( + valueListenable: sizeController, + builder: (context, value, child) => CustomDropdown( + value: value, + items: const ['58mm', '80mm'], + label: 'Ukuruan Struk', + onChanged: (value) => sizeController.value = value ?? '', + ), + ), + const SpaceHeight(24.0), + ValueListenableBuilder( + valueListenable: typeController, + builder: (context, value, child) => CustomDropdown( + value: value.value, + items: [ + PrinterType.wifi.value, + PrinterType.bluetooth.value, + ], + label: 'Type', + onChanged: (value) => + typeController.value = PrinterType.fromValue(value ?? ''), + ), + ), + const SpaceHeight(24.0), + ValueListenableBuilder( + valueListenable: isCutReceipt, + builder: (context, value, child) => GestureDetector( + onTap: () => isCutReceipt.value = !value, + child: ListTile( + contentPadding: EdgeInsets.zero, + title: const Text( + 'Potong struk setelah selesai cetak', + style: TextStyle( + fontSize: 12.0, + fontWeight: FontWeight.bold, + ), + ), + subtitle: const Text( + 'hanya aktifkan jika printer kamu support', + style: TextStyle(fontSize: 12.0), + ), + trailing: Checkbox( + value: value, + onChanged: (_) => isCutReceipt.value = !value, + ), + textColor: AppColors.primary, + ), + ), + ), + const SpaceHeight(24.0), + ValueListenableBuilder( + valueListenable: isOpenLychee, + builder: (context, value, child) => GestureDetector( + onTap: () => isOpenLychee.value = !value, + child: ListTile( + contentPadding: EdgeInsets.zero, + title: const Text( + 'Buka laci setelah selesai cetak', + style: TextStyle( + fontSize: 12.0, + fontWeight: FontWeight.bold, + ), + ), + subtitle: const Text( + 'hanya aktifkan jika printer kamu support', + style: TextStyle(fontSize: 12.0), + ), + trailing: Checkbox( + value: value, + onChanged: (_) => isOpenLychee.value = !value, + ), + textColor: AppColors.primary, + ), + ), + ), + const SpaceHeight(24.0), + Button.filled( + onPressed: () { + if (data == null) { + // TODO: do add printer + } else { + // TODO: do edit printer + } + context.pop(); + }, + label: data == null ? 'Simpan' : 'Perbarui', + ) + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/setting/dialogs/form_product_dialog.dart b/lib/presentation/setting/dialogs/form_product_dialog.dart new file mode 100644 index 0000000..2c4a3f3 --- /dev/null +++ b/lib/presentation/setting/dialogs/form_product_dialog.dart @@ -0,0 +1,409 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/custom_text_field.dart'; +import 'package:enaklo_pos/core/components/image_picker_widget.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/models/response/category_response_model.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/add_product/add_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_categories/get_categories_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_products/get_products_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_product/update_product_bloc.dart'; +import 'package:image_picker/image_picker.dart'; +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; + +class FormProductDialog extends StatefulWidget { + final Product? product; + const FormProductDialog({ + super.key, + this.product, + }); + + @override + State createState() => _FormProductDialogState(); +} + +class _FormProductDialogState extends State { + TextEditingController? nameController; + TextEditingController? priceController; + TextEditingController? stockController; + + XFile? imageFile; + + bool isBestSeller = false; + int priceValue = 0; + + CategoryModel? selectCategory; + String? imageUrl; + String? printType = 'kitchen'; + bool isEditMode = false; + + @override + void initState() { + context.read().add(const GetCategoriesEvent.fetch()); + nameController = TextEditingController(); + priceController = TextEditingController(); + stockController = TextEditingController(); + + // Check if we're in edit mode + isEditMode = widget.product != null; + + if (isEditMode) { + // Pre-fill the form with existing product data + final product = widget.product!; + nameController!.text = product.name ?? ''; + priceValue = int.tryParse(product.price ?? '0') ?? 0; + priceController!.text = priceValue.currencyFormatRp; + stockController!.text = (product.stock ?? 0).toString(); + isBestSeller = product.isFavorite == 1; + printType = product.printerType ?? 'kitchen'; + imageUrl = product.image; + } + + super.initState(); + } + + @override + void dispose() { + super.dispose(); + nameController!.dispose(); + priceController!.dispose(); + stockController!.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + onPressed: () => context.pop(), + icon: const Icon(Icons.close), + ), + Text( + isEditMode ? 'Edit Product' : 'Add Product', + style: TextStyle(fontWeight: FontWeight.bold), + ), + const Spacer(), + ], + ), + content: SingleChildScrollView( + child: SizedBox( + width: context.deviceWidth / 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CustomTextField( + controller: nameController!, + label: 'Product Name', + keyboardType: TextInputType.text, + textInputAction: TextInputAction.next, + textCapitalization: TextCapitalization.words, + ), + const SpaceHeight(20.0), + CustomTextField( + controller: priceController!, + label: 'Price', + keyboardType: TextInputType.number, + textInputAction: TextInputAction.next, + onChanged: (value) { + priceValue = value.toIntegerFromText; + final int newValue = value.toIntegerFromText; + priceController!.text = newValue.currencyFormatRp; + priceController!.selection = TextSelection.fromPosition( + TextPosition(offset: priceController!.text.length)); + }, + ), + const SpaceHeight(20.0), + ImagePickerWidget( + label: 'Photo Product', + onChanged: (file) { + if (file == null) { + return; + } + imageFile = file; + }, + initialImageUrl: imageUrl, + ), + const SpaceHeight(20.0), + CustomTextField( + controller: stockController!, + label: 'Stock', + keyboardType: TextInputType.number, + ), + const SpaceHeight(20.0), + const Text( + "Category", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + success: (categories) { + // Set the selected category if in edit mode and not already set + if (isEditMode && selectCategory == null && widget.product?.category != null) { + try { + selectCategory = categories.firstWhere( + (cat) => cat.id == widget.product!.category!.id, + ); + } catch (e) { + // If no exact match found, leave selectCategory as null + // This will show the hint text instead + log("No matching category found for product category ID: ${widget.product!.category!.id}"); + } + } + + return DropdownButtonHideUnderline( + child: Container( + decoration: BoxDecoration( + border: Border.all(color: Colors.grey), + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 5), + child: DropdownButton( + value: selectCategory, + hint: const Text("Select Category"), + isExpanded: true, // Untuk mengisi lebar container + onChanged: (newValue) { + if (newValue != null) { + selectCategory = newValue; + setState(() {}); + log("selectCategory: ${selectCategory!.name}"); + } + }, + items: categories + .map>( + (CategoryModel category) { + return DropdownMenuItem( + value: category, + child: Text(category.name!), + ); + }).toList(), + ), + ), + ); + }, + ); + }, + ), + const SpaceHeight(12.0), + const Text( + "Print Type", + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + //radio printer type + const SpaceHeight(12.0), + Row( + children: [ + Radio( + value: 'kitchen', + groupValue: printType, + onChanged: (value) { + setState(() { + printType = value; + }); + }, + ), + const Text('Kitchen'), + ], + ), + Row( + children: [ + Radio( + value: 'bar', + groupValue: printType, + onChanged: (value) { + setState(() { + printType = value; + }); + }, + ), + const Text('Bar'), + ], + ), + const SpaceHeight(20.0), + Row( + children: [ + Checkbox( + value: isBestSeller, + onChanged: (value) { + setState(() { + isBestSeller = value!; + }); + }, + ), + const Text('Favorite Product'), + ], + ), + const SpaceHeight(20.0), + const SpaceHeight(24.0), + if (isEditMode) + BlocConsumer( + listener: (context, state) { + state.maybeMap( + orElse: () {}, + success: (_) { + context + .read() + .add(const SyncProductEvent.syncProduct()); + context + .read() + .add(const GetProductsEvent.fetch()); + context.pop(true); + + const snackBar = SnackBar( + content: Text('Success Update Product'), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context).showSnackBar( + snackBar, + ); + }, + error: (message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Error: $message'), + backgroundColor: Colors.red, + ), + ); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + if (selectCategory == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please select a category'), + backgroundColor: Colors.red, + ), + ); + return; + } + + log("isBestSeller: $isBestSeller"); + final String name = nameController!.text; + final int stock = stockController!.text.toIntegerFromText; + + final Product product = widget.product!.copyWith( + name: name, + price: priceValue.toString(), + stock: stock, + categoryId: selectCategory!.id!, + isFavorite: isBestSeller ? 1 : 0, + printerType: printType, + ); + + context.read().add( + UpdateProductEvent.updateProduct(product, imageFile)); + }, + label: 'Update Product', + ); + }, + loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + ); + }, + ) + else + BlocConsumer( + listener: (context, state) { + state.maybeMap( + orElse: () {}, + success: (_) { + context + .read() + .add(const SyncProductEvent.syncProduct()); + context + .read() + .add(const GetProductsEvent.fetch()); + context.pop(true); + + const snackBar = SnackBar( + content: Text('Success Add Product'), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context).showSnackBar( + snackBar, + ); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + if (selectCategory == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please select a category'), + backgroundColor: Colors.red, + ), + ); + return; + } + + log("isBestSeller: $isBestSeller"); + final String name = nameController!.text; + + final int stock = + stockController!.text.toIntegerFromText; + final Product product = Product( + name: name, + price: priceValue.toString(), + stock: stock, + categoryId: selectCategory!.id!, + isFavorite: isBestSeller ? 1 : 0, + image: imageFile!.path, + printerType: printType, + ); + context.read().add( + AddProductEvent.addProduct(product, imageFile!)); + }, + label: 'Save Product', + ); + }, + loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + ); + }, + ), + const SpaceHeight(16.0), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/setting/dialogs/form_tax_dialog.dart b/lib/presentation/setting/dialogs/form_tax_dialog.dart new file mode 100644 index 0000000..4297648 --- /dev/null +++ b/lib/presentation/setting/dialogs/form_tax_dialog.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/custom_text_field.dart'; +import '../../../core/components/spaces.dart'; + +class FormTaxDialog extends StatefulWidget { + final int taxValue; + final int serviceChargeValue; + final Function(int taxValue, int serviceChargeValue)? onSave; + + const FormTaxDialog({ + super.key, + required this.taxValue, + required this.serviceChargeValue, + this.onSave, + }); + + @override + State createState() => _FormTaxDialogState(); +} + +class _FormTaxDialogState extends State { + late final TextEditingController serviceFeeController; + late final TextEditingController taxFeeController; + + @override + void initState() { + super.initState(); + serviceFeeController = TextEditingController(text: widget.serviceChargeValue.toString()); + taxFeeController = TextEditingController(text: widget.taxValue.toString()); + } + + @override + void dispose() { + serviceFeeController.dispose(); + taxFeeController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + onPressed: () => context.pop(), + icon: const Icon(Icons.close), + ), + const Text('Edit Perhitungan Biaya'), + const Spacer(), + ], + ), + content: SingleChildScrollView( + child: SizedBox( + width: context.deviceWidth / 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CustomTextField( + controller: serviceFeeController, + label: 'Biaya Layanan (%)', + onChanged: (value) {}, + keyboardType: TextInputType.number, + suffixIcon: const Icon(Icons.percent), + ), + const SpaceHeight(24.0), + CustomTextField( + controller: taxFeeController, + label: 'Pajak PB1 (%)', + onChanged: (value) {}, + keyboardType: TextInputType.number, + suffixIcon: const Icon(Icons.percent), + ), + const SpaceHeight(24.0), + Button.filled( + onPressed: () { + final taxValue = int.tryParse(taxFeeController.text) ?? 0; + final serviceChargeValue = int.tryParse(serviceFeeController.text) ?? 0; + + if (widget.onSave != null) { + widget.onSave!(taxValue, serviceChargeValue); + } + + context.pop(); + }, + label: 'Simpan', + ) + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/setting/models/discount_model.dart b/lib/presentation/setting/models/discount_model.dart new file mode 100644 index 0000000..c726376 --- /dev/null +++ b/lib/presentation/setting/models/discount_model.dart @@ -0,0 +1,17 @@ +import '../../home/models/product_category.dart'; + +class DiscountModel { + final String name; + final String code; + final int discount; + final ProductCategory category; + final String? description; + + DiscountModel({ + required this.name, + required this.code, + required this.discount, + required this.category, + required this.description, + }); +} diff --git a/lib/presentation/setting/models/printer_model.dart b/lib/presentation/setting/models/printer_model.dart new file mode 100644 index 0000000..209a5ab --- /dev/null +++ b/lib/presentation/setting/models/printer_model.dart @@ -0,0 +1,31 @@ +enum PrinterType { + wifi('Wifi'), + bluetooth('Bluetooth'); + + final String value; + const PrinterType(this.value); + + bool get isWifi => this == PrinterType.wifi; + bool get isBluetooth => this == PrinterType.bluetooth; + + factory PrinterType.fromValue(String value) { + return values.firstWhere( + (element) => element.value == value, + orElse: () => PrinterType.wifi, + ); + } +} + +class PrinterModel { + final String name; + final String ipAddress; + final String size; + final PrinterType type; + + PrinterModel({ + required this.name, + required this.ipAddress, + required this.size, + required this.type, + }); +} diff --git a/lib/presentation/setting/models/tax_model.dart b/lib/presentation/setting/models/tax_model.dart new file mode 100644 index 0000000..d4a4f7b --- /dev/null +++ b/lib/presentation/setting/models/tax_model.dart @@ -0,0 +1,44 @@ +import 'dart:convert'; + +enum TaxType { + layanan, + pajak; + + bool get isLayanan => this == TaxType.layanan; + bool get isPajak => this == TaxType.pajak; +} + +class TaxModel { + final String name; + final TaxType type; + final int value; + + TaxModel({ + required this.name, + required this.type, + required this.value, + }); + + Map toMap() { + return { + 'name': name, + 'type': type.name, + 'value': value, + }; + } + + factory TaxModel.fromMap(Map map) { + return TaxModel( + name: map['name'] ?? '', + type: TaxType.values.firstWhere( + (e) => e.name == map['type'], + orElse: () => TaxType.layanan, + ), + value: map['value']?.toInt() ?? 0, + ); + } + + String toJson() => json.encode(toMap()); + + factory TaxModel.fromJson(String source) => TaxModel.fromMap(json.decode(source)); +} diff --git a/lib/presentation/setting/pages/discount_page.dart b/lib/presentation/setting/pages/discount_page.dart new file mode 100644 index 0000000..09086a5 --- /dev/null +++ b/lib/presentation/setting/pages/discount_page.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/discount/discount_bloc.dart'; + +import '../../home/widgets/custom_tab_bar.dart'; +import '../dialogs/form_discount_dialog.dart'; +import '../models/discount_model.dart'; +import '../widgets/add_data.dart'; +import '../widgets/manage_discount_card.dart'; +import '../widgets/settings_title.dart'; + +class DiscountPage extends StatefulWidget { + const DiscountPage({super.key}); + + @override + State createState() => _DiscountPageState(); +} + +class _DiscountPageState extends State { + // final List discounts = [ + // DiscountModel( + // name: '20', + // code: 'BUKAPUASA', + // description: null, + // discount: 50, + // category: ProductCategory.food, + // ), + // ]; + + void onEditTap(DiscountModel item) { + showDialog( + context: context, + builder: (context) => FormDiscountDialog(data: item), + ); + } + + void onAddDataTap() { + showDialog( + context: context, + builder: (context) => const FormDiscountDialog(), + ); + } + + @override + void initState() { + context.read().add(const DiscountEvent.getDiscounts()); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + const SettingsTitle('Kelola Diskon'), + const SizedBox(height: 24), + CustomTabBar( + tabTitles: const ['Semua'], + initialTabIndex: 0, + tabViews: [ + // SEMUA TAB + SizedBox( + child: BlocBuilder( + builder: (context, state) { + return state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, loaded: (discounts) { + return GridView.builder( + shrinkWrap: true, + itemCount: discounts.length + 1, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + if (index == 0) { + return AddData( + title: 'Tambah Diskon Baru', + onPressed: onAddDataTap, + ); + } + final item = discounts[index - 1]; + return ManageDiscountCard( + data: item, + onEditTap: (){}, + ); + }, + ); + }); + // return GridView.builder( + // shrinkWrap: true, + // itemCount: discounts.length + 1, + // physics: const NeverScrollableScrollPhysics(), + // gridDelegate: + // const SliverGridDelegateWithFixedCrossAxisCount( + // childAspectRatio: 0.85, + // crossAxisCount: 3, + // crossAxisSpacing: 30.0, + // mainAxisSpacing: 30.0, + // ), + // itemBuilder: (context, index) { + // if (index == 0) { + // return AddData( + // title: 'Tambah Diskon Baru', + // onPressed: onAddDataTap, + // ); + // } + // final item = discounts[index - 1]; + // return ManageDiscountCard( + // data: item, + // onEditTap: () => onEditTap(item), + // ); + // }, + // ); + }, + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/pages/manage_printer_page.dart b/lib/presentation/setting/pages/manage_printer_page.dart new file mode 100644 index 0000000..3172b29 --- /dev/null +++ b/lib/presentation/setting/pages/manage_printer_page.dart @@ -0,0 +1,431 @@ +import 'package:esc_pos_utils_plus/esc_pos_utils_plus.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; + +import '../../../core/constants/colors.dart'; +import '../widgets/menu_printer_button.dart'; +import '../widgets/menu_printer_content.dart'; + +class ManagePrinterPage extends StatefulWidget { + const ManagePrinterPage({super.key}); + + @override + State createState() => _ManagePrinterPageState(); +} + +class _ManagePrinterPageState extends State { + int selectedIndex = 0; + int? selectedSize; + // final List datas = [ + // PrinterModel( + // name: 'Galaxy A30', + // address: 12324567412, + // ), + // PrinterModel( + // name: 'Galaxy A30', + // address: 12324567412, + // ), + // PrinterModel( + // name: 'Galaxy A30', + // address: 12324567412, + // ), + // ]; + + String macName = ''; + + String _info = ""; + String _msj = ''; + bool connected = false; + List items = []; + final List _options = [ + "permission bluetooth granted", + "bluetooth enabled", + "connection status", + "update info" + ]; + + final String _selectSize = "2"; + final _txtText = TextEditingController(text: "Hello developer"); + bool _progress = false; + String _msjprogress = ""; + + String optionprinttype = "58 mm"; + List options = ["58 mm", "80 mm"]; + + @override + void initState() { + super.initState(); + initPlatformState(); + loadData(); + } + + Future initPlatformState() async { + String platformVersion; + int porcentbatery = 0; + // Platform messages may fail, so we use a try/catch PlatformException. + try { + platformVersion = await PrintBluetoothThermal.platformVersion; + print("patformversion: $platformVersion"); + porcentbatery = await PrintBluetoothThermal.batteryLevel; + } on PlatformException { + platformVersion = 'Failed to get platform version.'; + } + + // If the widget was removed from the tree while the asynchronous platform + // message was in flight, we want to discard the reply rather than calling + // setState to update our non-existent appearance. + if (!mounted) return; + + final bool result = await PrintBluetoothThermal.bluetoothEnabled; + print("bluetooth enabled: $result"); + if (result) { + _msj = "Bluetooth enabled, please search and connect"; + } else { + _msj = "Bluetooth not enabled"; + } + + setState(() { + _info = "$platformVersion ($porcentbatery% battery)"; + }); + } + + Future getBluetoots() async { + setState(() { + _progress = true; + _msjprogress = "Wait"; + items = []; + }); + var status2 = await Permission.bluetoothScan.status; + if (status2.isDenied) { + await Permission.bluetoothScan.request(); + } + var status = await Permission.bluetoothConnect.status; + if (status.isDenied) { + await Permission.bluetoothConnect.request(); + } + final List listResult = + await PrintBluetoothThermal.pairedBluetooths; + + setState(() { + _progress = false; + }); + + if (listResult.isEmpty) { + _msj = + "There are no bluetoohs linked, go to settings and link the printer"; + } else { + _msj = "Touch an item in the list to connect"; + } + + setState(() { + items = listResult; + }); + } + + Future connect(String mac) async { + setState(() { + _progress = true; + _msjprogress = "Connecting..."; + connected = false; + }); + final bool result = + await PrintBluetoothThermal.connect(macPrinterAddress: mac); + print("state conected $result"); + if (result) connected = true; + setState(() { + _progress = false; + }); + } + + Future disconnect() async { + final bool status = await PrintBluetoothThermal.disconnect; + setState(() { + connected = false; + }); + print("status disconnect $status"); + } + + Future printTest() async { + bool conexionStatus = await PrintBluetoothThermal.connectionStatus; + //print("connection status: $conexionStatus"); + if (conexionStatus) { + List ticket = await testTicket(); + final result = await PrintBluetoothThermal.writeBytes(ticket); + print("print test result: $result"); + } else { + //no conectado, reconecte + } + } + + Future> testTicket() async { + List bytes = []; + // Using default profile + final profile = await CapabilityProfile.load(); + final generator = Generator( + optionprinttype == "58 mm" ? PaperSize.mm58 : PaperSize.mm80, profile); + //bytes += generator.setGlobalFont(PosFontType.fontA); + bytes += generator.reset(); + + bytes += + generator.text('Enaklo POS', styles: const PosStyles(bold: true)); + bytes += + generator.text('Reverse text', styles: const PosStyles(reverse: true)); + bytes += generator.text('Underlined text', + styles: const PosStyles(underline: true), linesAfter: 1); + bytes += generator.text('Align left', + styles: const PosStyles(align: PosAlign.left)); + bytes += generator.text('Align center', + styles: const PosStyles(align: PosAlign.center)); + bytes += generator.text('Align right', + styles: const PosStyles(align: PosAlign.right), linesAfter: 1); + + bytes += generator.text( + 'FIC Batch 11', + styles: const PosStyles( + height: PosTextSize.size2, + width: PosTextSize.size2, + ), + ); + + bytes += generator.feed(2); + //bytes += generator.cut(); + return bytes; + } + + Future printWithoutPackage() async { + //impresion sin paquete solo de PrintBluetoothTermal + bool connectionStatus = await PrintBluetoothThermal.connectionStatus; + if (connectionStatus) { + String text = "${_txtText.text}\n"; + bool result = await PrintBluetoothThermal.writeString( + printText: PrintTextSize(size: int.parse(_selectSize), text: text)); + print("status print result: $result"); + setState(() { + _msj = "printed status: $result"; + }); + } else { + //no conectado, reconecte + setState(() { + _msj = "no connected device"; + }); + print("no conectado"); + } + } + + Future printString() async { + bool conexionStatus = await PrintBluetoothThermal.connectionStatus; + if (conexionStatus) { + String enter = '\n'; + await PrintBluetoothThermal.writeBytes(enter.codeUnits); + //size of 1-5 + String text = "Hello"; + await PrintBluetoothThermal.writeString( + printText: PrintTextSize(size: 1, text: text)); + await PrintBluetoothThermal.writeString( + printText: PrintTextSize(size: 2, text: "$text size 2")); + await PrintBluetoothThermal.writeString( + printText: PrintTextSize(size: 3, text: "$text size 3")); + } else { + //desconectado + print("desconectado bluetooth $conexionStatus"); + } + } + + Future loadData() async { + final savedSize = await AuthLocalDataSource().getSizeReceipt(); + if (savedSize.isNotEmpty) { + setState(() { + selectedSize = int.parse(savedSize); + }); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Kelola Printer'), + centerTitle: true, + ), + bottomNavigationBar: SizedBox( + height: 60, + child: Button.filled( + onPressed: () async { + // Periksa apakah ukuran dan printer telah dipilih + if (selectedSize != null && macName.isNotEmpty) { + // Simpan ukuran dan alamat MAC printer + AuthLocalDataSource().saveSizeReceipt(selectedSize.toString()); + await connect(macName); + + // Tampilkan pesan berhasil + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Pengaturan berhasil disimpan')), + ); + } else { + // Tampilkan pesan error jika belum dipilih + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: + Text('Pilih ukuran dan printer terlebih dahulu')), + ); + } + }, + label: 'Simpan'), + ), + body: ListView( + padding: const EdgeInsets.all(24.0), + children: [ + Text( + "Pilih Ukuran", + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold, + color: AppColors.primary), + ), + SpaceHeight(16), + Container( + width: context.deviceWidth / 2, + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: AppColors.card, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + // Radio button untuk ukuran 58 + Expanded( + child: Row( + children: [ + Radio( + value: 58, + groupValue: selectedSize, + onChanged: (value) { + setState(() { + selectedSize = value; + }); + }, + ), + const Text('58 mm'), + ], + ), + ), + // Radio button untuk ukuran 80 + Expanded( + child: Row( + children: [ + Radio( + value: 80, + groupValue: selectedSize, + onChanged: (value) { + setState(() { + selectedSize = value; + }); + }, + ), + const Text('80 mm'), + ], + ), + ), + ], + ), + ), + SpaceHeight(24), + Text( + "Pilih Printer", + style: TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.bold, + color: AppColors.primary), + ), + SpaceHeight(16), + Container( + width: context.deviceWidth / 2, + padding: const EdgeInsets.all(8.0), + decoration: BoxDecoration( + color: AppColors.card, + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + MenuPrinterButton( + label: 'Search', + onPressed: () { + getBluetoots(); + selectedIndex = 0; + setState(() {}); + }, + isActive: selectedIndex == 0, + ), + ], + ), + ), + const SpaceHeight(34.0), + _Body( + // selectedIndex: selectedIndex, + macName: macName, + datas: items, + clickHandler: (mac) async { + macName = mac; + + setState(() {}); + }, + ), + SpaceHeight(24), + ], + ), + ); + } +} + +class _Body extends StatelessWidget { + // final int selectedIndex; + final String macName; + final List datas; + + //clickHandler + final Function(String) clickHandler; + + const _Body({ + required this.macName, + required this.datas, + required this.clickHandler, + }); + + @override + Widget build(BuildContext context) { + if (datas.isEmpty) { + return const Text('No data available'); + } else { + return Container( + padding: const EdgeInsets.all(24.0), + decoration: BoxDecoration( + color: Colors.white, + border: Border.all(color: AppColors.card, width: 2), + borderRadius: BorderRadius.circular(6), + ), + child: ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: datas.length, + separatorBuilder: (context, index) => const SpaceHeight(16.0), + itemBuilder: (context, index) => InkWell( + onTap: () { + clickHandler(datas[index].macAdress); + }, + child: MenuPrinterContent( + isSelected: macName == datas[index].macAdress, + data: datas[index], + ), + ), + ), + ); + } + // return const Placeholder(); + } +} diff --git a/lib/presentation/setting/pages/printer_configuration_page.dart b/lib/presentation/setting/pages/printer_configuration_page.dart new file mode 100644 index 0000000..5d7c998 --- /dev/null +++ b/lib/presentation/setting/pages/printer_configuration_page.dart @@ -0,0 +1,191 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/presentation/setting/pages/discount_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/manage_printer_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/product_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/server_key_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/sync_data_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/tax_page.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/bar_printer_page.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/checker_printer_page.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/kitchen_printer_page.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/receipt_printer_page.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class PrinterConfigurationPage extends StatefulWidget { + const PrinterConfigurationPage({super.key}); + + @override + State createState() => _SettingsPageState(); +} + +class _SettingsPageState extends State { + int currentIndex = 0; + String? role; + + void indexValue(int index) { + currentIndex = index; + setState(() {}); + } + + @override + void initState() { + super.initState(); + setRole(); + } + + void setRole() { + AuthLocalDataSource().getAuthData().then((value) { + setState(() { + role = value.user!.role; + }); + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + // LEFT CONTENT + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: ListView( + padding: const EdgeInsets.only( + left: 16, + top: 16, + ), + children: [ + const Text( + 'Printer Configuration', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + ListTile( + // contentPadding: const EdgeInsets.all(12.0), + // leading: Assets.icons.kelolaDiskon.svg(), + title: const Text('Receipt Printer', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + )), + subtitle: const Text('To Print bill and receipt'), + textColor: AppColors.primary, + tileColor: + currentIndex == 0 ? AppColors.card : Colors.transparent, + onTap: () => indexValue(0), + ), + ListTile( + // contentPadding: const EdgeInsets.all(12.0), + // leading: Assets.icons.kelolaPrinter.svg(), + title: const Text('Checker Printer', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + )), + subtitle: const Text('Print checker chit'), + textColor: AppColors.primary, + tileColor: currentIndex == 1 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(1), + ), + ListTile( + // contentPadding: const EdgeInsets.all(12.0), + // leading: Assets.icons.kelolaPajak.svg(), + title: const Text('Kitchen Printer', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + )), + subtitle: const Text('To print food to kitchen'), + textColor: AppColors.primary, + tileColor: currentIndex == 2 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(2), + ), + ListTile( + // contentPadding: const EdgeInsets.all(12.0), + // leading: Assets.icons.kelolaPajak.svg(), + title: const Text('Bar Printer', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + )), + subtitle: const Text('To print drink to bar'), + textColor: AppColors.primary, + tileColor: currentIndex == 3 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(3), + ), + ListTile( + // contentPadding: const EdgeInsets.all(12.0), + // leading: Image.asset(Assets.images.manageQr.path, + // fit: BoxFit.contain), + title: const Text('Additional Printer', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + )), + subtitle: + const Text('To print additional kitchen/bar printer'), + + textColor: AppColors.primary, + tileColor: currentIndex == 4 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(4), + ), + ], + ), + ), + ), + + // RIGHT CONTENT + Expanded( + flex: 4, + child: Align( + alignment: AlignmentDirectional.topStart, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: IndexedStack( + index: currentIndex, + children: [ + ReceiptPrinterPage(), + CheckerPrinterPage(), + KitchenPrinterPage(), + BarPrinterPage(), + // role != null && role! != 'admin' + // ? SizedBox() + // : ProductPage(), + // DiscountPage(), + // ManagePrinterPage(), + // TaxPage(), + // SyncDataPage(), + // ProductPage(), + // ServerKeyPage() + // Text('tax'), + // ManageDiscount(), + // ManagePrinterPage(), + // ManageTax(), + ], + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/pages/product_page.dart b/lib/presentation/setting/pages/product_page.dart new file mode 100644 index 0000000..50bcc50 --- /dev/null +++ b/lib/presentation/setting/pages/product_page.dart @@ -0,0 +1,116 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_remote_datasource.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_products/get_products_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_product/update_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/add_product/add_product_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/dialogs/form_product_dialog.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/add_data.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/menu_product_item.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/settings_title.dart'; + +class ProductPage extends StatefulWidget { + const ProductPage({super.key}); + + @override + State createState() => _ProductPageState(); +} + +class _ProductPageState extends State { + @override + void initState() { + context.read().add(const GetProductsEvent.fetch()); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: ListView( + padding: const EdgeInsets.all(24.0), + children: [ + const SettingsTitle('Manage Products'), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen(orElse: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, success: (products) { + return GridView.builder( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 1, + crossAxisCount: 3, + mainAxisSpacing: 12, + crossAxisSpacing: 12, + ), + itemCount: products.length + 1, + shrinkWrap: true, + physics: const ScrollPhysics(), + itemBuilder: (BuildContext context, int index) { + if (index == 0) { + return AddData( + title: 'Add New Product', + onPressed: () { + showDialog( + context: context, + builder: (context) => MultiBlocProvider( + providers: [ + BlocProvider( + create: (context) => AddProductBloc(ProductRemoteDatasource()), + ), + BlocProvider.value( + value: context.read(), + ), + BlocProvider.value( + value: context.read(), + ), + ], + child: const FormProductDialog(), + ), + ); + }, + ); + } + final item = products[index - 1]; + return MenuProductItem( + data: item, + onTapEdit: () { + showDialog( + context: context, + builder: (context) => MultiBlocProvider( + providers: [ + BlocProvider( + create: (context) => UpdateProductBloc(ProductRemoteDatasource()), + ), + BlocProvider.value( + value: context.read(), + ), + BlocProvider.value( + value: context.read(), + ), + ], + child: FormProductDialog(product: item), + ), + ); + }, + ); + }, + ); + }); + }, + ), + ], + ), + // floatingActionButton: FloatingActionButton( + // onPressed: () { + + // }, + // child: const Icon(Icons.add), + // ), + ); + } +} diff --git a/lib/presentation/setting/pages/server_key_page.dart b/lib/presentation/setting/pages/server_key_page.dart new file mode 100644 index 0000000..4a41ab7 --- /dev/null +++ b/lib/presentation/setting/pages/server_key_page.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; + +class ServerKeyPage extends StatefulWidget { + final bool isTablet; + const ServerKeyPage({ + super.key, + this.isTablet = false, + }); + + @override + State createState() => _ServerKeyPageState(); +} + +class _ServerKeyPageState extends State { + TextEditingController? serverKeyController; + + String serverKey = ''; + + Future getServerKey() async { + serverKey = await AuthLocalDataSource().getMitransServerKey(); + } + + @override + void initState() { + super.initState(); + serverKeyController = TextEditingController(); + getServerKey(); + //delay 2 detik + Future.delayed(const Duration(seconds: 2), () { + serverKeyController!.text = serverKey; + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Save Server Key'), + centerTitle: true, + ), + //textfield untuk input server key + body: Column( + children: [ + Padding( + padding: const EdgeInsets.all(20.0), + child: TextField( + controller: serverKeyController, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Server Key', + ), + ), + ), + //button untuk save server key + ElevatedButton( + onPressed: () { + AuthLocalDataSource() + .saveMidtransServerKey(serverKeyController!.text); + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Server Key saved'), + backgroundColor: AppColors.primary, + ), + ); + }, + child: const Text('Save'), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/pages/settings_page.dart b/lib/presentation/setting/pages/settings_page.dart new file mode 100644 index 0000000..4f7958b --- /dev/null +++ b/lib/presentation/setting/pages/settings_page.dart @@ -0,0 +1,174 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart'; +import 'package:enaklo_pos/presentation/sales/pages/sales_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/discount_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/manage_printer_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/product_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/server_key_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/sync_data_page.dart'; +import 'package:enaklo_pos/presentation/setting/pages/tax_page.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class SettingsPage extends StatefulWidget { + const SettingsPage({super.key}); + + @override + State createState() => _SettingsPageState(); +} + +class _SettingsPageState extends State { + int currentIndex = 0; + String? role; + + void indexValue(int index) { + currentIndex = index; + setState(() {}); + } + + @override + void initState() { + super.initState(); + setRole(); + } + + void setRole() { + AuthLocalDataSource().getAuthData().then((value) { + setState(() { + role = value.user!.role; + }); + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + // LEFT CONTENT + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: ListView( + padding: const EdgeInsets.all(16.0), + children: [ + const Text( + 'Settings', + style: TextStyle( + color: AppColors.primary, + fontSize: 28, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + role != null && role! != 'admin' + ? const SizedBox() + : ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Assets.icons.kelolaProduk.svg(), + title: const Text('Manage Products'), + subtitle: const Text('Manage products in your store'), + textColor: AppColors.primary, + tileColor: currentIndex == 0 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(0), + ), + ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Assets.icons.kelolaDiskon.svg(), + title: const Text('Kelola Diskon'), + subtitle: const Text('Kelola Diskon Pelanggan'), + textColor: AppColors.primary, + tileColor: currentIndex == 1 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(1), + ), + ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Assets.icons.dashboard.svg(), + title: const Text('History Transaksi'), + subtitle: const Text('Lihat history transaksi'), + textColor: AppColors.primary, + tileColor: currentIndex == 2 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(2), + ), + ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Assets.icons.kelolaPajak.svg(), + title: const Text('Perhitungan Biaya'), + subtitle: const Text('Kelola biaya diluar biaya modal'), + textColor: AppColors.primary, + tileColor: currentIndex == 3 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(3), + ), + ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Assets.icons.kelolaPajak.svg(), + title: const Text('Sync Data'), + subtitle: + const Text('Sinkronisasi data dari dan ke server'), + textColor: AppColors.primary, + tileColor: currentIndex == 4 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(4), + ), + ListTile( + contentPadding: const EdgeInsets.all(12.0), + leading: Image.asset(Assets.images.manageQr.path, + fit: BoxFit.contain), + title: const Text('QR Key Setting'), + subtitle: const Text('QR Key Configuration'), + textColor: AppColors.primary, + tileColor: currentIndex == 6 + ? AppColors.blueLight + : Colors.transparent, + onTap: () => indexValue(6), + ), + ], + ), + ), + ), + + // RIGHT CONTENT + Expanded( + flex: 4, + child: Align( + alignment: AlignmentDirectional.topStart, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: IndexedStack( + index: currentIndex, + children: [ + role != null && role! != 'admin' + ? SizedBox() + : ProductPage(), + DiscountPage(), + SalesPage(), + TaxPage(), + SyncDataPage(), + ProductPage(), + ServerKeyPage() + // Text('tax'), + // ManageDiscount(), + // ManagePrinterPage(), + // ManageTax(), + ], + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/pages/sync_data_page.dart b/lib/presentation/setting/pages/sync_data_page.dart new file mode 100644 index 0000000..c1acd55 --- /dev/null +++ b/lib/presentation/setting/pages/sync_data_page.dart @@ -0,0 +1,118 @@ +import 'dart:developer'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_order/sync_order_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/sync_product/sync_product_bloc.dart'; + +class SyncDataPage extends StatefulWidget { + const SyncDataPage({super.key}); + + @override + State createState() => _SyncDataPageState(); +} + +class _SyncDataPageState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Sync Data'), + ), + body: Column( + children: [ + BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + error: (message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(message), + backgroundColor: Colors.red, + ), + ); + }, + loaded: (productResponseModel) async { + await ProductLocalDatasource.instance.deleteAllProducts(); + await ProductLocalDatasource.instance.insertProducts( + productResponseModel.data!, + ); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Sync Product Success2'), + backgroundColor: Colors.green, + ), + ); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return ElevatedButton( + onPressed: () { + context + .read() + .add(const SyncProductEvent.syncProduct()); + }, + child: const Text('Sync Product')); + }, + loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + ); + }, + ), + BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + error: (message) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(message), + backgroundColor: Colors.red, + ), + ); + }, + loaded: () { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Sync Order Success'), + backgroundColor: Colors.green, + ), + ); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return ElevatedButton( + onPressed: () { + log("🔘 Sync Order button pressed"); + log("🔘 SyncOrderBloc instance: ${context.read()}"); + context + .read() + .add(const SyncOrderEvent.syncOrder()); + log("🔘 SyncOrderEvent.syncOrder dispatched"); + }, + child: const Text('Sync Order'), + ); + }, + loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }, + ); + }, + ) + ], + ), + ); + } +} diff --git a/lib/presentation/setting/pages/tax_page.dart b/lib/presentation/setting/pages/tax_page.dart new file mode 100644 index 0000000..304977b --- /dev/null +++ b/lib/presentation/setting/pages/tax_page.dart @@ -0,0 +1,151 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../home/widgets/custom_tab_bar.dart'; +import '../bloc/tax_settings/tax_settings_bloc.dart'; +import '../dialogs/form_tax_dialog.dart'; +import '../models/tax_model.dart'; +import '../widgets/add_data.dart'; +import '../widgets/manage_tax_card.dart'; +import '../widgets/settings_title.dart'; + +class TaxPage extends StatefulWidget { + const TaxPage({super.key}); + + @override + State createState() => _TaxPageState(); +} + +class _TaxPageState extends State { + @override + void initState() { + super.initState(); + context.read().add(const TaxSettingsEvent.loadSettings()); + } + + void onEditTap(TaxModel item, int serviceChargeValue, int taxValue) { + showDialog( + context: context, + builder: (context) => FormTaxDialog( + taxValue: taxValue, + serviceChargeValue: serviceChargeValue, + onSave: (newTaxValue, newServiceChargeValue) { + context.read().add( + TaxSettingsEvent.updateSettings( + taxValue: newTaxValue, + serviceChargeValue: newServiceChargeValue, + ), + ); + }, + ), + ); + } + + void onAddDataTap(int serviceChargeValue, int taxValue) { + showDialog( + context: context, + builder: (context) => FormTaxDialog( + taxValue: taxValue, + serviceChargeValue: serviceChargeValue, + onSave: (newTaxValue, newServiceChargeValue) { + context.read().add( + TaxSettingsEvent.updateSettings( + taxValue: newTaxValue, + serviceChargeValue: newServiceChargeValue, + ), + ); + }, + ), + ); + } + + @override + Widget build(BuildContext context) { + return SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + const SettingsTitle('Perhitungan Biaya'), + const SizedBox(height: 24), + BlocBuilder( + builder: (context, state) { + return state.when( + initial: () => const Center(child: CircularProgressIndicator()), + loading: () => const Center(child: CircularProgressIndicator()), + error: (message) => Center(child: Text('Error: $message')), + loaded: (taxModel, serviceChargeValue) { + final items = [ + TaxModel(name: 'Biaya Layanan', type: TaxType.layanan, value: serviceChargeValue), + taxModel, + ]; + + return CustomTabBar( + tabTitles: const ['Layanan', 'Pajak'], + initialTabIndex: 0, + tabViews: [ + // LAYANAN TAB + SizedBox( + child: GridView.builder( + shrinkWrap: true, + itemCount: 2, // Add button + 1 service charge item + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + if (index == 0) { + return AddData( + title: 'Edit Perhitungan', + onPressed: () => onAddDataTap(serviceChargeValue, taxModel.value), + ); + } + final item = items.firstWhere((element) => element.type.isLayanan); + return ManageTaxCard( + data: item, + onEditTap: () => onEditTap(item, serviceChargeValue, taxModel.value), + ); + }, + ), + ), + + // PAJAK TAB + SizedBox( + child: GridView.builder( + shrinkWrap: true, + itemCount: 2, // Add button + 1 tax item + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 0.85, + crossAxisCount: 3, + crossAxisSpacing: 30.0, + mainAxisSpacing: 30.0, + ), + itemBuilder: (context, index) { + if (index == 0) { + return AddData( + title: 'Edit Perhitungan', + onPressed: () => onAddDataTap(serviceChargeValue, taxModel.value), + ); + } + final item = items.firstWhere((element) => element.type.isPajak); + return ManageTaxCard( + data: item, + onEditTap: () => onEditTap(item, serviceChargeValue, taxModel.value), + ); + }, + ), + ), + ], + ); + }, + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/add_data.dart b/lib/presentation/setting/widgets/add_data.dart new file mode 100644 index 0000000..384aab1 --- /dev/null +++ b/lib/presentation/setting/widgets/add_data.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + + + +class AddData extends StatelessWidget { + final String title; + final VoidCallback onPressed; + + const AddData({ + super.key, + required this.title, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onPressed, + child: Container( + padding: const EdgeInsets.all(16.0), + decoration: ShapeDecoration( + shape: RoundedRectangleBorder( + side: const BorderSide(width: 1, color: AppColors.card), + borderRadius: BorderRadius.circular(19), + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.add, + color: AppColors.primary, + ), + const SpaceHeight(8.0), + Text( + title, + style: const TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/bar_printer_page.dart b/lib/presentation/setting/widgets/bar_printer_page.dart new file mode 100644 index 0000000..a37a195 --- /dev/null +++ b/lib/presentation/setting/widgets/bar_printer_page.dart @@ -0,0 +1,308 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_bar/get_printer_bar_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/dialog_search_printer.dart'; + +class BarPrinterPage extends StatefulWidget { + const BarPrinterPage({super.key}); + + @override + State createState() => _BarPrinterPageState(); +} + +class _BarPrinterPageState extends State { + String selectedPrinter = 'Bluetooth'; + TextEditingController? addressController; + TextEditingController? printNameController; + String paper = '58'; + bool isInitialized = false; + @override + void initState() { + // TODO: implement initState + super.initState(); + addressController = TextEditingController(); + printNameController = TextEditingController(); + context.read().add(GetPrinterBarEvent.get()); + } + + @override + void dispose() { + addressController!.dispose(); + printNameController!.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loading: () { + return Center(child: CircularProgressIndicator()); + }, + success: (data) { + if (data != null && !isInitialized) { + addressController!.text = data.address; + printNameController!.text = data.name; + selectedPrinter = data.type; + paper = data.paper; + isInitialized = true; + } + return Container( + // width: 300, + width: context.deviceWidth, + padding: const EdgeInsets.all(16.0), + color: Colors.white, + child: ListView( + children: [ + const Text( + 'Bar Printer', + style: TextStyle( + color: Colors.black, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + SpaceHeight(16), + + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Printer Type', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: selectedPrinter, // nilai default + items: const [ + DropdownMenuItem( + value: 'Bluetooth', + child: Text('Bluetooth'), + ), + DropdownMenuItem( + value: 'Network', + child: Text('Network'), + ), + ], + onChanged: (value) { + selectedPrinter = value ?? 'Bluetooth'; + setState(() {}); + }, + ), + SpaceHeight(8), + //button search + selectedPrinter == 'Bluetooth' + ? Button.outlined( + onPressed: () { + showDialog( + context: context, + builder: (context) => DialogSearchPrinter( + onSelected: (value) { + addressController!.text = value; + setState(() {}); + }, + ), + ); + }, + label: 'Search') + : CustomTextField( + controller: addressController!, + label: 'Address', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for name + CustomTextField( + controller: printNameController!, + label: 'Print Name', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for width paper + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Width Paper', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: paper, // nilai default + items: const [ + DropdownMenuItem( + value: '58', + child: Text('58 mm'), + ), + DropdownMenuItem( + value: '80', + child: Text('80 mm'), + ), + ], + onChanged: (value) { + paper = value ?? '58'; + log('Paper : $paper'); + }, + ), + + SpaceHeight(16), + // button test print + Button.outlined( + onPressed: () async { + if (addressController!.text.isNotEmpty && printNameController!.text.isNotEmpty) { + try { + // Create a test print model + final testPrinter = PrintModel( + code: 'bar', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + // Generate test print data + final testPrintData = await PrintDataoutputs.instance.printBar( + [], // Empty product list for test + 'Test Table', + 'Test Order', + 'Test Cashier', + int.parse(paper), + 'DINE IN', + ); + + // Print test + await PrinterService().printWithPrinter( + testPrinter, + testPrintData, + context, + ); + } catch (e) { + log("Error test printing: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error test printing: $e')), + ); + } + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Please fill in printer details first')), + ); + } + }, + label: 'Test Print' + ), + SpaceHeight(8), + // button save + data == null + ? BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterBarEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + code: 'bar', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + context.read().add( + CreatePrinterEvent.createPrinter( + printData), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ) + : BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterBarEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + id: data.id, + code: 'bar', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + log("Print Data : ${printData.toMap()}"); + + context.read().add( + UpdatePrinterEvent.updatePrinter( + printData, + ), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ), + SpaceHeight(16), + ], + ), + ); + }, + ); + }, + )); + } +} diff --git a/lib/presentation/setting/widgets/checker_printer_page.dart b/lib/presentation/setting/widgets/checker_printer_page.dart new file mode 100644 index 0000000..924dd95 --- /dev/null +++ b/lib/presentation/setting/widgets/checker_printer_page.dart @@ -0,0 +1,310 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_checker/get_printer_checker_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/dialog_search_printer.dart'; + +class CheckerPrinterPage extends StatefulWidget { + const CheckerPrinterPage({super.key}); + + @override + State createState() => _CheckerPrinterPageState(); +} + +class _CheckerPrinterPageState extends State { + String selectedPrinter = 'Bluetooth'; + TextEditingController? addressController; + TextEditingController? printNameController; + String paper = '58'; + bool isInitialized = false; + @override + void initState() { + // TODO: implement initState + super.initState(); + addressController = TextEditingController(); + printNameController = TextEditingController(); + context.read().add(GetPrinterCheckerEvent.get()); + } + + @override + void dispose() { + addressController!.dispose(); + printNameController!.dispose(); + isInitialized = false; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loading: () { + return Center(child: CircularProgressIndicator()); + }, + success: (data) { + log("Checker Printer: ${data?.toMap()}"); + if (data != null && !isInitialized) { + addressController!.text = data.address; + printNameController!.text = data.name; + selectedPrinter = data.type; + paper = data.paper; + isInitialized = true; + } + return Container( + // width: 300, + width: context.deviceWidth, + padding: const EdgeInsets.all(16.0), + color: Colors.white, + child: ListView( + children: [ + const Text( + 'Checker Printer', + style: TextStyle( + color: Colors.black, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + SpaceHeight(16), + + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Printer Type', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: selectedPrinter, // nilai default + items: const [ + DropdownMenuItem( + value: 'Bluetooth', + child: Text('Bluetooth'), + ), + DropdownMenuItem( + value: 'Network', + child: Text('Network'), + ), + ], + onChanged: (value) { + selectedPrinter = value ?? 'Bluetooth'; + setState(() {}); + }, + ), + SpaceHeight(8), + //button search + selectedPrinter == 'Bluetooth' + ? Button.outlined( + onPressed: () { + showDialog( + context: context, + builder: (context) => DialogSearchPrinter( + onSelected: (value) { + addressController!.text = value; + setState(() {}); + }, + ), + ); + }, + label: 'Search') + : CustomTextField( + controller: addressController!, + label: 'Address', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for name + CustomTextField( + controller: printNameController!, + label: 'Print Name', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for width paper + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Width Paper', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: paper, // nilai default + items: const [ + DropdownMenuItem( + value: '58', + child: Text('58 mm'), + ), + DropdownMenuItem( + value: '80', + child: Text('80 mm'), + ), + ], + onChanged: (value) { + paper = value ?? '58'; + log('Paper : $paper'); + }, + ), + + SpaceHeight(16), + // button test print + Button.outlined( + onPressed: () async { + if (addressController!.text.isNotEmpty && printNameController!.text.isNotEmpty) { + try { + // Create a test print model + final testPrinter = PrintModel( + code: 'checker', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + // Generate test print data + final testPrintData = await PrintDataoutputs.instance.printChecker( + [], // Empty product list for test + 'Test Table', + 'Test Order', + 'Test Cashier', + int.parse(paper), + 'DINE IN', + ); + + // Print test + await PrinterService().printWithPrinter( + testPrinter, + testPrintData, + context, + ); + } catch (e) { + log("Error test printing: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error test printing: $e')), + ); + } + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Please fill in printer details first')), + ); + } + }, + label: 'Test Print' + ), + SpaceHeight(8), + // button save + data == null + ? BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterCheckerEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + code: 'checker', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + context.read().add( + CreatePrinterEvent.createPrinter( + printData), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ) + : BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterCheckerEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + id: data.id, + code: 'checker', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + log("Print Data : ${printData.toMap()}"); + + context.read().add( + UpdatePrinterEvent.updatePrinter( + printData, + ), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ), + SpaceHeight(16), + ], + ), + ); + }, + ); + }, + )); + } +} diff --git a/lib/presentation/setting/widgets/dialog_search_printer.dart b/lib/presentation/setting/widgets/dialog_search_printer.dart new file mode 100644 index 0000000..89c9494 --- /dev/null +++ b/lib/presentation/setting/widgets/dialog_search_printer.dart @@ -0,0 +1,108 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:permission_handler/permission_handler.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; + +class DialogSearchPrinter extends StatefulWidget { + final Function(String) onSelected; + const DialogSearchPrinter({ + super.key, + required this.onSelected, + }); + + @override + State createState() => _DialogSearchPrinterState(); +} + +class _DialogSearchPrinterState extends State { + String macName = ''; + String? macConnected; + + bool connected = false; + List items = []; + + Future getBluetoots() async { + setState(() { + items = []; + }); + if (!mounted) return; + + final bool result = await PrinterService().isBluetoothEnabled(); + if (result) { + final List listResult = await PrinterService().getPairedBluetoothDevices(); + log("listResult: $listResult"); + setState(() { + items = listResult; + }); + } + } + + Future connect(String mac) async { + final bool result = await PrinterService().connectBluetoothPrinter(mac); + if (result) { + widget.onSelected(mac); + } + } + + @override + void initState() { + loadPermession(); + getBluetoots(); + super.initState(); + } + + Future loadPermession() async { + var status2 = await Permission.bluetoothScan.status; + log("Permession: $status2"); + if (status2.isDenied) { + await Permission.bluetoothScan.request(); + } + var status = await Permission.bluetoothConnect.status; + if (status.isDenied) { + await Permission.bluetoothConnect.request(); + } + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: const Text('Search Printer'), + content: SizedBox( + width: context.deviceWidth / 2, + child: items.isEmpty + ? const Padding( + padding: EdgeInsets.all(20), + child: Center(child: CircularProgressIndicator()), + ) + : SizedBox( + height: 200, + child: ListView.builder( + itemCount: items.length, + itemBuilder: (context, index) { + return ListTile( + title: Text(items[index].name), + subtitle: Text(items[index].macAdress), + onTap: () { + connect(items[index].macAdress); + widget.onSelected(items[index].macAdress); + Navigator.of(context).pop(); + }, + ); + }, + ), + ), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); + }, + child: const Text('Cancel'), + ), + ], + ); + } +} diff --git a/lib/presentation/setting/widgets/kitchen_printer_page.dart b/lib/presentation/setting/widgets/kitchen_printer_page.dart new file mode 100644 index 0000000..0afd491 --- /dev/null +++ b/lib/presentation/setting/widgets/kitchen_printer_page.dart @@ -0,0 +1,308 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_kitchen/get_printer_kitchen_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/dialog_search_printer.dart'; + +class KitchenPrinterPage extends StatefulWidget { + const KitchenPrinterPage({super.key}); + + @override + State createState() => _KitchenPrinterPageState(); +} + +class _KitchenPrinterPageState extends State { + String selectedPrinter = 'Bluetooth'; + TextEditingController? addressController; + TextEditingController? printNameController; + String paper = '58'; + bool isInitialized = false; + @override + void initState() { + // TODO: implement initState + super.initState(); + addressController = TextEditingController(); + printNameController = TextEditingController(); + context.read().add(GetPrinterKitchenEvent.get()); + } + + @override + void dispose() { + addressController!.dispose(); + printNameController!.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loading: () { + return Center(child: CircularProgressIndicator()); + }, + success: (data) { + if (data != null && !isInitialized) { + addressController!.text = data.address; + printNameController!.text = data.name; + selectedPrinter = data.type; + paper = data.paper; + isInitialized = true; + } + return Container( + // width: 300, + width: context.deviceWidth, + padding: const EdgeInsets.all(16.0), + color: Colors.white, + child: ListView( + children: [ + const Text( + 'Kitchen Printer', + style: TextStyle( + color: Colors.black, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + SpaceHeight(16), + + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Printer Type', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: selectedPrinter, // nilai default + items: const [ + DropdownMenuItem( + value: 'Bluetooth', + child: Text('Bluetooth'), + ), + DropdownMenuItem( + value: 'Network', + child: Text('Network'), + ), + ], + onChanged: (value) { + selectedPrinter = value ?? 'Bluetooth'; + setState(() {}); + }, + ), + SpaceHeight(8), + //button search + selectedPrinter == 'Bluetooth' + ? Button.outlined( + onPressed: () { + showDialog( + context: context, + builder: (context) => DialogSearchPrinter( + onSelected: (value) { + addressController!.text = value; + setState(() {}); + }, + ), + ); + }, + label: 'Search') + : CustomTextField( + controller: addressController!, + label: 'Address', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for name + CustomTextField( + controller: printNameController!, + label: 'Print Name', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for width paper + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Width Paper', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: paper, // nilai default + items: const [ + DropdownMenuItem( + value: '58', + child: Text('58 mm'), + ), + DropdownMenuItem( + value: '80', + child: Text('80 mm'), + ), + ], + onChanged: (value) { + paper = value ?? '58'; + log('Paper : $paper'); + }, + ), + + SpaceHeight(16), + // button test print + Button.outlined( + onPressed: () async { + if (addressController!.text.isNotEmpty && printNameController!.text.isNotEmpty) { + try { + // Create a test print model + final testPrinter = PrintModel( + code: 'kitchen', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + // Generate test print data + final testPrintData = await PrintDataoutputs.instance.printKitchen( + [], // Empty product list for test + 'Test Table', + 'Test Order', + 'Test Cashier', + int.parse(paper), + 'DINE IN', + ); + + // Print test + await PrinterService().printWithPrinter( + testPrinter, + testPrintData, + context, + ); + } catch (e) { + log("Error test printing: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error test printing: $e')), + ); + } + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Please fill in printer details first')), + ); + } + }, + label: 'Test Print' + ), + SpaceHeight(8), + // button save + data == null + ? BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterKitchenEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + code: 'kitchen', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + context.read().add( + CreatePrinterEvent.createPrinter( + printData), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ) + : BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterKitchenEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + id: data.id, + code: 'kitchen', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + log("Print Data : ${printData.toMap()}"); + + context.read().add( + UpdatePrinterEvent.updatePrinter( + printData, + ), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ), + SpaceHeight(16), + ], + ), + ); + }, + ); + }, + )); + } +} diff --git a/lib/presentation/setting/widgets/manage_discount_card.dart b/lib/presentation/setting/widgets/manage_discount_card.dart new file mode 100644 index 0000000..8fa1c80 --- /dev/null +++ b/lib/presentation/setting/widgets/manage_discount_card.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/data/models/response/discount_response_model.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/constants/colors.dart'; + +class ManageDiscountCard extends StatelessWidget { + final Discount data; + final VoidCallback onEditTap; + + const ManageDiscountCard({ + super.key, + required this.data, + required this.onEditTap, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16.0), + decoration: ShapeDecoration( + shape: RoundedRectangleBorder( + side: const BorderSide(width: 1, color: AppColors.card), + borderRadius: BorderRadius.circular(19), + ), + ), + child: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Spacer(), + Container( + alignment: Alignment.center, + padding: const EdgeInsets.all(20.0), + margin: const EdgeInsets.only(top: 30.0), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.disabled.withOpacity(0.4), + ), + child: Text( + '${data.value!.replaceAll('.00', '')}%', + style: const TextStyle( + fontSize: 24, + fontWeight: FontWeight.w900, + ), + ), + ), + const Spacer(), + Center( + child: RichText( + text: TextSpan( + text: 'Nama Promo : ', + children: [ + TextSpan( + text: data.name, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ], + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: AppColors.black, + ), + ), + ), + ), + const Spacer(), + ], + ), + Align( + alignment: Alignment.topRight, + child: GestureDetector( + onTap: onEditTap, + child: Container( + padding: const EdgeInsets.all(8.0), + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(50.0)), + color: AppColors.primary, + ), + child: Assets.icons.edit.svg(), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/manage_tax_card.dart b/lib/presentation/setting/widgets/manage_tax_card.dart new file mode 100644 index 0000000..0577f68 --- /dev/null +++ b/lib/presentation/setting/widgets/manage_tax_card.dart @@ -0,0 +1,92 @@ +import 'package:flutter/material.dart'; + +import '../../../core/assets/assets.gen.dart'; +import '../../../core/constants/colors.dart'; +import '../models/tax_model.dart'; + +class ManageTaxCard extends StatelessWidget { + final TaxModel data; + final VoidCallback onEditTap; + + const ManageTaxCard({ + super.key, + required this.data, + required this.onEditTap, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16.0), + decoration: ShapeDecoration( + shape: RoundedRectangleBorder( + side: const BorderSide(width: 1, color: AppColors.card), + borderRadius: BorderRadius.circular(19), + ), + ), + child: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Spacer(), + Container( + alignment: Alignment.center, + padding: const EdgeInsets.all(12.0), + margin: const EdgeInsets.only(top: 30.0), + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppColors.disabled.withOpacity(0.4), + ), + child: Text( + '${data.value}%', + style: const TextStyle( + fontSize: 32, + fontWeight: FontWeight.w900, + ), + ), + ), + const Spacer(), + Center( + child: RichText( + text: TextSpan( + text: 'Nama Promo : ', + children: [ + TextSpan( + text: data.type.name, + style: const TextStyle( + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + ], + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w400, + color: AppColors.black, + ), + ), + ), + ), + const Spacer(), + ], + ), + Align( + alignment: Alignment.topRight, + child: GestureDetector( + onTap: onEditTap, + child: Container( + padding: const EdgeInsets.all(8.0), + decoration: const BoxDecoration( + borderRadius: BorderRadius.all(Radius.circular(50.0)), + color: AppColors.primary, + ), + child: Assets.icons.edit.svg(), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/menu_printer_button.dart b/lib/presentation/setting/widgets/menu_printer_button.dart new file mode 100644 index 0000000..70838de --- /dev/null +++ b/lib/presentation/setting/widgets/menu_printer_button.dart @@ -0,0 +1,52 @@ +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + + + +class MenuPrinterButton extends StatelessWidget { + final String label; + final VoidCallback onPressed; + final bool isActive; + + const MenuPrinterButton({ + super.key, + required this.label, + required this.onPressed, + required this.isActive, + }); + + @override + Widget build(BuildContext context) { + return Flexible( + child: InkWell( + onTap: onPressed, + child: Container( + width: context.deviceWidth, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: isActive ? Colors.white : AppColors.card, + borderRadius: BorderRadius.circular(6), + boxShadow: isActive + ? const [ + BoxShadow( + color: AppColors.white, + blurRadius: 2, + offset: Offset(0, 1), + spreadRadius: 0, + ), + ] + : null, + ), + child: Text( + label, + textAlign: TextAlign.center, + style: TextStyle( + color: isActive ? AppColors.primary : AppColors.black, + ), + ), + ), + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/menu_printer_content.dart b/lib/presentation/setting/widgets/menu_printer_content.dart new file mode 100644 index 0000000..9ce9224 --- /dev/null +++ b/lib/presentation/setting/widgets/menu_printer_content.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart'; + + +import '../../../../core/constants/colors.dart'; + +class MenuPrinterContent extends StatelessWidget { + final BluetoothInfo data; + final bool isSelected; + const MenuPrinterContent({ + super.key, + required this.data, + required this.isSelected, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 10.0), + decoration: BoxDecoration( + border: Border.all( + width: isSelected ? 4.0 : 1.0, + color: isSelected ? AppColors.primary : AppColors.card), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Name : ${data.name}', + style: const TextStyle( + fontWeight: FontWeight.w700, + ), + ), + Text( + 'macAddress: ${data.macAdress}', + style: const TextStyle( + fontSize: 12, + ), + ), + ], + ), + ); + } +} diff --git a/lib/presentation/setting/widgets/menu_product_item.dart b/lib/presentation/setting/widgets/menu_product_item.dart new file mode 100644 index 0000000..083393d --- /dev/null +++ b/lib/presentation/setting/widgets/menu_product_item.dart @@ -0,0 +1,185 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; +import '../../../core/constants/variables.dart'; + +class MenuProductItem extends StatelessWidget { + final Product data; + final Function() onTapEdit; + const MenuProductItem({ + super.key, + required this.data, + required this.onTapEdit, + }); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16.0), + decoration: ShapeDecoration( + color: Colors.white, + shape: RoundedRectangleBorder( + side: const BorderSide(width: 3, color: AppColors.blueLight), + borderRadius: BorderRadius.circular(16), + ), + ), + child: Column( + children: buildList(context), + )); + } + + List buildList(BuildContext context) { + return [ + Stack( + children: [ + Center( + child: ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(10.0)), + child: CachedNetworkImage( + imageUrl: '${Variables.baseUrl}/${data.image}', + placeholder: (context, url) => + const Center(child: CircularProgressIndicator()), + errorWidget: (context, url, error) => const Icon( + Icons.food_bank_outlined, + size: 80, + ), + width: 54, + height: 54, + fit: BoxFit.cover, + ), + ), + ), + ], + ), + Flexible( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Spacer(), + Text( + data.name!, + style: const TextStyle( + fontSize: 16, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + Text( + data.category?.name ?? '-', + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + Spacer(), + Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () { + showDialog( + context: context, + // backgroundColor: AppColors.white, + builder: (context) { + //container for product detail + return AlertDialog( + contentPadding: const EdgeInsets.all(16.0), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + mainAxisAlignment: + MainAxisAlignment.spaceBetween, + children: [ + Text( + data.name!, + style: const TextStyle( + fontSize: 20, + ), + ), + IconButton( + onPressed: () { + Navigator.pop(context); + }, + icon: const Icon(Icons.close), + ), + ], + ), + const SpaceHeight(10.0), + ClipRRect( + borderRadius: const BorderRadius.all( + Radius.circular(10.0)), + child: CachedNetworkImage( + imageUrl: + '${Variables.baseUrl}${data.image}', + placeholder: (context, url) => + const Center( + child: + CircularProgressIndicator()), + errorWidget: (context, url, error) => + const Icon( + Icons.food_bank_outlined, + size: 80, + ), + width: 80, + ), + ), + const SpaceHeight(10.0), + Text( + data.category?.name ?? '-', + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + const SpaceHeight(10.0), + Text( + data.price.toString(), + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + const SpaceHeight(10.0), + Text( + data.stock.toString(), + style: const TextStyle( + fontSize: 12, + color: Colors.grey, + ), + ), + const SpaceHeight(10.0), + ], + ), + ); + }); + }, + label: 'View', + fontSize: 12.0, + height: 30, + borderRadius: 10, + ), + ), + const SpaceWidth(6.0), + Flexible( + child: Button.outlined( + onPressed: onTapEdit, + label: 'Edit', + fontSize: 12.0, + height: 30, + borderRadius: 10, + ), + ), + ], + ), + ], + ), + ), + ]; + } +} diff --git a/lib/presentation/setting/widgets/receipt_printer_page.dart b/lib/presentation/setting/widgets/receipt_printer_page.dart new file mode 100644 index 0000000..8561e6e --- /dev/null +++ b/lib/presentation/setting/widgets/receipt_printer_page.dart @@ -0,0 +1,323 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/data/models/response/print_model.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/create_printer/create_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/get_printer_receipt/get_printer_receipt_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/bloc/update_printer/update_printer_bloc.dart'; +import 'package:enaklo_pos/presentation/setting/widgets/dialog_search_printer.dart'; +import 'package:enaklo_pos/core/utils/printer_service.dart'; +import 'package:enaklo_pos/data/dataoutputs/print_dataoutputs.dart'; +import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart'; + +class ReceiptPrinterPage extends StatefulWidget { + const ReceiptPrinterPage({super.key}); + + @override + State createState() => _ReceiptPrinterPageState(); +} + +class _ReceiptPrinterPageState extends State { + String selectedPrinter = 'Bluetooth'; + TextEditingController? addressController; + TextEditingController? printNameController; + String paper = '58'; + bool isInitialized = false; + @override + void initState() { + // TODO: implement initState + super.initState(); + addressController = TextEditingController(); + printNameController = TextEditingController(); + context.read().add(GetPrinterReceiptEvent.get()); + } + + @override + void dispose() { + addressController!.dispose(); + printNameController!.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.white, + body: BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loading: () { + return Center(child: CircularProgressIndicator()); + }, + success: (data) { + if (data != null && !isInitialized) { + addressController!.text = data.address; + printNameController!.text = data.name; + selectedPrinter = data.type; + paper = data.paper; + isInitialized = true; + } + return Container( + // width: 300, + width: context.deviceWidth, + padding: const EdgeInsets.all(16.0), + color: Colors.white, + child: ListView( + children: [ + const Text( + 'Receipt Printer', + style: TextStyle( + color: Colors.black, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + SpaceHeight(16), + + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Printer Type', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: selectedPrinter, // nilai default + items: const [ + DropdownMenuItem( + value: 'Bluetooth', + child: Text('Bluetooth'), + ), + DropdownMenuItem( + value: 'Network', + child: Text('Network'), + ), + ], + onChanged: (value) { + selectedPrinter = value ?? 'Bluetooth'; + setState(() {}); + }, + ), + SpaceHeight(8), + //button search + selectedPrinter == 'Bluetooth' + ? Button.outlined( + onPressed: () { + showDialog( + context: context, + builder: (context) => DialogSearchPrinter( + onSelected: (value) { + addressController!.text = value; + setState(() {}); + }, + ), + ); + }, + label: 'Search') + : CustomTextField( + controller: addressController!, + label: 'Address', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for name + CustomTextField( + controller: printNameController!, + label: 'Print Name', + showLabel: false, + ), + SpaceHeight(16), + // Textfield for width paper + DropdownButtonFormField( + decoration: InputDecoration( + labelText: 'Width Paper', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10.0), + ), + ), + value: paper, // nilai default + items: const [ + DropdownMenuItem( + value: '58', + child: Text('58 mm'), + ), + DropdownMenuItem( + value: '80', + child: Text('80 mm'), + ), + ], + onChanged: (value) { + paper = value ?? '58'; + log('Paper : $paper'); + }, + ), + + SpaceHeight(16), + // button test print + Button.outlined( + onPressed: () async { + if (addressController!.text.isNotEmpty && printNameController!.text.isNotEmpty) { + try { + // Get actual tax and service charge settings + final settingsLocalDatasource = SettingsLocalDatasource(); + final taxModel = await settingsLocalDatasource.getTax(); + final serviceChargeValue = await settingsLocalDatasource.getServiceCharge(); + + // Create a test print model + final testPrinter = PrintModel( + code: 'receipt', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + // Generate test print data + final testPrintData = await PrintDataoutputs.instance.printOrderV3( + [], // Empty product list for test + 0, + 0, + 'Test', + 0, + 0, + 0, + 0, + 0, + 1, + 'Test Cashier', + 'Test Customer', + int.parse(paper), + taxPercentage: taxModel.value, + serviceChargePercentage: serviceChargeValue, + ); + + // Print test + await PrinterService().printWithPrinter( + testPrinter, + testPrintData, + context, + ); + } catch (e) { + log("Error test printing: $e"); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error test printing: $e')), + ); + } + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Please fill in printer details first')), + ); + } + }, + label: 'Test Print' + ), + SpaceHeight(8), + // button save + data == null + ? BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterReceiptEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + code: 'receipt', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + + context.read().add( + CreatePrinterEvent.createPrinter( + printData), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ) + : BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + final snackBar = SnackBar( + content: Text(message), + backgroundColor: AppColors.primary, + ); + ScaffoldMessenger.of(context) + .showSnackBar(snackBar); + context + .read() + .add(GetPrinterReceiptEvent.get()); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return Button.filled( + onPressed: () { + final printData = PrintModel( + id: data.id, + code: 'receipt', + name: printNameController!.text, + address: addressController!.text, + paper: paper, + type: selectedPrinter, + ); + log("Print Data : ${printData.toMap()}"); + + context.read().add( + UpdatePrinterEvent.updatePrinter( + printData, + ), + ); + }, + label: 'Save', + ); + }, + loading: () { + return CircularProgressIndicator(); + }, + ); + }, + ), + SpaceHeight(16), + ], + ), + ); + }, + ); + }, + )); + } +} diff --git a/lib/presentation/setting/widgets/settings_title.dart b/lib/presentation/setting/widgets/settings_title.dart new file mode 100644 index 0000000..00e30b1 --- /dev/null +++ b/lib/presentation/setting/widgets/settings_title.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; + +import '../../../core/components/search_input.dart'; +import '../../../core/constants/colors.dart'; + + + +class SettingsTitle extends StatelessWidget { + final String title; + final TextEditingController? controller; + final Function(String value)? onChanged; + + const SettingsTitle( + this.title, { + super.key, + this.controller, + this.onChanged, + }); + + @override + Widget build(BuildContext context) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + title, + style: const TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + if (controller != null) + SizedBox( + width: 300.0, + child: SearchInput( + controller: controller!, + onChanged: onChanged, + hintText: 'Search for food, coffe, etc..', + ), + ), + ], + ); + } +} diff --git a/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.dart b/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.dart new file mode 100644 index 0000000..fdb1b3f --- /dev/null +++ b/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.dart @@ -0,0 +1,21 @@ +import 'dart:ui'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'change_position_table_event.dart'; +part 'change_position_table_state.dart'; +part 'change_position_table_bloc.freezed.dart'; + +class ChangePositionTableBloc + extends Bloc { + ChangePositionTableBloc() : super(_Initial()) { + on<_ChangePositionTable>((event, emit) async { + emit(_Loading()); + await ProductLocalDatasource.instance + .changePositionTable(event.tableId, event.position); + emit(_Success('Generate Success')); + }); + } +} diff --git a/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.freezed.dart b/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.freezed.dart new file mode 100644 index 0000000..9e0cb6d --- /dev/null +++ b/lib/presentation/table/blocs/change_position_table/change_position_table_bloc.freezed.dart @@ -0,0 +1,777 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'change_position_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$ChangePositionTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableId, Offset position) changePositionTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableId, Offset position)? changePositionTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableId, Offset position)? changePositionTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_ChangePositionTable value) changePositionTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_ChangePositionTable value)? changePositionTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_ChangePositionTable value)? changePositionTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ChangePositionTableEventCopyWith<$Res> { + factory $ChangePositionTableEventCopyWith(ChangePositionTableEvent value, + $Res Function(ChangePositionTableEvent) then) = + _$ChangePositionTableEventCopyWithImpl<$Res, ChangePositionTableEvent>; +} + +/// @nodoc +class _$ChangePositionTableEventCopyWithImpl<$Res, + $Val extends ChangePositionTableEvent> + implements $ChangePositionTableEventCopyWith<$Res> { + _$ChangePositionTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ChangePositionTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$ChangePositionTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of ChangePositionTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'ChangePositionTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableId, Offset position) changePositionTable, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableId, Offset position)? changePositionTable, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableId, Offset position)? changePositionTable, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_ChangePositionTable value) changePositionTable, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_ChangePositionTable value)? changePositionTable, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_ChangePositionTable value)? changePositionTable, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements ChangePositionTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$ChangePositionTableImplCopyWith<$Res> { + factory _$$ChangePositionTableImplCopyWith(_$ChangePositionTableImpl value, + $Res Function(_$ChangePositionTableImpl) then) = + __$$ChangePositionTableImplCopyWithImpl<$Res>; + @useResult + $Res call({int tableId, Offset position}); +} + +/// @nodoc +class __$$ChangePositionTableImplCopyWithImpl<$Res> + extends _$ChangePositionTableEventCopyWithImpl<$Res, + _$ChangePositionTableImpl> + implements _$$ChangePositionTableImplCopyWith<$Res> { + __$$ChangePositionTableImplCopyWithImpl(_$ChangePositionTableImpl _value, + $Res Function(_$ChangePositionTableImpl) _then) + : super(_value, _then); + + /// Create a copy of ChangePositionTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tableId = null, + Object? position = null, + }) { + return _then(_$ChangePositionTableImpl( + tableId: null == tableId + ? _value.tableId + : tableId // ignore: cast_nullable_to_non_nullable + as int, + position: null == position + ? _value.position + : position // ignore: cast_nullable_to_non_nullable + as Offset, + )); + } +} + +/// @nodoc + +class _$ChangePositionTableImpl implements _ChangePositionTable { + const _$ChangePositionTableImpl( + {required this.tableId, required this.position}); + + @override + final int tableId; + @override + final Offset position; + + @override + String toString() { + return 'ChangePositionTableEvent.changePositionTable(tableId: $tableId, position: $position)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChangePositionTableImpl && + (identical(other.tableId, tableId) || other.tableId == tableId) && + (identical(other.position, position) || + other.position == position)); + } + + @override + int get hashCode => Object.hash(runtimeType, tableId, position); + + /// Create a copy of ChangePositionTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$ChangePositionTableImplCopyWith<_$ChangePositionTableImpl> get copyWith => + __$$ChangePositionTableImplCopyWithImpl<_$ChangePositionTableImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int tableId, Offset position) changePositionTable, + }) { + return changePositionTable(tableId, position); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int tableId, Offset position)? changePositionTable, + }) { + return changePositionTable?.call(tableId, position); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int tableId, Offset position)? changePositionTable, + required TResult orElse(), + }) { + if (changePositionTable != null) { + return changePositionTable(tableId, position); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_ChangePositionTable value) changePositionTable, + }) { + return changePositionTable(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_ChangePositionTable value)? changePositionTable, + }) { + return changePositionTable?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_ChangePositionTable value)? changePositionTable, + required TResult orElse(), + }) { + if (changePositionTable != null) { + return changePositionTable(this); + } + return orElse(); + } +} + +abstract class _ChangePositionTable implements ChangePositionTableEvent { + const factory _ChangePositionTable( + {required final int tableId, + required final Offset position}) = _$ChangePositionTableImpl; + + int get tableId; + Offset get position; + + /// Create a copy of ChangePositionTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$ChangePositionTableImplCopyWith<_$ChangePositionTableImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$ChangePositionTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ChangePositionTableStateCopyWith<$Res> { + factory $ChangePositionTableStateCopyWith(ChangePositionTableState value, + $Res Function(ChangePositionTableState) then) = + _$ChangePositionTableStateCopyWithImpl<$Res, ChangePositionTableState>; +} + +/// @nodoc +class _$ChangePositionTableStateCopyWithImpl<$Res, + $Val extends ChangePositionTableState> + implements $ChangePositionTableStateCopyWith<$Res> { + _$ChangePositionTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$ChangePositionTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'ChangePositionTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements ChangePositionTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$ChangePositionTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'ChangePositionTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements ChangePositionTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$ChangePositionTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'ChangePositionTableState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements ChangePositionTableState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of ChangePositionTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/table/blocs/change_position_table/change_position_table_event.dart b/lib/presentation/table/blocs/change_position_table/change_position_table_event.dart new file mode 100644 index 0000000..3b58a34 --- /dev/null +++ b/lib/presentation/table/blocs/change_position_table/change_position_table_event.dart @@ -0,0 +1,10 @@ +part of 'change_position_table_bloc.dart'; + +@freezed +class ChangePositionTableEvent with _$ChangePositionTableEvent { + const factory ChangePositionTableEvent.started() = _Started; + const factory ChangePositionTableEvent.changePositionTable({ + required int tableId, + required Offset position, + }) = _ChangePositionTable; +} diff --git a/lib/presentation/table/blocs/change_position_table/change_position_table_state.dart b/lib/presentation/table/blocs/change_position_table/change_position_table_state.dart new file mode 100644 index 0000000..5fb037b --- /dev/null +++ b/lib/presentation/table/blocs/change_position_table/change_position_table_state.dart @@ -0,0 +1,10 @@ +part of 'change_position_table_bloc.dart'; + +@freezed +class ChangePositionTableState with _$ChangePositionTableState { + const factory ChangePositionTableState.initial() = _Initial; + + const factory ChangePositionTableState.loading() = _Loading; + + const factory ChangePositionTableState.success(String message) = _Success; +} diff --git a/lib/presentation/table/blocs/create_table/create_table_bloc.dart b/lib/presentation/table/blocs/create_table/create_table_bloc.dart new file mode 100644 index 0000000..ecdd58c --- /dev/null +++ b/lib/presentation/table/blocs/create_table/create_table_bloc.dart @@ -0,0 +1,20 @@ +import 'dart:ui'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'create_table_event.dart'; +part 'create_table_state.dart'; +part 'create_table_bloc.freezed.dart'; + +class CreateTableBloc extends Bloc { + CreateTableBloc() : super(_Initial()) { + on<_CreateTable>((event, emit) async { + emit(_Loading()); + await ProductLocalDatasource.instance + .createTableManagement(event.tableName, event.position); + emit(_Success('Create Table Success')); + }); + } +} diff --git a/lib/presentation/table/blocs/create_table/create_table_bloc.freezed.dart b/lib/presentation/table/blocs/create_table/create_table_bloc.freezed.dart new file mode 100644 index 0000000..707ba61 --- /dev/null +++ b/lib/presentation/table/blocs/create_table/create_table_bloc.freezed.dart @@ -0,0 +1,772 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'create_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$CreateTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String tableName, Offset position) createTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String tableName, Offset position)? createTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String tableName, Offset position)? createTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreateTable value) createTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreateTable value)? createTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreateTable value)? createTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CreateTableEventCopyWith<$Res> { + factory $CreateTableEventCopyWith( + CreateTableEvent value, $Res Function(CreateTableEvent) then) = + _$CreateTableEventCopyWithImpl<$Res, CreateTableEvent>; +} + +/// @nodoc +class _$CreateTableEventCopyWithImpl<$Res, $Val extends CreateTableEvent> + implements $CreateTableEventCopyWith<$Res> { + _$CreateTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CreateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$CreateTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of CreateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'CreateTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String tableName, Offset position) createTable, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String tableName, Offset position)? createTable, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String tableName, Offset position)? createTable, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreateTable value) createTable, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreateTable value)? createTable, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreateTable value)? createTable, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements CreateTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$CreateTableImplCopyWith<$Res> { + factory _$$CreateTableImplCopyWith( + _$CreateTableImpl value, $Res Function(_$CreateTableImpl) then) = + __$$CreateTableImplCopyWithImpl<$Res>; + @useResult + $Res call({String tableName, Offset position}); +} + +/// @nodoc +class __$$CreateTableImplCopyWithImpl<$Res> + extends _$CreateTableEventCopyWithImpl<$Res, _$CreateTableImpl> + implements _$$CreateTableImplCopyWith<$Res> { + __$$CreateTableImplCopyWithImpl( + _$CreateTableImpl _value, $Res Function(_$CreateTableImpl) _then) + : super(_value, _then); + + /// Create a copy of CreateTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tableName = null, + Object? position = null, + }) { + return _then(_$CreateTableImpl( + null == tableName + ? _value.tableName + : tableName // ignore: cast_nullable_to_non_nullable + as String, + null == position + ? _value.position + : position // ignore: cast_nullable_to_non_nullable + as Offset, + )); + } +} + +/// @nodoc + +class _$CreateTableImpl implements _CreateTable { + const _$CreateTableImpl(this.tableName, this.position); + + @override + final String tableName; + @override + final Offset position; + + @override + String toString() { + return 'CreateTableEvent.createTable(tableName: $tableName, position: $position)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$CreateTableImpl && + (identical(other.tableName, tableName) || + other.tableName == tableName) && + (identical(other.position, position) || + other.position == position)); + } + + @override + int get hashCode => Object.hash(runtimeType, tableName, position); + + /// Create a copy of CreateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$CreateTableImplCopyWith<_$CreateTableImpl> get copyWith => + __$$CreateTableImplCopyWithImpl<_$CreateTableImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(String tableName, Offset position) createTable, + }) { + return createTable(tableName, position); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(String tableName, Offset position)? createTable, + }) { + return createTable?.call(tableName, position); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(String tableName, Offset position)? createTable, + required TResult orElse(), + }) { + if (createTable != null) { + return createTable(tableName, position); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_CreateTable value) createTable, + }) { + return createTable(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_CreateTable value)? createTable, + }) { + return createTable?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_CreateTable value)? createTable, + required TResult orElse(), + }) { + if (createTable != null) { + return createTable(this); + } + return orElse(); + } +} + +abstract class _CreateTable implements CreateTableEvent { + const factory _CreateTable(final String tableName, final Offset position) = + _$CreateTableImpl; + + String get tableName; + Offset get position; + + /// Create a copy of CreateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$CreateTableImplCopyWith<_$CreateTableImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$CreateTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $CreateTableStateCopyWith<$Res> { + factory $CreateTableStateCopyWith( + CreateTableState value, $Res Function(CreateTableState) then) = + _$CreateTableStateCopyWithImpl<$Res, CreateTableState>; +} + +/// @nodoc +class _$CreateTableStateCopyWithImpl<$Res, $Val extends CreateTableState> + implements $CreateTableStateCopyWith<$Res> { + _$CreateTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$CreateTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'CreateTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements CreateTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$CreateTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'CreateTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements CreateTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$CreateTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'CreateTableState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements CreateTableState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of CreateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/table/blocs/create_table/create_table_event.dart b/lib/presentation/table/blocs/create_table/create_table_event.dart new file mode 100644 index 0000000..1278f35 --- /dev/null +++ b/lib/presentation/table/blocs/create_table/create_table_event.dart @@ -0,0 +1,8 @@ +part of 'create_table_bloc.dart'; + +@freezed +class CreateTableEvent with _$CreateTableEvent { + const factory CreateTableEvent.started() = _Started; + const factory CreateTableEvent.createTable( + String tableName, Offset position) = _CreateTable; +} diff --git a/lib/presentation/table/blocs/create_table/create_table_state.dart b/lib/presentation/table/blocs/create_table/create_table_state.dart new file mode 100644 index 0000000..e697088 --- /dev/null +++ b/lib/presentation/table/blocs/create_table/create_table_state.dart @@ -0,0 +1,10 @@ +part of 'create_table_bloc.dart'; + +@freezed +class CreateTableState with _$CreateTableState { + const factory CreateTableState.initial() = _Initial; + // loading + const factory CreateTableState.loading() = _Loading; + // success + const factory CreateTableState.success(String message) = _Success; +} diff --git a/lib/presentation/table/blocs/generate_table/generate_table_bloc.dart b/lib/presentation/table/blocs/generate_table/generate_table_bloc.dart new file mode 100644 index 0000000..ba70da5 --- /dev/null +++ b/lib/presentation/table/blocs/generate_table/generate_table_bloc.dart @@ -0,0 +1,19 @@ +import 'package:bloc/bloc.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'generate_table_event.dart'; +part 'generate_table_state.dart'; +part 'generate_table_bloc.freezed.dart'; + +class GenerateTableBloc extends Bloc { + GenerateTableBloc() : super(_Initial()) { + on<_Generate>((event, emit) async { + emit(_Loading()); + // await ProductLocalDatasource.instance + // .createTableManagement(event.count); + emit(_Success('Generate Success')); + }); + } +} diff --git a/lib/presentation/table/blocs/generate_table/generate_table_bloc.freezed.dart b/lib/presentation/table/blocs/generate_table/generate_table_bloc.freezed.dart new file mode 100644 index 0000000..a85f5d7 --- /dev/null +++ b/lib/presentation/table/blocs/generate_table/generate_table_bloc.freezed.dart @@ -0,0 +1,760 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'generate_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GenerateTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int count) generate, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int count)? generate, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int count)? generate, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Generate value) generate, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Generate value)? generate, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Generate value)? generate, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GenerateTableEventCopyWith<$Res> { + factory $GenerateTableEventCopyWith( + GenerateTableEvent value, $Res Function(GenerateTableEvent) then) = + _$GenerateTableEventCopyWithImpl<$Res, GenerateTableEvent>; +} + +/// @nodoc +class _$GenerateTableEventCopyWithImpl<$Res, $Val extends GenerateTableEvent> + implements $GenerateTableEventCopyWith<$Res> { + _$GenerateTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GenerateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GenerateTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GenerateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GenerateTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int count) generate, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int count)? generate, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int count)? generate, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Generate value) generate, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Generate value)? generate, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Generate value)? generate, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GenerateTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GenerateImplCopyWith<$Res> { + factory _$$GenerateImplCopyWith( + _$GenerateImpl value, $Res Function(_$GenerateImpl) then) = + __$$GenerateImplCopyWithImpl<$Res>; + @useResult + $Res call({int count}); +} + +/// @nodoc +class __$$GenerateImplCopyWithImpl<$Res> + extends _$GenerateTableEventCopyWithImpl<$Res, _$GenerateImpl> + implements _$$GenerateImplCopyWith<$Res> { + __$$GenerateImplCopyWithImpl( + _$GenerateImpl _value, $Res Function(_$GenerateImpl) _then) + : super(_value, _then); + + /// Create a copy of GenerateTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? count = null, + }) { + return _then(_$GenerateImpl( + null == count + ? _value.count + : count // ignore: cast_nullable_to_non_nullable + as int, + )); + } +} + +/// @nodoc + +class _$GenerateImpl implements _Generate { + const _$GenerateImpl(this.count); + + @override + final int count; + + @override + String toString() { + return 'GenerateTableEvent.generate(count: $count)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$GenerateImpl && + (identical(other.count, count) || other.count == count)); + } + + @override + int get hashCode => Object.hash(runtimeType, count); + + /// Create a copy of GenerateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$GenerateImplCopyWith<_$GenerateImpl> get copyWith => + __$$GenerateImplCopyWithImpl<_$GenerateImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(int count) generate, + }) { + return generate(count); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(int count)? generate, + }) { + return generate?.call(count); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(int count)? generate, + required TResult orElse(), + }) { + if (generate != null) { + return generate(count); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_Generate value) generate, + }) { + return generate(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_Generate value)? generate, + }) { + return generate?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_Generate value)? generate, + required TResult orElse(), + }) { + if (generate != null) { + return generate(this); + } + return orElse(); + } +} + +abstract class _Generate implements GenerateTableEvent { + const factory _Generate(final int count) = _$GenerateImpl; + + int get count; + + /// Create a copy of GenerateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$GenerateImplCopyWith<_$GenerateImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$GenerateTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GenerateTableStateCopyWith<$Res> { + factory $GenerateTableStateCopyWith( + GenerateTableState value, $Res Function(GenerateTableState) then) = + _$GenerateTableStateCopyWithImpl<$Res, GenerateTableState>; +} + +/// @nodoc +class _$GenerateTableStateCopyWithImpl<$Res, $Val extends GenerateTableState> + implements $GenerateTableStateCopyWith<$Res> { + _$GenerateTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GenerateTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GenerateTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GenerateTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GenerateTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GenerateTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GenerateTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GenerateTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'GenerateTableState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GenerateTableState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of GenerateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/table/blocs/generate_table/generate_table_event.dart b/lib/presentation/table/blocs/generate_table/generate_table_event.dart new file mode 100644 index 0000000..2fd38fa --- /dev/null +++ b/lib/presentation/table/blocs/generate_table/generate_table_event.dart @@ -0,0 +1,7 @@ +part of 'generate_table_bloc.dart'; + +@freezed +class GenerateTableEvent with _$GenerateTableEvent { + const factory GenerateTableEvent.started() = _Started; + const factory GenerateTableEvent.generate(int count) = _Generate; +} diff --git a/lib/presentation/table/blocs/generate_table/generate_table_state.dart b/lib/presentation/table/blocs/generate_table/generate_table_state.dart new file mode 100644 index 0000000..6d51797 --- /dev/null +++ b/lib/presentation/table/blocs/generate_table/generate_table_state.dart @@ -0,0 +1,8 @@ +part of 'generate_table_bloc.dart'; + +@freezed +class GenerateTableState with _$GenerateTableState { + const factory GenerateTableState.initial() = _Initial; + const factory GenerateTableState.loading() = _Loading; + const factory GenerateTableState.success(String message) = _Success; +} diff --git a/lib/presentation/table/blocs/get_table/get_table_bloc.dart b/lib/presentation/table/blocs/get_table/get_table_bloc.dart new file mode 100644 index 0000000..84c3d76 --- /dev/null +++ b/lib/presentation/table/blocs/get_table/get_table_bloc.dart @@ -0,0 +1,18 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'get_table_event.dart'; +part 'get_table_state.dart'; +part 'get_table_bloc.freezed.dart'; + +class GetTableBloc extends Bloc { + GetTableBloc() : super(_Initial()) { + on<_GetTables>((event, emit) async { + emit(_Loading()); + final tables = await ProductLocalDatasource.instance.getAllTable(); + emit(_Success(tables)); + }); + } +} diff --git a/lib/presentation/table/blocs/get_table/get_table_bloc.freezed.dart b/lib/presentation/table/blocs/get_table/get_table_bloc.freezed.dart new file mode 100644 index 0000000..332d5f8 --- /dev/null +++ b/lib/presentation/table/blocs/get_table/get_table_bloc.freezed.dart @@ -0,0 +1,731 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'get_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$GetTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getTables, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getTables, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getTables, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTables value) getTables, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTables value)? getTables, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTables value)? getTables, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetTableEventCopyWith<$Res> { + factory $GetTableEventCopyWith( + GetTableEvent value, $Res Function(GetTableEvent) then) = + _$GetTableEventCopyWithImpl<$Res, GetTableEvent>; +} + +/// @nodoc +class _$GetTableEventCopyWithImpl<$Res, $Val extends GetTableEvent> + implements $GetTableEventCopyWith<$Res> { + _$GetTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$GetTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'GetTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getTables, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getTables, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getTables, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTables value) getTables, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTables value)? getTables, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTables value)? getTables, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements GetTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$GetTablesImplCopyWith<$Res> { + factory _$$GetTablesImplCopyWith( + _$GetTablesImpl value, $Res Function(_$GetTablesImpl) then) = + __$$GetTablesImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$GetTablesImplCopyWithImpl<$Res> + extends _$GetTableEventCopyWithImpl<$Res, _$GetTablesImpl> + implements _$$GetTablesImplCopyWith<$Res> { + __$$GetTablesImplCopyWithImpl( + _$GetTablesImpl _value, $Res Function(_$GetTablesImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$GetTablesImpl implements _GetTables { + const _$GetTablesImpl(); + + @override + String toString() { + return 'GetTableEvent.getTables()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$GetTablesImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function() getTables, + }) { + return getTables(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function()? getTables, + }) { + return getTables?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function()? getTables, + required TResult orElse(), + }) { + if (getTables != null) { + return getTables(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_GetTables value) getTables, + }) { + return getTables(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_GetTables value)? getTables, + }) { + return getTables?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_GetTables value)? getTables, + required TResult orElse(), + }) { + if (getTables != null) { + return getTables(this); + } + return orElse(); + } +} + +abstract class _GetTables implements GetTableEvent { + const factory _GetTables() = _$GetTablesImpl; +} + +/// @nodoc +mixin _$GetTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $GetTableStateCopyWith<$Res> { + factory $GetTableStateCopyWith( + GetTableState value, $Res Function(GetTableState) then) = + _$GetTableStateCopyWithImpl<$Res, GetTableState>; +} + +/// @nodoc +class _$GetTableStateCopyWithImpl<$Res, $Val extends GetTableState> + implements $GetTableStateCopyWith<$Res> { + _$GetTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$GetTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'GetTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements GetTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$GetTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'GetTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements GetTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({List tables}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$GetTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tables = null, + }) { + return _then(_$SuccessImpl( + null == tables + ? _value._tables + : tables // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(final List tables) : _tables = tables; + + final List _tables; + @override + List get tables { + if (_tables is EqualUnmodifiableListView) return _tables; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_tables); + } + + @override + String toString() { + return 'GetTableState.success(tables: $tables)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + const DeepCollectionEquality().equals(other._tables, _tables)); + } + + @override + int get hashCode => + Object.hash(runtimeType, const DeepCollectionEquality().hash(_tables)); + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(List tables) success, + }) { + return success(tables); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(List tables)? success, + }) { + return success?.call(tables); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(List tables)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(tables); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements GetTableState { + const factory _Success(final List tables) = _$SuccessImpl; + + List get tables; + + /// Create a copy of GetTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/table/blocs/get_table/get_table_event.dart b/lib/presentation/table/blocs/get_table/get_table_event.dart new file mode 100644 index 0000000..4d361f9 --- /dev/null +++ b/lib/presentation/table/blocs/get_table/get_table_event.dart @@ -0,0 +1,7 @@ +part of 'get_table_bloc.dart'; + +@freezed +class GetTableEvent with _$GetTableEvent { + const factory GetTableEvent.started() = _Started; + const factory GetTableEvent.getTables() = _GetTables; +} diff --git a/lib/presentation/table/blocs/get_table/get_table_state.dart b/lib/presentation/table/blocs/get_table/get_table_state.dart new file mode 100644 index 0000000..ef24094 --- /dev/null +++ b/lib/presentation/table/blocs/get_table/get_table_state.dart @@ -0,0 +1,8 @@ +part of 'get_table_bloc.dart'; + +@freezed +class GetTableState with _$GetTableState { + const factory GetTableState.initial() = _Initial; + const factory GetTableState.loading() = _Loading; + const factory GetTableState.success(List tables) = _Success; +} diff --git a/lib/presentation/table/blocs/update_table/update_table_bloc.dart b/lib/presentation/table/blocs/update_table/update_table_bloc.dart new file mode 100644 index 0000000..aec6e7c --- /dev/null +++ b/lib/presentation/table/blocs/update_table/update_table_bloc.dart @@ -0,0 +1,22 @@ +import 'dart:async'; + +import 'package:bloc/bloc.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'update_table_event.dart'; +part 'update_table_state.dart'; +part 'update_table_bloc.freezed.dart'; + +class UpdateTableBloc extends Bloc { + UpdateTableBloc() : super(_Initial()) { + on<_UpdateTable>((event, emit) async { + emit(_Loading()); + await ProductLocalDatasource.instance.updateTable( + event.table, + ); + emit(_Success('Update Table Success')); + }); + } +} diff --git a/lib/presentation/table/blocs/update_table/update_table_bloc.freezed.dart b/lib/presentation/table/blocs/update_table/update_table_bloc.freezed.dart new file mode 100644 index 0000000..8607432 --- /dev/null +++ b/lib/presentation/table/blocs/update_table/update_table_bloc.freezed.dart @@ -0,0 +1,760 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'update_table_bloc.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$UpdateTableEvent { + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) updateTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? updateTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? updateTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdateTable value) updateTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdateTable value)? updateTable, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdateTable value)? updateTable, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdateTableEventCopyWith<$Res> { + factory $UpdateTableEventCopyWith( + UpdateTableEvent value, $Res Function(UpdateTableEvent) then) = + _$UpdateTableEventCopyWithImpl<$Res, UpdateTableEvent>; +} + +/// @nodoc +class _$UpdateTableEventCopyWithImpl<$Res, $Val extends UpdateTableEvent> + implements $UpdateTableEventCopyWith<$Res> { + _$UpdateTableEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$StartedImplCopyWith<$Res> { + factory _$$StartedImplCopyWith( + _$StartedImpl value, $Res Function(_$StartedImpl) then) = + __$$StartedImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$StartedImplCopyWithImpl<$Res> + extends _$UpdateTableEventCopyWithImpl<$Res, _$StartedImpl> + implements _$$StartedImplCopyWith<$Res> { + __$$StartedImplCopyWithImpl( + _$StartedImpl _value, $Res Function(_$StartedImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateTableEvent + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$StartedImpl implements _Started { + const _$StartedImpl(); + + @override + String toString() { + return 'UpdateTableEvent.started()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$StartedImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) updateTable, + }) { + return started(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? updateTable, + }) { + return started?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? updateTable, + required TResult orElse(), + }) { + if (started != null) { + return started(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdateTable value) updateTable, + }) { + return started(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdateTable value)? updateTable, + }) { + return started?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdateTable value)? updateTable, + required TResult orElse(), + }) { + if (started != null) { + return started(this); + } + return orElse(); + } +} + +abstract class _Started implements UpdateTableEvent { + const factory _Started() = _$StartedImpl; +} + +/// @nodoc +abstract class _$$UpdateTableImplCopyWith<$Res> { + factory _$$UpdateTableImplCopyWith( + _$UpdateTableImpl value, $Res Function(_$UpdateTableImpl) then) = + __$$UpdateTableImplCopyWithImpl<$Res>; + @useResult + $Res call({TableModel table}); +} + +/// @nodoc +class __$$UpdateTableImplCopyWithImpl<$Res> + extends _$UpdateTableEventCopyWithImpl<$Res, _$UpdateTableImpl> + implements _$$UpdateTableImplCopyWith<$Res> { + __$$UpdateTableImplCopyWithImpl( + _$UpdateTableImpl _value, $Res Function(_$UpdateTableImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateTableEvent + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? table = null, + }) { + return _then(_$UpdateTableImpl( + null == table + ? _value.table + : table // ignore: cast_nullable_to_non_nullable + as TableModel, + )); + } +} + +/// @nodoc + +class _$UpdateTableImpl implements _UpdateTable { + const _$UpdateTableImpl(this.table); + + @override + final TableModel table; + + @override + String toString() { + return 'UpdateTableEvent.updateTable(table: $table)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$UpdateTableImpl && + (identical(other.table, table) || other.table == table)); + } + + @override + int get hashCode => Object.hash(runtimeType, table); + + /// Create a copy of UpdateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$UpdateTableImplCopyWith<_$UpdateTableImpl> get copyWith => + __$$UpdateTableImplCopyWithImpl<_$UpdateTableImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() started, + required TResult Function(TableModel table) updateTable, + }) { + return updateTable(table); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? started, + TResult? Function(TableModel table)? updateTable, + }) { + return updateTable?.call(table); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? started, + TResult Function(TableModel table)? updateTable, + required TResult orElse(), + }) { + if (updateTable != null) { + return updateTable(table); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Started value) started, + required TResult Function(_UpdateTable value) updateTable, + }) { + return updateTable(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Started value)? started, + TResult? Function(_UpdateTable value)? updateTable, + }) { + return updateTable?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Started value)? started, + TResult Function(_UpdateTable value)? updateTable, + required TResult orElse(), + }) { + if (updateTable != null) { + return updateTable(this); + } + return orElse(); + } +} + +abstract class _UpdateTable implements UpdateTableEvent { + const factory _UpdateTable(final TableModel table) = _$UpdateTableImpl; + + TableModel get table; + + /// Create a copy of UpdateTableEvent + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$UpdateTableImplCopyWith<_$UpdateTableImpl> get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$UpdateTableState { + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $UpdateTableStateCopyWith<$Res> { + factory $UpdateTableStateCopyWith( + UpdateTableState value, $Res Function(UpdateTableState) then) = + _$UpdateTableStateCopyWithImpl<$Res, UpdateTableState>; +} + +/// @nodoc +class _$UpdateTableStateCopyWithImpl<$Res, $Val extends UpdateTableState> + implements $UpdateTableStateCopyWith<$Res> { + _$UpdateTableStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc +abstract class _$$InitialImplCopyWith<$Res> { + factory _$$InitialImplCopyWith( + _$InitialImpl value, $Res Function(_$InitialImpl) then) = + __$$InitialImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$InitialImplCopyWithImpl<$Res> + extends _$UpdateTableStateCopyWithImpl<$Res, _$InitialImpl> + implements _$$InitialImplCopyWith<$Res> { + __$$InitialImplCopyWithImpl( + _$InitialImpl _value, $Res Function(_$InitialImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$InitialImpl implements _Initial { + const _$InitialImpl(); + + @override + String toString() { + return 'UpdateTableState.initial()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$InitialImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return initial(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return initial?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return initial(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return initial?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (initial != null) { + return initial(this); + } + return orElse(); + } +} + +abstract class _Initial implements UpdateTableState { + const factory _Initial() = _$InitialImpl; +} + +/// @nodoc +abstract class _$$LoadingImplCopyWith<$Res> { + factory _$$LoadingImplCopyWith( + _$LoadingImpl value, $Res Function(_$LoadingImpl) then) = + __$$LoadingImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$LoadingImplCopyWithImpl<$Res> + extends _$UpdateTableStateCopyWithImpl<$Res, _$LoadingImpl> + implements _$$LoadingImplCopyWith<$Res> { + __$$LoadingImplCopyWithImpl( + _$LoadingImpl _value, $Res Function(_$LoadingImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. +} + +/// @nodoc + +class _$LoadingImpl implements _Loading { + const _$LoadingImpl(); + + @override + String toString() { + return 'UpdateTableState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _$LoadingImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class _Loading implements UpdateTableState { + const factory _Loading() = _$LoadingImpl; +} + +/// @nodoc +abstract class _$$SuccessImplCopyWith<$Res> { + factory _$$SuccessImplCopyWith( + _$SuccessImpl value, $Res Function(_$SuccessImpl) then) = + __$$SuccessImplCopyWithImpl<$Res>; + @useResult + $Res call({String message}); +} + +/// @nodoc +class __$$SuccessImplCopyWithImpl<$Res> + extends _$UpdateTableStateCopyWithImpl<$Res, _$SuccessImpl> + implements _$$SuccessImplCopyWith<$Res> { + __$$SuccessImplCopyWithImpl( + _$SuccessImpl _value, $Res Function(_$SuccessImpl) _then) + : super(_value, _then); + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? message = null, + }) { + return _then(_$SuccessImpl( + null == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$SuccessImpl implements _Success { + const _$SuccessImpl(this.message); + + @override + final String message; + + @override + String toString() { + return 'UpdateTableState.success(message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SuccessImpl && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode => Object.hash(runtimeType, message); + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + __$$SuccessImplCopyWithImpl<_$SuccessImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initial, + required TResult Function() loading, + required TResult Function(String message) success, + }) { + return success(message); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initial, + TResult? Function()? loading, + TResult? Function(String message)? success, + }) { + return success?.call(message); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initial, + TResult Function()? loading, + TResult Function(String message)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(message); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(_Initial value) initial, + required TResult Function(_Loading value) loading, + required TResult Function(_Success value) success, + }) { + return success(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_Initial value)? initial, + TResult? Function(_Loading value)? loading, + TResult? Function(_Success value)? success, + }) { + return success?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_Initial value)? initial, + TResult Function(_Loading value)? loading, + TResult Function(_Success value)? success, + required TResult orElse(), + }) { + if (success != null) { + return success(this); + } + return orElse(); + } +} + +abstract class _Success implements UpdateTableState { + const factory _Success(final String message) = _$SuccessImpl; + + String get message; + + /// Create a copy of UpdateTableState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SuccessImplCopyWith<_$SuccessImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/presentation/table/blocs/update_table/update_table_event.dart b/lib/presentation/table/blocs/update_table/update_table_event.dart new file mode 100644 index 0000000..b1889ba --- /dev/null +++ b/lib/presentation/table/blocs/update_table/update_table_event.dart @@ -0,0 +1,7 @@ +part of 'update_table_bloc.dart'; + +@freezed +class UpdateTableEvent with _$UpdateTableEvent { + const factory UpdateTableEvent.started() = _Started; + const factory UpdateTableEvent.updateTable(TableModel table) = _UpdateTable; +} diff --git a/lib/presentation/table/blocs/update_table/update_table_state.dart b/lib/presentation/table/blocs/update_table/update_table_state.dart new file mode 100644 index 0000000..10f0e08 --- /dev/null +++ b/lib/presentation/table/blocs/update_table/update_table_state.dart @@ -0,0 +1,8 @@ +part of 'update_table_bloc.dart'; + +@freezed +class UpdateTableState with _$UpdateTableState { + const factory UpdateTableState.initial() = _Initial; + const factory UpdateTableState.loading() = _Loading; + const factory UpdateTableState.success(String message) = _Success; +} diff --git a/lib/presentation/table/dialogs/form_table_dialog.dart b/lib/presentation/table/dialogs/form_table_dialog.dart new file mode 100644 index 0000000..347a0b5 --- /dev/null +++ b/lib/presentation/table/dialogs/form_table_dialog.dart @@ -0,0 +1,86 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/custom_text_field.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/presentation/table/blocs/generate_table/generate_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; + +class FormTableDialog extends StatefulWidget { + const FormTableDialog({ + super.key, + }); + + @override + State createState() => _FormTableDialogState(); +} + +class _FormTableDialogState extends State { + final generateController = TextEditingController(); + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + IconButton( + onPressed: () => context.pop(), + icon: const Icon(Icons.close), + ), + const Text('Tambah Table'), + const Spacer(), + ], + ), + content: SingleChildScrollView( + child: SizedBox( + width: context.deviceWidth / 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + CustomTextField( + controller: generateController, + label: 'Jumlah Table', + onChanged: (value) {}, + keyboardType: TextInputType.number, + ), + const SpaceHeight(24.0), + BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + context + .read() + .add(const GetTableEvent.getTables()); + context.pop(); + }, + ); + }, + builder: (context, state) { + return state.maybeWhen(orElse: () { + return Button.filled( + onPressed: () { + context.read().add( + GenerateTableEvent.generate( + int.parse(generateController.text), + ), + ); + }, + label: 'Generate', + ); + }, loading: () { + return const Center( + child: CircularProgressIndicator(), + ); + }); + }, + ) + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/table/models/draft_order_item.dart b/lib/presentation/table/models/draft_order_item.dart new file mode 100644 index 0000000..afe8d66 --- /dev/null +++ b/lib/presentation/table/models/draft_order_item.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:enaklo_pos/data/models/response/product_response_model.dart'; + +class DraftOrderItem { + final Product product; + int quantity; + DraftOrderItem({ + required this.product, + required this.quantity, + }); + + Map toMap() { + return { + 'product': product.toMap(), + 'quantity': quantity, + }; + } + + // id INTEGER PRIMARY KEY AUTOINCREMENT, + // id_order INTEGER, + // id_product INTEGER, + // quantity INTEGER, + // price INTEGER + + Map toMapForLocal(int orderId) { + return { + 'id_draft_order': orderId, + 'id_product': product.productId, + 'quantity': quantity, + 'price': product.price, + }; + } + + static OrderItemModel fromMapLocal(Map map) { + return OrderItemModel( + productId: map['id_product']?.toInt() ?? 0, + quantity: map['quantity']?.toInt() ?? 0, + totalPrice: map['price']?.toInt() ?? 0 * (map['quantity']?.toInt() ?? 0), + ); + } + + factory DraftOrderItem.fromMap(Map map) { + return DraftOrderItem( + product: Product.fromMap(map['product']), + quantity: map['quantity']?.toInt() ?? 0, + ); + } + + String toJson() => json.encode(toMap()); + + factory DraftOrderItem.fromJson(String source) => + DraftOrderItem.fromMap(json.decode(source)); +} + +class OrderItemModel { + final int productId; + final int quantity; + final int totalPrice; + + OrderItemModel({ + required this.productId, + required this.quantity, + required this.totalPrice, + }); + + factory OrderItemModel.fromJson(String str) => + OrderItemModel.fromMap(json.decode(str)); + + String toJson() => json.encode(toMap()); + + factory OrderItemModel.fromMap(Map json) => OrderItemModel( + productId: json["product_id"], + quantity: json["quantity"], + totalPrice: json["total_price"], + ); + + Map toMap() => { + "product_id": productId, + "quantity": quantity, + "total_price": totalPrice, + }; +} diff --git a/lib/presentation/table/models/draft_order_model.dart b/lib/presentation/table/models/draft_order_model.dart new file mode 100644 index 0000000..f6fd61e --- /dev/null +++ b/lib/presentation/table/models/draft_order_model.dart @@ -0,0 +1,158 @@ +import 'dart:convert'; +import 'dart:developer'; + +import 'package:enaklo_pos/presentation/table/models/draft_order_item.dart'; + +import '../../home/models/order_item.dart'; + +class DraftOrderModel { + final int? id; + final List orders; + + final int totalQuantity; + final int subTotal; + final int tax; + final int discount; + final int discountAmount; + final int serviceCharge; + final int totalPrice; + final String transactionTime; + final int tableNumber; + final String draftName; + + DraftOrderModel({ + this.id, + required this.orders, + required this.totalQuantity, + required this.subTotal, + required this.tax, + required this.discount, + required this.discountAmount, + required this.serviceCharge, + required this.totalPrice, + required this.tableNumber, + required this.draftName, + required this.transactionTime, + }); + + Map toMap() { + return { + 'orders': orders.map((x) => x.toMap()).toList(), + 'totalQuantity': totalQuantity, + 'totalPrice': totalPrice, + 'tableNumber': tableNumber, + 'draftName': draftName, + }; + } + + // mominal INTEGER, + // payment_method TEXT + // total_item INTEGER, + // id_kasir INTEGER, + // nama_kasir TEXT, + // is_sync INTEGER DEFAULT 0 + + Map toMapForLocal() { + return { + 'total_item': totalQuantity, + 'subTotal': subTotal, + 'tax': tax, + 'discount': discount, + 'discount_amount': discountAmount, + 'service_charge': serviceCharge, + 'total': totalPrice, + 'table_number': tableNumber, + 'transaction_time': transactionTime, + 'draft_name': draftName, + }; + } + + factory DraftOrderModel.fromLocalMap(Map map) { + return DraftOrderModel( + orders: [], + totalQuantity: map['total_item']?.toInt() ?? 0, + totalPrice: map['nominal']?.toInt() ?? 0, + id: map['id']?.toInt() ?? 0, + transactionTime: map['transaction_time'] ?? '', + tableNumber: map['table_number']?.toInt() ?? 0, + draftName: map['draft_name'] ?? '', + discount: map['discount']?.toInt() ?? 0, + discountAmount: map['discount_amount']?.toInt() ?? 0, + serviceCharge: map['service_charge']?.toInt() ?? 0, + subTotal: map['subTotal']?.toInt() ?? 0, + tax: map['tax']?.toInt() ?? 0, + ); + } + + factory DraftOrderModel.newFromLocalMap( + Map map, List orders) { + log("newFromLocalMap: $map"); + return DraftOrderModel( + orders: orders, + totalQuantity: map['total_item']?.toInt() ?? 0, + totalPrice: map['nominal']?.toInt() ?? 0, + id: map['id']?.toInt() ?? 0, + transactionTime: map['transaction_time'] ?? '', + tableNumber: map['table_number']?.toInt() ?? 0, + draftName: map['draft_name'] ?? '', + discount: map['discount']?.toInt() ?? 0, + discountAmount: map['discount_amount']?.toInt() ?? 0, + serviceCharge: map['service_charge']?.toInt() ?? 0, + subTotal: map['subTotal']?.toInt() ?? 0, + tax: map['tax']?.toInt() ?? 0, + ); + } + + factory DraftOrderModel.fromMap(Map map) { + return DraftOrderModel( + orders: List.from( + map['orders']?.map((x) => OrderItem.fromMap(x))), + totalQuantity: map['totalQuantity']?.toInt() ?? 0, + totalPrice: map['totalPrice']?.toInt() ?? 0, + id: map['id']?.toInt() ?? 0, + transactionTime: map['transactionTime'] ?? '', + tableNumber: map['tableNumber']?.toInt() ?? 0, + draftName: map['draftName'] ?? '', + discount: map['discount']?.toInt() ?? 0, + discountAmount: map['discountAmount']?.toInt() ?? 0, + serviceCharge: map['serviceCharge']?.toInt() ?? 0, + subTotal: map['subTotal']?.toInt() ?? 0, + tax: map['tax']?.toInt() ?? 0, + ); + } + + String toJson() => json.encode(toMap()); + + factory DraftOrderModel.fromJson(String source) => + DraftOrderModel.fromMap(json.decode(source)); + + DraftOrderModel copyWith({ + int? id, + List? orders, + int? totalQuantity, + int? subTotal, + int? tax, + int? discount, + int? discountAmount, + int? serviceCharge, + int? totalPrice, + String? transactionTime, + int? tableNumber, + String? draftName, + }) { + return DraftOrderModel( + id: id ?? this.id, + orders: orders ?? this.orders, + totalQuantity: totalQuantity ?? this.totalQuantity, + subTotal: subTotal ?? this.subTotal, + tax: tax ?? this.tax, + discount: discount ?? this.discount, + discountAmount: discountAmount ?? this.discountAmount, + serviceCharge: serviceCharge ?? this.serviceCharge, + totalPrice: totalPrice ?? this.totalPrice, + transactionTime: transactionTime ?? this.transactionTime, + tableNumber: tableNumber ?? this.tableNumber, + draftName: draftName ?? this.draftName, + ); + } +} diff --git a/lib/presentation/table/pages/new_table_management_page.dart b/lib/presentation/table/pages/new_table_management_page.dart new file mode 100644 index 0000000..95fb0d9 --- /dev/null +++ b/lib/presentation/table/pages/new_table_management_page.dart @@ -0,0 +1,187 @@ +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/table/blocs/change_position_table/change_position_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/widgets/table_widget.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:hive/hive.dart'; +import 'package:path_provider/path_provider.dart'; + +class TableManagementScreen extends StatefulWidget { + const TableManagementScreen({super.key}); + + @override + State createState() => _TableManagementScreenState(); +} + +class _TableManagementScreenState extends State { + TextEditingController? tableNameController; + + @override + void initState() { + context.read().add(const GetTableEvent.getTables()); + tableNameController = TextEditingController(); + super.initState(); + } + + @override + void dispose() { + tableNameController!.dispose(); + super.dispose(); + } + + @override + Widget build( + BuildContext context, + ) { + // final tables = ref.watch(tableProvider); + return Scaffold( + appBar: AppBar( + title: Text('Table Layout', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600)), + // leading: Icon(Icons.arrow_back), + backgroundColor: AppColors.white, + actions: [ + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + context + .read() + .add(const GetTableEvent.getTables()); + }); + }, + child: IconButton( + icon: Icon(Icons.add), + onPressed: () { + // show dialaog adn input table name + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text('Add Table'), + content: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: 180, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CustomTextField( + controller: tableNameController!, + label: 'Table Name', + ), + SpaceHeight(16), + Row( + children: [ + Expanded( + child: Button.outlined( + onPressed: () { + context.pop(); + }, + label: 'close', + ), + ), + SpaceWidth(16), + Expanded( + child: Button.filled( + onPressed: () { + context.read().add( + CreateTableEvent.createTable( + tableNameController!.text, + Offset(200, 200))); + context + .pop(); // close dialog after adding + }, + label: 'Add', + ), + ), + ], + ) + ], + ), + ), + ), + actions: []); + }); + }, + ), + ), + IconButton( + icon: Icon(Icons.edit), + onPressed: () { + // Handle delete action + }, + ), + IconButton( + icon: Icon(Icons.save), + onPressed: () { + // Handle delete action + }, + ), + IconButton( + icon: Icon(Icons.delete), + onPressed: () { + // Handle delete action + }, + ), + SpaceWidth(16), + ], + ), + body: BlocBuilder( + builder: (context, state) { + return state.maybeWhen(orElse: () { + return Container(); + }, success: (tables) { + return Stack( + children: tables.map((table) { + return Positioned( + left: table.position.dx - 116, + top: table.position.dy - 80, + child: BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + context + .read() + .add(const GetTableEvent.getTables()); + }); + }, + child: Draggable( + feedback: TableWidget(table: table), + childWhenDragging: SizedBox.shrink(), + onDragEnd: (details) { + context + .read() + .add(ChangePositionTableEvent.changePositionTable( + tableId: table.id!, + position: details.offset, + )); + }, + child: TableWidget(table: table), + ), + ), + ); + }).toList(), + ); + }); + }, + ), + // floatingActionButton: FloatingActionButton( + // onPressed: () => ref.read(tableProvider.notifier).addTable(), + // child: Icon(Icons.add), + // ), + ); + } +} diff --git a/lib/presentation/table/pages/payment_table_page.dart b/lib/presentation/table/pages/payment_table_page.dart new file mode 100644 index 0000000..7dbbbf5 --- /dev/null +++ b/lib/presentation/table/pages/payment_table_page.dart @@ -0,0 +1,1202 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/core/extensions/string_ext.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/order/order_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/payment_methods/payment_methods_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/models/product_quantity.dart'; +import 'package:enaklo_pos/presentation/home/models/order_type.dart'; +import 'package:enaklo_pos/presentation/home/widgets/order_menu.dart'; +import 'package:enaklo_pos/presentation/home/widgets/success_payment_dialog.dart'; +import 'package:enaklo_pos/presentation/home/widgets/order_type_selector.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart'; +import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart'; + +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; + +import '../../../core/components/buttons.dart'; +import '../../../core/components/spaces.dart'; +import '../../../core/constants/colors.dart'; + +class PaymentTablePage extends StatefulWidget { + final DraftOrderModel? draftOrder; + final TableModel? table; + const PaymentTablePage({ + Key? key, + this.draftOrder, + this.table, + }) : super(key: key); + + @override + State createState() => _PaymentTablePageState(); +} + +class _PaymentTablePageState extends State { + final totalPriceController = TextEditingController(); + final customerController = TextEditingController(); + PaymentMethod? selectedPaymentMethod; + int totalPriceFinal = 0; + int discountAmountFinal = 0; + + // Helper method to handle post-payment cleanup + Future _handlePostPaymentCleanup() async { + if (widget.table != null && widget.draftOrder?.id != null) { + // Update table status to available + final newTable = TableModel( + id: widget.table!.id, + tableName: widget.table!.tableName, + status: 'available', + orderId: 0, + paymentAmount: 0, + startTime: DateTime.now().toIso8601String(), + position: widget.table!.position, + ); + + // Update table status + await ProductLocalDatasource.instance.updateStatusTable(newTable); + + // Remove draft order + await ProductLocalDatasource.instance.removeDraftOrderById(widget.draftOrder!.id!); + + // Refresh table status + context.read().add( + GetTableStatusEvent.getTablesStatus('all'), + ); + + log("Table ${widget.table!.tableName} freed up and draft order removed"); + } + + // Safely navigate back - pop multiple times to get to table management + // Pop the success dialog first, then the payment page + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); // Pop success dialog + if (Navigator.of(context).canPop()) { + Navigator.of(context).pop(); // Pop payment page + } + } + } + @override + void initState() { + context + .read() + .add(GetTableStatusEvent.getTablesStatus('available')); + context + .read() + .add(PaymentMethodsEvent.fetchPaymentMethods()); + super.initState(); + + // Set a default payment method in case API fails + selectedPaymentMethod = PaymentMethod( + id: 1, + name: 'Cash', + description: 'Cash payment', + isActive: true, + sortOrder: 1, + ); + } + + @override + void dispose() { + totalPriceController.dispose(); + customerController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return SafeArea( + child: Hero( + tag: 'table_payment_screen', + child: Scaffold( + appBar: AppBar( + title: Text('Payment - Table ${widget.table?.tableName}'), + backgroundColor: AppColors.primary, + foregroundColor: Colors.white, + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + Navigator.of(context).pop(); + }, + ), + actions: [ + TextButton( + onPressed: () { + showDialog( + context: context, + builder: (BuildContext context) { + return AlertDialog( + title: const Text('Kembali'), + content: const Text('Apakah Anda yakin ingin kembali? Order akan tetap tersimpan.'), + actions: [ + TextButton( + onPressed: () { + Navigator.of(context).pop(); // Close dialog + }, + child: const Text('Tidak'), + ), + TextButton( + onPressed: () { + Navigator.of(context).pop(); // Close dialog + Navigator.of(context).pop(); // Go back to previous page + }, + child: const Text('Ya'), + ), + ], + ); + }, + ); + }, + child: const Text( + 'Kembali', + style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), + ), + ), + ], + ), + body: Row( + children: [ + // LEFT CONTENT + Expanded( + flex: 2, + child: Align( + alignment: Alignment.topCenter, + child: SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Konfirmasi', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + Text( + 'Orders Table ${widget.table?.tableName}', + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(24.0), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Item', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + SizedBox( + width: 160, + ), + SizedBox( + width: 50.0, + child: Text( + 'Qty', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox( + child: Text( + 'Price', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + const SpaceHeight(8), + const Divider(), + const SpaceHeight(8), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: Text('No Items'), + ), + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + if (products.isEmpty) { + return const Center( + child: Text('No Items'), + ); + } + return ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemBuilder: (context, index) => + OrderMenu(data: products[index]), + separatorBuilder: (context, index) => + const SpaceHeight(16.0), + itemCount: products.length, + ); + }, + ); + }, + ), + const SpaceHeight(16.0), + + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Sub total', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + )); + return Text( + price.currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(16.0), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Diskon', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + log("discountAmount: $discountAmount"); + return discountAmount; + }); + + discountAmountFinal = discount.toInt(); + + return Text( + discount.toInt().currencyFormatRp, + style: TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Pajak PB1', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + tax, + ); + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + return discountAmount; + }); + + final subTotal = price - discount; + final finalTax = subTotal * (tax / 100); + return Text( + '$tax % (${finalTax.toInt().currencyFormatRp})', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(16.0), + + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Biaya Layanan', + style: TextStyle(color: AppColors.grey), + ), + BlocBuilder( + builder: (context, state) { + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + tax, + ); + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + return discountAmount; + }); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + serviceCharge, + ); + + final subTotal = price - discount; + final finalServiceCharge = + subTotal * (serviceCharge / 100); + + return Text( + '$serviceCharge % (${finalServiceCharge.toInt().currencyFormatRp}) ', + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + const SpaceHeight(16.0), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text( + 'Total', + style: TextStyle( + color: AppColors.grey, + fontWeight: FontWeight.bold, + fontSize: 16), + ), + BlocBuilder( + builder: (context, state) { + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + return discountAmount; + }); + + final serviceCharge = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + serviceCharge, + ); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) => + tax, + ); + + final subTotal = price - discount; + final finalTax = subTotal * (tax / 100); + final service = + subTotal * (serviceCharge / 100); + final total = subTotal + finalTax + service; + totalPriceFinal = total.ceil(); + totalPriceController.text = + total.ceil().toString(); + return Text( + total.ceil().currencyFormatRp, + style: const TextStyle( + color: AppColors.primary, + fontWeight: FontWeight.w600, + fontSize: 16, + ), + ); + }, + ), + ], + ), + // const SpaceHeight(20.0), + // Button.filled( + // onPressed: () {}, + // label: 'Lanjutkan Pembayaran', + // ), + ], + ), + ), + ), + ), + + // RIGHT CONTENT + Expanded( + flex: 3, + child: Align( + alignment: Alignment.topCenter, + child: Stack( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.all(24.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Pembayaran', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(16.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Customer', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loaded: (items, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, orderType) { + customerController.text = draftName; + return TextFormField( + readOnly: true, + controller: customerController, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: + BorderRadius.circular(8.0), + ), + hintText: 'Nama Customer', + ), + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const OrderTypeSelector(), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Metode Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 20, + fontWeight: FontWeight.w600, + ), + ), + const SpaceHeight(12.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () => const Center( + child: CircularProgressIndicator(), + ), + loading: () => const Center( + child: Column( + children: [ + CircularProgressIndicator(), + SizedBox(height: 8.0), + Text('Loading payment methods...'), + ], + ), + ), + error: (message) => Column( + children: [ + Center( + child: Text('Error loading payment methods: $message'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent.fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ), + loaded: (paymentMethods) { + log("Loaded ${paymentMethods.length} payment methods"); + paymentMethods.forEach((method) { + log("Payment method: ${method.name} (ID: ${method.id})"); + }); + if (paymentMethods.isEmpty) { + return Column( + children: [ + const Center( + child: Text('No payment methods available'), + ), + const SpaceHeight(16.0), + Button.filled( + onPressed: () { + context + .read() + .add(PaymentMethodsEvent.fetchPaymentMethods()); + }, + label: 'Retry', + ), + ], + ); + } + + // Set default selected payment method if none selected or if current selection is not in the list + if (selectedPaymentMethod == null || + !paymentMethods.any((method) => method.id == selectedPaymentMethod?.id)) { + selectedPaymentMethod = paymentMethods.first; + } + + return Wrap( + spacing: 12.0, + runSpacing: 8.0, + children: paymentMethods.map((method) { + final isSelected = selectedPaymentMethod?.id == method.id; + return Container( + constraints: const BoxConstraints( + minWidth: 120.0, + ), + decoration: isSelected + ? BoxDecoration( + border: Border.all( + color: AppColors.primary, + width: 2.0, + ), + borderRadius: BorderRadius.circular(8.0), + ) + : null, + child: Tooltip( + message: method.description ?? 'No description available', + child: isSelected + ? Button.filled( + width: double.infinity, + height: 50.0, + onPressed: () { + setState(() { + selectedPaymentMethod = method; + }); + }, + label: method.name?.isNotEmpty == true ? method.name! : 'Unknown', + ) + : Button.outlined( + width: double.infinity, + height: 50.0, + onPressed: () { + setState(() { + selectedPaymentMethod = method; + }); + }, + label: method.name?.isNotEmpty == true ? method.name! : 'Unknown', + ), + ), + ); + }).toList(), + ); + }, + ); + }, + ), + const SpaceHeight(8.0), + const Divider(), + const SpaceHeight(8.0), + const Text( + 'Total Bayar', + style: TextStyle( + color: AppColors.primary, + fontSize: 16, + fontWeight: FontWeight.w500, + ), + ), + const SpaceHeight(12.0), + TextFormField( + controller: totalPriceController, + keyboardType: TextInputType.number, + decoration: InputDecoration( + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8.0), + ), + hintText: 'Total harga', + ), + ), + const SpaceHeight(45.0), + Row( + children: [ + Button.filled( + width: 150.0, + onPressed: () {}, + label: 'UANG PAS', + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () {}, + label: 'Rp 250.000', + ), + const SpaceWidth(20.0), + Button.filled( + width: 150.0, + onPressed: () {}, + label: 'Rp 300.000', + ), + ], + ), + const SpaceHeight(100.0), + ]), + ), + Align( + alignment: Alignment.bottomCenter, + child: ColoredBox( + color: AppColors.white, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 24.0, vertical: 16.0), + child: Row( + children: [ + Flexible( + child: Button.outlined( + onPressed: () => context.pop(), + label: 'Kembali', + ), + ), + const SpaceWidth(8.0), + Flexible( + child: Button.outlined( + onPressed: () { + // Show void confirmation dialog + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Row( + children: [ + Icon(Icons.warning, color: AppColors.red), + SizedBox(width: 8), + Text('Batalkan Pesanan?'), + ], + ), + content: Text( + 'Apakah anda yakin ingin membatalkan pesanan untuk meja ${widget.table?.tableName ?? "ini"}?\n\nPesanan akan dihapus secara permanen.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('Tidak', + style: TextStyle(color: AppColors.primary)), + ), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: () { + Navigator.pop(context); // Close void dialog + Navigator.pop(context); // Close payment page + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Pesanan berhasil dibatalkan'), + backgroundColor: AppColors.primary, + ), + ); + }, + ); + }, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.red, + ), + onPressed: () { + // Void the order + if (widget.table != null) { + final newTable = TableModel( + id: widget.table!.id, + tableName: widget.table!.tableName, + status: 'available', + orderId: 0, + paymentAmount: 0, + startTime: DateTime.now().toIso8601String(), + position: widget.table!.position, + ); + context.read().add( + StatusTableEvent.statusTabel(newTable), + ); + } + // Remove draft order from local storage + if (widget.draftOrder?.id != null) { + ProductLocalDatasource.instance + .removeDraftOrderById(widget.draftOrder!.id!); + } + log("Voided order from payment page"); + }, + child: const Text( + "Ya, Batalkan", + style: TextStyle(color: Colors.white), + ), + ), + ), + ], + ), + ); + }, + label: 'Batalkan', + ), + ), + const SpaceWidth(8.0), + BlocListener( + listener: (context, state) { + final newTable = TableModel( + id: widget.table!.id, + tableName: widget.table!.tableName, + status: 'available', + orderId: 0, + paymentAmount: 0, + startTime: + DateTime.now().toIso8601String(), + position: widget.table!.position, + ); + context.read().add( + StatusTableEvent.statusTabel( + newTable, + ), + ); + ProductLocalDatasource.instance + .removeDraftOrderById( + widget.draftOrder!.id!); + }, + child: + BlocBuilder( + builder: (context, state) { + final discount = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) { + if (discountModel == null) { + return 0; + } + return discountModel!.value! + .replaceAll('.00', '') + .toIntegerFromText; + }); + + final price = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products.fold( + 0, + (previousValue, element) => + previousValue + + (element.product.price! + .toIntegerFromText * + element.quantity), + ), + ); + + final tax = state.maybeWhen( + orElse: () => 0, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + tax, + ); + + final subTotal = + price - (discount / 100 * price); + final totalDiscount = + discount / 100 * price; + final finalTax = subTotal * (tax / 100); + + List items = + state.maybeWhen( + orElse: () => [], + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + products, + ); + final totalQty = items.fold( + 0, + (previousValue, element) => + previousValue + element.quantity, + ); + + final orderType = state.maybeWhen( + orElse: () => OrderType.dineIn, + loaded: (products, + discountModel, + discount, + discountAmount, + tax, + serviceCharge, + totalQuantity, + totalPrice, + draftName, + orderType) => + orderType, + ); + + final totalPrice = subTotal + finalTax; + + return Flexible( + child: Button.filled( + onPressed: () async { + if (selectedPaymentMethod == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Please select a payment method'), + backgroundColor: Colors.red, + ), + ); + return; + } + + final paymentMethodName = selectedPaymentMethod?.name?.toLowerCase() ?? ''; + log("Selected payment method: ${selectedPaymentMethod?.name} (normalized: $paymentMethodName)"); + + if (paymentMethodName == 'cash' || + paymentMethodName == 'tunai' || + paymentMethodName == 'uang tunai' || + paymentMethodName == 'cash payment') { + context.read().add( + OrderEvent.order( + items, + discount, + discountAmountFinal, + finalTax.toInt(), + 0, + totalPriceController.text + .toIntegerFromText, + customerController.text, + widget.table?.id ?? 0, + 'completed', + 'paid', + selectedPaymentMethod?.name ?? 'Cash', + totalPriceFinal, + orderType)); + + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + isTablePaymentPage: true, + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal.toInt(), + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: 0, + draftName: + customerController.text, + ), + ); + await _handlePostPaymentCleanup(); + } else { + log("Processing non-cash payment: ${selectedPaymentMethod?.name}"); + context.read().add( + OrderEvent.order( + items, + discount, + discountAmountFinal, + finalTax.toInt(), + 0, + totalPriceController.text + .toIntegerFromText, + customerController.text, + widget.table?.id ?? 0, + 'completed', + 'paid', + selectedPaymentMethod?.name ?? 'Unknown Payment Method', + totalPriceFinal, + orderType)); + + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => + SuccessPaymentDialog( + isTablePaymentPage: true, + data: items, + totalQty: totalQty, + totalPrice: + totalPriceFinal.toInt(), + totalTax: finalTax.toInt(), + totalDiscount: + totalDiscount.toInt(), + subTotal: subTotal.toInt(), + normalPrice: price, + totalService: 0, + draftName: + customerController.text, + ), + ); + + // Handle post-payment cleanup + await _handlePostPaymentCleanup(); + } + }, + label: 'Bayar', + ), + ); + }, + ), + ), + ], + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/presentation/table/pages/table_page.dart b/lib/presentation/table/pages/table_page.dart new file mode 100644 index 0000000..570d051 --- /dev/null +++ b/lib/presentation/table/pages/table_page.dart @@ -0,0 +1,95 @@ +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/dialogs/form_table_dialog.dart'; +import 'package:enaklo_pos/presentation/table/widgets/card_table_widget.dart'; + +class TablePage extends StatefulWidget { + const TablePage({super.key}); + + @override + State createState() => _TablePageState(); +} + +class _TablePageState extends State { + @override + void initState() { + context.read().add(const GetTableEvent.getTables()); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(24), + child: ListView( + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + "Table Management", + style: TextStyle( + fontSize: 24.0, + fontWeight: FontWeight.bold, + color: AppColors.primary, + ), + ), + Button.filled( + onPressed: () { + showDialog( + context: context, + builder: (context) => FormTableDialog(), + ); + }, + label: 'Generate Table', + height: 48.0, + width: 200.0, + ), + ], + ), + SpaceHeight(24.0), + BlocBuilder( + builder: (context, state) { + return state.maybeWhen( + orElse: () { + return SizedBox.shrink(); + }, + loading: () { + return const CircularProgressIndicator(); + }, + success: (tables) { + if (tables.isEmpty) { + return const Center( + child: Text('No table available'), + ); + } + return GridView.builder( + padding: EdgeInsets.zero, + gridDelegate: + const SliverGridDelegateWithFixedCrossAxisCount( + childAspectRatio: 1.0, + crossAxisCount: 4, + mainAxisSpacing: 16, + crossAxisSpacing: 16, + ), + itemCount: tables.length, + shrinkWrap: true, + physics: const ScrollPhysics(), + itemBuilder: (BuildContext context, int index) { + return CardTableWidget( + table: tables[index], + ); + }, + ); + }, + ); + }, + ), + ], + ), + ); + } +} diff --git a/lib/presentation/table/widgets/card_table_widget.dart b/lib/presentation/table/widgets/card_table_widget.dart new file mode 100644 index 0000000..024a311 --- /dev/null +++ b/lib/presentation/table/widgets/card_table_widget.dart @@ -0,0 +1,108 @@ +import 'dart:developer'; + +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter/material.dart'; +import 'package:enaklo_pos/core/components/components.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/extensions/date_time_ext.dart'; +import 'package:enaklo_pos/core/extensions/int_ext.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; + +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/pages/home_page.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart'; +import 'package:enaklo_pos/presentation/table/pages/payment_table_page.dart'; + +class CardTableWidget extends StatefulWidget { + final TableModel table; + const CardTableWidget({ + super.key, + required this.table, + }); + + @override + State createState() => _CardTableWidgetState(); +} + +class _CardTableWidgetState extends State { + DraftOrderModel? data; + + @override + void initState() { + loadData(); + super.initState(); + } + + loadData() async { + if (widget.table.status != 'available') { + data = await ProductLocalDatasource.instance + .getDraftOrderById(widget.table.orderId); + } + } + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.all(16.0), + height: 200, + width: 200, + decoration: BoxDecoration( + border: Border.all( + color: widget.table.status == 'available' + ? AppColors.primary + : AppColors.red, + width: 2), + borderRadius: BorderRadius.circular(16), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Table ${widget.table.tableName}', + style: TextStyle( + color: AppColors.black, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + Text( + widget.table.status == 'available' + ? widget.table.status + : "${widget.table.status} - ${DateTime.parse(widget.table.startTime).toFormattedTime()}", + style: TextStyle( + color: AppColors.black, + fontSize: 24, + fontWeight: FontWeight.bold, + ), + ), + Button.filled( + color: widget.table.status == 'available' + ? AppColors.primary + : AppColors.red, + onPressed: () async { + if (widget.table.status == 'available') { + context.push(HomePage( + isTable: true, + table: widget.table, + )); + } else { + context.read().add( + CheckoutEvent.loadDraftOrder(data!), + ); + log("Data Draft Order: ${data!.toMap()}"); + context.push(PaymentTablePage( + table: widget.table, + draftOrder: data!, + )); + } + }, + label: widget.table.status == 'available' ? 'Open' : 'Close') + ], + ), + ); + } +} diff --git a/lib/presentation/table/widgets/table_widget.dart b/lib/presentation/table/widgets/table_widget.dart new file mode 100644 index 0000000..ea94ca8 --- /dev/null +++ b/lib/presentation/table/widgets/table_widget.dart @@ -0,0 +1,379 @@ +// ignore_for_file: public_member_api_docs, sort_constructors_first +import 'dart:developer'; + +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:enaklo_pos/core/components/buttons.dart'; +import 'package:enaklo_pos/core/components/custom_text_field.dart'; +import 'package:enaklo_pos/core/components/spaces.dart'; +import 'package:enaklo_pos/core/constants/colors.dart'; +import 'package:enaklo_pos/core/extensions/build_context_ext.dart'; +import 'package:enaklo_pos/core/utils/date_formatter.dart'; +import 'package:enaklo_pos/data/datasources/product_local_datasource.dart'; + +import 'package:enaklo_pos/data/models/response/table_model.dart'; +import 'package:enaklo_pos/presentation/home/bloc/checkout/checkout_bloc.dart'; +import 'package:enaklo_pos/presentation/home/bloc/status_table/status_table_bloc.dart'; +import 'package:enaklo_pos/presentation/home/pages/dashboard_page.dart'; +import 'package:enaklo_pos/presentation/table/blocs/create_table/create_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/get_table/get_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/blocs/update_table/update_table_bloc.dart'; +import 'package:enaklo_pos/presentation/table/models/draft_order_model.dart'; + +import '../pages/payment_table_page.dart'; + +class TableWidget extends StatefulWidget { + final TableModel table; + const TableWidget({ + super.key, + required this.table, + }); + + @override + State createState() => _TableWidgetState(); +} + +class _TableWidgetState extends State { + TextEditingController? tableNameController; + DraftOrderModel? data; + @override + void initState() { + super.initState(); + loadData(); + tableNameController = TextEditingController(text: widget.table.tableName); + } + + @override + void dispose() { + tableNameController!.dispose(); + super.dispose(); + } + + loadData() async { + if (widget.table.status != 'available') { + data = await ProductLocalDatasource.instance + .getDraftOrderById(widget.table.orderId); + } + } + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: () async { + if (widget.table.status == 'available') { + context.push(DashboardPage( + table: widget.table, + )); + } else { + // Handle occupied table click - load draft order and navigate to payment + context.read().add( + CheckoutEvent.loadDraftOrder(data!), + ); + log("Data Draft Order: ${data!.toMap()}"); + context.push(PaymentTablePage( + table: widget.table, + draftOrder: data!, + )); + } + }, + onLongPress: () { + // dialog info table + showDialog( + context: context, + builder: (context) { + return AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16)), + title: Row( + children: [ + Icon(Icons.table_bar, color: AppColors.primary), + SizedBox(width: 8), + Text('Table ${widget.table.tableName}'), + Spacer(), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: (message) { + context + .read() + .add(const GetTableEvent.getTables()); + context.pop(); + }); + }, + child: IconButton( + onPressed: () { + // show dialaog adn input table name + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text('Update Table'), + content: SingleChildScrollView( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: 180, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + CustomTextField( + controller: tableNameController!, + label: 'Table Name', + ), + SpaceHeight(16), + Row( + children: [ + Expanded( + child: Button.outlined( + onPressed: () { + context.pop(); + }, + label: 'close', + ), + ), + SpaceWidth(16), + Expanded( + child: Button.filled( + onPressed: () { + final newData = + TableModel( + id: widget.table.id, + tableName: + tableNameController! + .text, + status: + widget.table.status, + startTime: widget + .table.startTime, + orderId: widget + .table.orderId, + paymentAmount: widget + .table + .paymentAmount, + position: widget + .table.position, + ); + context + .read< + UpdateTableBloc>() + .add( + UpdateTableEvent + .updateTable( + newData, + ), + ); + context + .pop(); // close dialog after adding + }, + label: 'Update', + ), + ) + ], + ) + ], + ), + ), + ), + actions: []); + }); + }, + icon: Icon(Icons.edit)), + ), + ], + ), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildInfoRow( + 'Status:', + widget.table.status == 'available' + ? 'Available' + : 'Occupied', + color: widget.table.status == 'available' + ? Colors.green + : Colors.red), + widget.table.status == 'available' + ? SizedBox.shrink() + : _buildInfoRow( + 'Start Time:', + DateFormatter.formatDateTime2( + widget.table.startTime)), + widget.table.status == 'available' + ? SizedBox.shrink() + : _buildInfoRow( + 'Order ID:', widget.table.orderId.toString()), + widget.table.status == 'available' + ? SizedBox.shrink() + : SpaceHeight(16), + widget.table.status == 'available' + ? SizedBox.shrink() + : Row( + children: [ + Expanded( + child: Button.outlined( + onPressed: () { + // Show void confirmation dialog + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Row( + children: [ + Icon(Icons.warning, color: AppColors.red), + SizedBox(width: 8), + Text('Void Order?'), + ], + ), + content: Text( + 'Apakah anda yakin ingin membatalkan pesanan untuk meja ${widget.table.tableName}?\n\nPesanan akan dihapus secara permanen.'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text('Tidak', + style: TextStyle(color: AppColors.primary)), + ), + BlocListener( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: () { + context + .read() + .add(const GetTableEvent.getTables()); + Navigator.pop(context); // Close void dialog + Navigator.pop(context); // Close table info dialog + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Pesanan berhasil dibatalkan'), + backgroundColor: AppColors.primary, + ), + ); + }, + ); + }, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: AppColors.red, + ), + onPressed: () { + // Void the order + final newTable = TableModel( + id: widget.table.id, + tableName: widget.table.tableName, + status: 'available', + orderId: 0, + paymentAmount: 0, + startTime: DateTime.now().toIso8601String(), + position: widget.table.position, + ); + context.read().add( + StatusTableEvent.statusTabel(newTable), + ); + // Remove draft order from local storage + ProductLocalDatasource.instance + .removeDraftOrderById(widget.table.orderId); + log("Voided order for table: ${widget.table.tableName}"); + }, + child: const Text( + "Ya, Batalkan", + style: TextStyle(color: Colors.white), + ), + ), + ), + ], + ), + ); + }, + label: 'Void Order', + color: AppColors.red, + textColor: AppColors.red, + ), + ), + SizedBox(width: 12), + Expanded( + child: BlocConsumer( + listener: (context, state) { + state.maybeWhen( + orElse: () {}, + success: () { + context + .read() + .add(const GetTableEvent.getTables()); + context.pop(); + }); + }, + builder: (context, state) { + return Button.filled( + onPressed: () { + context.pop(); + context.read().add( + CheckoutEvent.loadDraftOrder(data!), + ); + context.push(PaymentTablePage( + table: widget.table, + draftOrder: data!, + )); + }, + label: 'Selesai'); + }, + ), + ), + ], + ), + ], + ), + actions: [ + TextButton( + child: + Text('Close', style: TextStyle(color: AppColors.primary)), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ); + }, + ); + }, + child: Container( + padding: const EdgeInsets.all(16.0), + alignment: Alignment.center, + decoration: BoxDecoration( + color: widget.table.status == 'available' + ? AppColors.primary + : AppColors.red, + shape: BoxShape.rectangle, + borderRadius: BorderRadius.circular(10), + ), + child: Text('${widget.table.tableName}', + style: TextStyle( + color: Colors.white, + fontSize: 18, + fontWeight: FontWeight.w600, + )), + ), + ); + } + + Widget _buildInfoRow(String label, String value, {Color? color}) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Row( + children: [ + Text( + label, + style: TextStyle(fontWeight: FontWeight.w600), + ), + SizedBox(width: 8), + Expanded( + child: Text( + value, + style: TextStyle( + color: color ?? Colors.black87, + ), + ), + ), + ], + ), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..5cc967c --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1503 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab" + url: "https://pub.dev" + source: hosted + version: "76.0.0" + _macros: + dependency: transitive + description: dart + source: sdk + version: "0.3.3" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e" + url: "https://pub.dev" + source: hosted + version: "6.11.0" + archive: + dependency: transitive + description: + name: archive + sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d + url: "https://pub.dev" + source: hosted + version: "3.6.1" + args: + dependency: transitive + description: + name: args + sha256: bf9f5caeea8d8fe6721a9c358dd8a5c1947b27f1cfaa18b39c301273594919e6 + url: "https://pub.dev" + source: hosted + version: "2.6.0" + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + barcode: + dependency: transitive + description: + name: barcode + sha256: ab180ce22c6555d77d45f0178a523669db67f95856e3378259ef2ffeb43e6003 + url: "https://pub.dev" + source: hosted + version: "2.2.8" + bidi: + dependency: transitive + description: + name: bidi + sha256: "9a712c7ddf708f7c41b1923aa83648a3ed44cfd75b04f72d598c45e5be287f9d" + url: "https://pub.dev" + source: hosted + version: "2.0.12" + bloc: + dependency: transitive + description: + name: bloc + sha256: "52c10575f4445c61dd9e0cafcc6356fdd827c4c64dd7945ef3c4105f6b6ac189" + url: "https://pub.dev" + source: hosted + version: "9.0.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build: + dependency: transitive + description: + name: build + sha256: cef23f1eda9b57566c81e2133d196f8e3df48f244b317368d65c5943d91148f0 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + build_config: + dependency: transitive + description: + name: build_config + sha256: "4ae2de3e1e67ea270081eaee972e1bd8f027d459f249e0f1186730784c2e7e33" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "294a2edaf4814a378725bfe6358210196f5ea37af89ecd81bfa32960113d4948" + url: "https://pub.dev" + source: hosted + version: "4.0.3" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: "99d3980049739a985cf9b21f30881f46db3ebc62c5b8d5e60e27440876b1ba1e" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "74691599a5bc750dc96a6b4bfd48f7d9d66453eab04c7f4063134800d6a5c573" + url: "https://pub.dev" + source: hosted + version: "2.4.14" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: "22e3aa1c80e0ada3722fe5b63fd43d9c8990759d0a2cf489c8c5d7b2bdebc021" + url: "https://pub.dev" + source: hosted + version: "8.0.0" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: "28a712df2576b63c6c005c465989a348604960c0958d28be5303ba9baa841ac2" + url: "https://pub.dev" + source: hosted + version: "8.9.3" + cached_network_image: + dependency: "direct main" + description: + name: cached_network_image + sha256: "7c1183e361e5c8b0a0f21a28401eecdbde252441106a9816400dd4c2b2424916" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + cached_network_image_platform_interface: + dependency: transitive + description: + name: cached_network_image_platform_interface + sha256: "35814b016e37fbdc91f7ae18c8caf49ba5c88501813f73ce8a07027a395e2829" + url: "https://pub.dev" + source: hosted + version: "4.1.1" + cached_network_image_web: + dependency: transitive + description: + name: cached_network_image_web + sha256: "980842f4e8e2535b8dbd3d5ca0b1f0ba66bf61d14cc3a17a9b4788a3685ba062" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff + url: "https://pub.dev" + source: hosted + version: "2.0.3" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.dev" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: "0ec10bf4a89e4c613960bf1e8b42c64127021740fb21640c29c909826a5eea3e" + url: "https://pub.dev" + source: hosted + version: "4.10.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + color: + dependency: transitive + description: + name: color + sha256: ddcdf1b3badd7008233f5acffaf20ca9f5dc2cd0172b75f68f24526a5f5725cb + url: "https://pub.dev" + source: hosted + version: "3.0.0" + connectivity_plus: + dependency: "direct main" + description: + name: connectivity_plus + sha256: "8a68739d3ee113e51ad35583fdf9ab82c55d09d693d3c39da1aebab87c938412" + url: "https://pub.dev" + source: hosted + version: "6.1.2" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "42657c1715d48b167930d5f34d00222ac100475f73d10162ddf43e714932f204" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" + url: "https://pub.dev" + source: hosted + version: "0.3.4+2" + crypto: + dependency: transitive + description: + name: crypto + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "7856d364b589d1f08986e140938578ed36ed948581fbc3bc9aef1805039ac5ab" + url: "https://pub.dev" + source: hosted + version: "2.3.7" + dartx: + dependency: transitive + description: + name: dartx + sha256: "8b25435617027257d43e6508b5fe061012880ddfdaa75a71d607c3de2a13d244" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + dartz: + dependency: "direct main" + description: + name: dartz + sha256: e6acf34ad2e31b1eb00948692468c30ab48ac8250e0f0df661e29f12dd252168 + url: "https://pub.dev" + source: hosted + version: "0.10.1" + dbus: + dependency: transitive + description: + name: dbus + sha256: "365c771ac3b0e58845f39ec6deebc76e3276aa9922b0cc60840712094d9047ac" + url: "https://pub.dev" + source: hosted + version: "0.7.10" + device_info_plus: + dependency: "direct main" + description: + name: device_info_plus + sha256: b37d37c2f912ad4e8ec694187de87d05de2a3cb82b465ff1f65f65a2d05de544 + url: "https://pub.dev" + source: hosted + version: "11.2.1" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "0b04e02b30791224b31969eb1b50d723498f402971bff3630bca2ba839bd1ed2" + url: "https://pub.dev" + source: hosted + version: "7.0.2" + esc_pos_utils_plus: + dependency: "direct main" + description: + name: esc_pos_utils_plus + sha256: "2a22d281cb6f04600ba3ebd607ad8df03a4b2446d814007d22525bab4d50c2ff" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + 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: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33" + url: "https://pub.dev" + source: hosted + version: "0.9.3+2" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc" + url: "https://pub.dev" + source: hosted + version: "0.9.4+2" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b + url: "https://pub.dev" + source: hosted + version: "2.6.2" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "8f5d2f6590d51ecd9179ba39c64f722edc15226cc93dcc8698466ad36a4a85a4" + url: "https://pub.dev" + source: hosted + version: "0.9.3+3" + 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_bloc: + dependency: "direct main" + description: + name: flutter_bloc + sha256: "153856bdaac302bbdc58a1d1403d50c40557254aa05eaeed40515d88a25a526b" + url: "https://pub.dev" + source: hosted + version: "9.0.0" + flutter_cache_manager: + dependency: transitive + description: + name: flutter_cache_manager + sha256: "400b6592f16a4409a7f2bb929a9a7e38c72cceb8ffb99ee57bbf2cb2cecf8386" + url: "https://pub.dev" + source: hosted + version: "3.4.1" + flutter_esc_pos_network: + dependency: "direct main" + description: + name: flutter_esc_pos_network + sha256: "44ca5966c82dd7a2a703a7ff95407c6738fb1d71b7540c137783b374e62a08fd" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + flutter_esc_pos_utils: + dependency: transitive + description: + name: flutter_esc_pos_utils + sha256: "2186973896d2dac3d5ebb2e09dac963001d29cd9e683f23afe8dbd5fb4013356" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + flutter_gen_core: + dependency: transitive + description: + name: flutter_gen_core + sha256: "46ecf0e317413dd065547887c43f93f55e9653e83eb98dc13dd07d40dd225325" + url: "https://pub.dev" + source: hosted + version: "5.8.0" + flutter_gen_runner: + dependency: "direct dev" + description: + name: flutter_gen_runner + sha256: "77f0a02fc30d9fcf2549fe874eb3fde091435724904bcbb1af60aa40cbfab1f4" + url: "https://pub.dev" + source: hosted + version: "5.8.0" + flutter_launcher_icons: + dependency: "direct dev" + description: + name: flutter_launcher_icons + sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + url: "https://pub.dev" + source: hosted + version: "0.13.1" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.dev" + source: hosted + version: "5.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "615a505aef59b151b46bbeef55b36ce2b6ed299d160c51d84281946f0aa0ce0e" + url: "https://pub.dev" + source: hosted + version: "2.0.24" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + flutter_svg: + dependency: "direct main" + description: + name: flutter_svg + sha256: c200fd79c918a40c5cd50ea0877fa13f81bdaf6f0a5d3dbcc2a13e3285d6aa1b + url: "https://pub.dev" + source: hosted + version: "2.0.17" + 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" + freezed: + dependency: "direct main" + description: + name: freezed + sha256: "44c19278dd9d89292cf46e97dc0c1e52ce03275f40a97c5a348e802a924bf40e" + url: "https://pub.dev" + source: hosted + version: "2.5.7" + freezed_annotation: + dependency: "direct main" + description: + name: freezed_annotation + sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2 + url: "https://pub.dev" + source: hosted + version: "2.4.4" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + gbk_codec: + dependency: transitive + description: + name: gbk_codec + sha256: "3af5311fc9393115e3650ae6023862adf998051a804a08fb804f042724999f61" + url: "https://pub.dev" + source: hosted + version: "0.4.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + google_fonts: + dependency: "direct main" + description: + name: google_fonts + sha256: b1ac0fe2832c9cc95e5e88b57d627c5e68c223b9657f4b96e1487aa9098c7b82 + url: "https://pub.dev" + source: hosted + version: "6.2.1" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + hashcodes: + dependency: transitive + description: + name: hashcodes + sha256: "80f9410a5b3c8e110c4b7604546034749259f5d6dcca63e0d3c17c9258f1a651" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + hex: + dependency: transitive + description: + name: hex + sha256: "4e7cd54e4b59ba026432a6be2dd9d96e4c5205725194997193bf871703b82c4a" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + hive: + dependency: "direct main" + description: + name: hive + sha256: "8dcf6db979d7933da8217edcec84e9df1bdb4e4edc7fc77dbd5aa74356d6d941" + url: "https://pub.dev" + source: hosted + version: "2.2.3" + horizontal_data_table: + dependency: "direct main" + description: + name: horizontal_data_table + sha256: c8ab5256bbced698a729f3e0ff2cb0e8e97416cdbb082860370eaf883badf722 + url: "https://pub.dev" + source: hosted + version: "4.3.1" + html: + dependency: transitive + description: + name: html + sha256: "1fc58edeaec4307368c60d59b7e15b9d658b57d7f3125098b6294153c75337ec" + url: "https://pub.dev" + source: hosted + version: "0.15.5" + http: + dependency: "direct main" + description: + name: http + sha256: b9c29a161230ee03d3ccf545097fccd9b87a5264228c5d348202e0f0c28f9010 + url: "https://pub.dev" + source: hosted + version: "1.2.2" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: "direct main" + description: + name: image + sha256: f31d52537dc417fdcde36088fdf11d191026fd5e4fae742491ebd40e5a8bea7d + url: "https://pub.dev" + source: hosted + version: "4.3.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "021834d9c0c3de46bf0fe40341fa07168407f694d9b2bb18d532dc1261867f7a" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: b62d34a506e12bb965e824b6db4fbf709ee4589cf5d3e99b45ab2287b008ee0c + url: "https://pub.dev" + source: hosted + version: "0.8.12+20" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "717eb042ab08c40767684327be06a5d8dbb341fe791d514e4b92c7bbe1b7bb83" + url: "https://pub.dev" + source: hosted + version: "3.0.6" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "05da758e67bc7839e886b3959848aa6b44ff123ab4b28f67891008afe8ef9100" + url: "https://pub.dev" + source: hosted + version: "0.8.12+2" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "4ed1d9bb36f7cd60aa6e6cd479779cc56a4cb4e4de8f49d487b1aaad831300fa" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "3f5ad1e8112a9a6111c46d0b57a7be2286a9a07fc6e1976fdf5be2bd31d4ff62" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "886d57f0be73c4b140004e78b9f28a8914a09e50c2d816bdd0520051a71236a0" + url: "https://pub.dev" + source: hosted + version: "2.10.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: "6ad07afc4eb1bc25f3a01084d28520496c4a3bb0cb13685435838167c9dcedeb" + url: "https://pub.dev" + source: hosted + version: "0.2.1+1" + image_size_getter: + dependency: transitive + description: + name: image_size_getter + sha256: "9a299e3af2ebbcfd1baf21456c3c884037ff524316c97d8e56035ea8fdf35653" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + intl: + dependency: "direct main" + description: + name: intl + sha256: "00f33b908655e606b86d2ade4710a231b802eec6f11e87e4ea3783fd72077a50" + url: "https://pub.dev" + source: hosted + version: "0.20.1" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.dev" + source: hosted + version: "1.0.5" + js: + dependency: transitive + description: + name: js + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf + url: "https://pub.dev" + source: hosted + version: "0.7.1" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + url: "https://pub.dev" + source: hosted + version: "10.0.9" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + url: "https://pub.dev" + source: hosted + version: "3.0.9" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.dev" + source: hosted + version: "5.1.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + macros: + dependency: transitive + description: + name: macros + sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656" + url: "https://pub.dev" + source: hosted + version: "0.1.3-main.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.dev" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.dev" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.dev" + source: hosted + version: "2.0.0" + nested: + dependency: transitive + description: + name: nested + sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + nm: + dependency: transitive + description: + name: nm + sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" + url: "https://pub.dev" + source: hosted + version: "0.5.0" + octo_image: + dependency: transitive + description: + name: octo_image + sha256: "34faa6639a78c7e3cbe79be6f9f96535867e879748ade7d17c9b1ae7536293bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + open_file: + dependency: "direct main" + description: + name: open_file + sha256: d17e2bddf5b278cb2ae18393d0496aa4f162142ba97d1a9e0c30d476adf99c0e + url: "https://pub.dev" + source: hosted + version: "3.5.10" + open_file_android: + dependency: transitive + description: + name: open_file_android + sha256: "58141fcaece2f453a9684509a7275f231ac0e3d6ceb9a5e6de310a7dff9084aa" + url: "https://pub.dev" + source: hosted + version: "1.0.6" + open_file_ios: + dependency: transitive + description: + name: open_file_ios + sha256: "02996f01e5f6863832068e97f8f3a5ef9b613516db6897f373b43b79849e4d07" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + open_file_linux: + dependency: transitive + description: + name: open_file_linux + sha256: d189f799eecbb139c97f8bc7d303f9e720954fa4e0fa1b0b7294767e5f2d7550 + url: "https://pub.dev" + source: hosted + version: "0.0.5" + open_file_mac: + dependency: transitive + description: + name: open_file_mac + sha256: "1440b1e37ceb0642208cfeb2c659c6cda27b25187a90635c9d1acb7d0584d324" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + open_file_platform_interface: + dependency: transitive + description: + name: open_file_platform_interface + sha256: "101b424ca359632699a7e1213e83d025722ab668b9fd1412338221bf9b0e5757" + url: "https://pub.dev" + source: hosted + version: "1.0.3" + open_file_web: + dependency: transitive + description: + name: open_file_web + sha256: e3dbc9584856283dcb30aef5720558b90f88036360bd078e494ab80a80130c4f + url: "https://pub.dev" + source: hosted + version: "0.0.4" + open_file_windows: + dependency: transitive + description: + name: open_file_windows + sha256: d26c31ddf935a94a1a3aa43a23f4fff8a5ff4eea395fe7a8cb819cf55431c875 + url: "https://pub.dev" + source: hosted + version: "0.0.3" + package_config: + dependency: transitive + description: + name: package_config + sha256: "92d4488434b520a62570293fbd33bb556c7d49230791c1b4bbd973baf6d2dc67" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + 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: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: "05df53f8791587402493ac97b9869d3824eccbc77d97855f4545cf72df3cae07" + url: "https://pub.dev" + source: hosted + version: "3.11.1" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: "18bf33f7fefbd812f37e72091a15575e72d5318854877e0e4035a24ac1113ecb" + url: "https://pub.dev" + source: hosted + version: "11.3.1" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: "71bbecfee799e65aff7c744761a57e817e73b738fedf62ab7afd5593da21f9f1" + url: "https://pub.dev" + source: hosted + version: "12.0.13" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: e6f6d73b12438ef13e648c4ae56bd106ec60d17e90a59c4545db6781229082a0 + url: "https://pub.dev" + source: hosted + version: "9.4.5" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24" + url: "https://pub.dev" + source: hosted + version: "0.1.3+5" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: e9c8eadee926c4532d0305dff94b85bf961f16759c3af791486613152af4b4f9 + url: "https://pub.dev" + source: hosted + version: "4.2.3" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e" + url: "https://pub.dev" + source: hosted + version: "0.2.1" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: c15605cd28af66339f8eb6fbe0e541bfe2d1b72d5825efc6598f3e0a31b9ad27 + url: "https://pub.dev" + source: hosted + version: "6.0.2" + pie_chart: + dependency: "direct main" + description: + name: pie_chart + sha256: "58e6a46999ac938bfa1c3e5be414d6e149f037647197dca03ba3614324c12c82" + url: "https://pub.dev" + source: hosted + version: "5.4.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + print_bluetooth_thermal: + dependency: "direct main" + description: + name: print_bluetooth_thermal + sha256: "74e3face536392562764f5555bf15e02c16de7436e9f7f0cb23a7f749c39691f" + url: "https://pub.dev" + source: hosted + version: "1.1.6" + provider: + dependency: transitive + description: + name: provider + sha256: c8a055ee5ce3fd98d6fc872478b03823ffdb448699c6ebdbbc71d59b596fd48c + url: "https://pub.dev" + source: hosted + version: "6.1.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "7b3cfbf654f3edd0c6298ecd5be782ce997ddf0e00531b9464b55245185bbbbd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + qr: + dependency: transitive + description: + name: qr + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + qr_flutter: + dependency: "direct main" + description: + name: qr_flutter + sha256: "5095f0fc6e3f71d08adef8feccc8cea4f12eec18a2e31c2e8d82cb6019f4b097" + url: "https://pub.dev" + source: hosted + version: "4.1.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.dev" + source: hosted + version: "2.6.1" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: a752ce92ea7540fc35a0d19722816e04d0e72828a4200e83a98cf1a1eb524c9a + url: "https://pub.dev" + source: hosted + version: "2.3.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "138b7bbbc7f59c56236e426c37afb8f78cbc57b094ac64c440e0bb90e380a4f5" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: d2ca4132d3946fec2184261726b355836a82c33d7d5b67af32692aff18a4684e + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: cc36c297b52866d203dbf9332263c94becc2fe0ceaa9681d07b6ef9807023b67 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.dev" + source: hosted + version: "1.10.1" + sprintf: + dependency: transitive + description: + name: sprintf + sha256: "1fc9ffe69d4df602376b52949af107d8f5703b77cda567c4d7d86a0693120f23" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + sqflite: + dependency: "direct main" + description: + name: sqflite + sha256: "2d7299468485dca85efeeadf5d38986909c5eb0cd71fd3db2c2f000e6c9454bb" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "78f489aab276260cdd26676d2169446c7ecd3484bbd5fead4ca14f3ed4dd9ee3" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "761b9740ecbd4d3e66b8916d784e581861fd3c3553eda85e167bc49fdb68f709" + url: "https://pub.dev" + source: hosted + version: "2.5.4+6" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "22adfd9a2c7d634041e96d6241e6e1c8138ca6817018afc5d443fef91dcefa9c" + url: "https://pub.dev" + source: hosted + version: "2.4.1+1" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" + 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" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.dev" + source: hosted + version: "2.1.1" + 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: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" + url: "https://pub.dev" + source: hosted + version: "3.3.0+3" + 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: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + url: "https://pub.dev" + source: hosted + version: "0.7.4" + time: + dependency: transitive + description: + name: time + sha256: "370572cf5d1e58adcb3e354c47515da3f7469dac3a95b447117e728e7be6f461" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + timing: + dependency: transitive + description: + name: timing + sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + uuid: + dependency: transitive + description: + name: uuid + sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff + url: "https://pub.dev" + source: hosted + version: "4.5.1" + vector_graphics: + dependency: transitive + description: + name: vector_graphics + sha256: "27d5fefe86fb9aace4a9f8375b56b3c292b64d8c04510df230f849850d912cb7" + url: "https://pub.dev" + source: hosted + version: "1.1.15" + vector_graphics_codec: + dependency: transitive + description: + name: vector_graphics_codec + sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146" + url: "https://pub.dev" + source: hosted + version: "1.1.13" + vector_graphics_compiler: + dependency: transitive + description: + name: vector_graphics_compiler + sha256: "1b4b9e706a10294258727674a340ae0d6e64a7231980f9f9a3d12e4b42407aad" + url: "https://pub.dev" + source: hosted + version: "1.1.16" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 + url: "https://pub.dev" + source: hosted + version: "15.0.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "69da27e49efa56a15f8afe8f4438c4ec02eff0a117df1b22ea4aad194fe1c104" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web: + dependency: transitive + description: + name: web + sha256: cd3543bd5798f6ad290ea73d210f423502e71900302dde696f8bff84bf89a1cb + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "3c12d96c0c9a4eec095246debcea7b86c0324f22df69893d538fcc6f1b8cce83" + url: "https://pub.dev" + source: hosted + version: "0.1.6" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: "9f187088ed104edd8662ca07af4b124465893caf063ba29758f97af57e61da8f" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + widgets_to_image: + dependency: "direct main" + description: + name: widgets_to_image + sha256: "9a251b95d3a9f10d72420dde9b7e3b0da5eddd47fb19cad066bc68c60b0d1dfb" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + win32: + dependency: transitive + description: + name: win32 + sha256: "154360849a56b7b67331c21f09a386562d88903f90a1099c5987afc1912e1f29" + url: "https://pub.dev" + source: hosted + version: "5.10.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "21ec76dfc731550fd3e2ce7a33a9ea90b828fdf19a5c3bcf556fa992cfa99852" + url: "https://pub.dev" + source: hosted + version: "1.1.5" + win_ble: + dependency: transitive + description: + name: win_ble + sha256: "2a867e13c4b355b101fc2c6e2ac85eeebf965db34eca46856f8b478e93b41e96" + 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: b015a8ad1c488f66851d762d3090a21c600e479dc75e68328c52774040cf9226 + url: "https://pub.dev" + source: hosted + version: "6.5.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.dev" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.7.0-0 <4.0.0" + flutter: ">=3.24.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..ac08c96 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,134 @@ +name: enaklo_pos +description: "EnakloPOS - Point of Sale Application" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: '>=3.2.4 <4.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + cached_network_image: ^3.4.1 + connectivity_plus: ^6.1.0 + cupertino_icons: ^1.0.2 + dartz: ^0.10.1 + device_info_plus: ^11.1.0 + esc_pos_utils_plus: ^2.0.3 + flutter: + sdk: flutter + flutter_bloc: ^9.0.0 + flutter_riverpod: ^2.6.1 + flutter_svg: ^2.0.9 + freezed: ^2.4.6 + freezed_annotation: ^2.4.1 + google_fonts: ^6.1.0 + hive: ^2.2.3 + horizontal_data_table: ^4.3.1 + http: ^1.2.0 + image: ^4.3.0 + image_picker: ^1.0.4 + intl: ^0.20.1 + open_file: ^3.3.2 + path_provider: ^2.1.2 + pdf: ^3.10.8 + permission_handler: ^11.3.1 + pie_chart: ^5.4.0 + print_bluetooth_thermal: ^1.1.6 + qr_flutter: ^4.1.0 + shared_preferences: ^2.2.2 + sqflite: ^2.3.2 + widgets_to_image: ^1.0.0 + flutter_esc_pos_network: ^1.0.3 + # imin_printer: ^0.6.10 + +dev_dependencies: + build_runner: ^2.4.6 + flutter_gen_runner: ^5.3.2 + flutter_lints: ^5.0.0 + flutter_test: + sdk: flutter + flutter_launcher_icons: ^0.13.1 +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec +# The following section is specific to Flutter packages. +flutter_gen: + output: lib/core/assets/ + integrations: + flutter_svg: true + +flutter_launcher_icons: + android: "launcher_icon" + ios: true + image_path: "assets/logo/logo.png" + min_sdk_android: 21 + remove_alpha_ios: true + adaptive_icon_background: "#FFFFFF" + adaptive_icon_foreground: "assets/logo/logo.png" + web: + generate: true + image_path: "assets/logo/logo.png" + background_color: "#hexcode" + theme_color: "#hexcode" + windows: + generate: true + image_path: "assets/logo/logo.png" + icon_size: 48 + macos: + generate: true + image_path: "assets/logo/logo.png" + +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + assets: + - assets/images/ + - assets/icons/ + - assets/logo/ + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..c09cfc2 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..bbe6bc1 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..4ad0bb0 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..bbe6bc1 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..4ad0bb0 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..abf912b --- /dev/null +++ b/web/index.html @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + flutter_posresto_app + + + + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..29c53fd --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "flutter_posresto_app", + "short_name": "flutter_posresto_app", + "start_url": ".", + "display": "standalone", + "background_color": "#hexcode", + "theme_color": "#hexcode", + "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" + } + ] +} \ No newline at end of file