Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
457ed38827 | ||
|
|
d34487d883 | ||
|
|
f4cdfcb96f | ||
|
|
0bccec8a1e | ||
|
|
86d2196a04 | ||
|
|
aa25de8da7 | ||
|
|
96387c08f4 | ||
|
|
e585cf4292 | ||
|
|
290360674f | ||
|
|
1fbacae1f4 | ||
|
|
613b216c04 | ||
|
|
455a6afd70 | ||
|
|
2813011fac | ||
|
|
83af323a2f | ||
|
|
cef1f79032 | ||
|
|
59a8d7f661 | ||
|
|
a58d1040af | ||
|
|
72a464b4c0 | ||
|
|
5b980d237f | ||
|
|
c12d6525fa | ||
|
|
44402140fb | ||
|
|
04811015b6 | ||
|
|
f104390141 | ||
|
|
3022d8de9f | ||
|
|
6acfbdc4ca | ||
|
|
7b12793618 | ||
|
|
a6ac12c36a | ||
|
|
e1e702bd76 | ||
|
|
fabb77d2b9 | ||
|
|
f18a70b312 | ||
|
|
78914d7140 | ||
|
|
937b98e45b | ||
|
|
c1be16845e | ||
|
|
dcb929cde5 | ||
|
|
8aa326c513 | ||
|
|
bd02f389e5 | ||
|
|
5534aad0d4 | ||
|
|
6599e6fe7c | ||
|
|
3624f75bea | ||
|
|
0d91d43866 | ||
|
|
dcd739e4a4 | ||
|
|
631ac4bc46 | ||
|
|
7007f39766 | ||
|
|
79585b253d | ||
|
|
cc8012354f | ||
|
|
2c75fcf582 | ||
|
|
34c0ad5411 | ||
|
|
f37814fec8 | ||
|
|
0c375de6e4 | ||
|
|
f87309af3f | ||
|
|
96d0b91984 | ||
|
|
e20dc53fb8 | ||
|
|
c09822b470 | ||
|
|
6a9a26f71c | ||
|
|
b0006ee6bc | ||
|
|
b34428965e | ||
|
|
670a0b6414 | ||
|
|
b7ab9c6939 | ||
|
|
6b5af82307 | ||
|
|
2848678cdc | ||
|
|
f05347c90d | ||
|
|
94725964ea | ||
|
|
2eceb0bc0c | ||
|
|
e19d788f47 | ||
|
|
3a07d2e7cc | ||
|
|
2c8b1333d8 | ||
|
|
b1a1303a40 | ||
|
|
de22251440 | ||
|
|
203eda75e4 | ||
|
|
49fef5afb2 | ||
|
|
e3da008a9a | ||
|
|
b5ad20eb8b | ||
|
|
fbd59964c3 | ||
|
|
5a260ca3a1 | ||
|
|
ffe076e120 | ||
|
|
9d78c9dcce | ||
|
|
d0e1f9a5b6 | ||
|
|
ab2a59930c | ||
|
|
fe92082ceb | ||
|
|
5575596bfc | ||
|
|
8022fa6b32 | ||
|
|
811ae06e58 | ||
|
|
2cf5ce7ae8 | ||
|
|
1cd2b1778b | ||
|
|
7d1c3d1bd6 | ||
|
|
7586df207e | ||
|
|
ecc817f66c | ||
|
|
f73aa619e9 | ||
|
|
c667584b11 | ||
|
|
5e9d5040e7 | ||
|
|
6fdaac2c0f | ||
|
|
a46a2cfa7c | ||
|
|
561aec371d | ||
|
|
7ee7db225c | ||
|
|
be803bbe4f | ||
|
|
20f8d5788c | ||
|
|
f067417ab2 | ||
|
|
db06f0dd13 | ||
|
|
bdb2c0ba52 | ||
|
|
91335ad8db | ||
|
|
648a4f5eb4 | ||
|
|
2a457ea5f6 | ||
|
|
fd254c22fd | ||
|
|
ae4f7b06ce | ||
|
|
37ed6686f8 | ||
|
|
092e68615c | ||
|
|
b82bb84152 | ||
|
|
afeccac4aa | ||
|
|
d7cd6ce4f2 | ||
|
|
f0ff078e0e | ||
|
|
7ca96d19db | ||
|
|
3e9b20f237 | ||
|
|
bb9aef55cf | ||
|
|
935b6b9a5b | ||
|
|
5af0259f0a | ||
|
|
a436769ec1 | ||
|
|
1b1d01c1e8 | ||
|
|
2912a438e3 | ||
|
|
a3fae1dc95 | ||
|
|
80649fe082 | ||
|
|
835c834ce1 | ||
|
|
04e1edbe79 | ||
|
|
a63328d953 | ||
|
|
c7f473eb5f | ||
|
|
c07ef29054 | ||
|
|
cd071db0cb | ||
|
|
00cd5bbeb8 | ||
|
|
e462326495 | ||
|
|
c906d5ebe5 | ||
|
|
ee38b6218f | ||
|
|
cbfa1689ba | ||
|
|
c1a739f7bd | ||
|
|
6fb1a7d0c4 | ||
|
|
571ba9802e | ||
|
|
6302ea0282 | ||
|
|
6afd62b617 | ||
|
|
8431b07057 | ||
|
|
617b5c54f2 | ||
|
|
8f3a19670b | ||
|
|
afc030f13f | ||
|
|
5d74ed0bed | ||
|
|
903e7d8c80 | ||
|
|
f581c17749 | ||
|
|
41db40eb54 | ||
|
|
c87276a0ea | ||
|
|
52bedee66d | ||
|
|
7a195705af |
@@ -2,6 +2,8 @@ plugins {
|
|||||||
id "com.android.application"
|
id "com.android.application"
|
||||||
id "kotlin-android"
|
id "kotlin-android"
|
||||||
id "dev.flutter.flutter-gradle-plugin"
|
id "dev.flutter.flutter-gradle-plugin"
|
||||||
|
id "com.google.gms.google-services"
|
||||||
|
id "com.google.firebase.crashlytics"
|
||||||
}
|
}
|
||||||
|
|
||||||
def localProperties = new Properties()
|
def localProperties = new Properties()
|
||||||
@@ -23,7 +25,7 @@ if (flutterVersionName == null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace "com.example.enaklo_pos"
|
namespace "com.appscale.pos"
|
||||||
compileSdkVersion 35
|
compileSdkVersion 35
|
||||||
ndkVersion flutter.ndkVersion
|
ndkVersion flutter.ndkVersion
|
||||||
|
|
||||||
@@ -42,10 +44,10 @@ android {
|
|||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||||
applicationId "com.example.enaklo_pos"
|
applicationId "com.appscale.pos"
|
||||||
// You can update the following values to match your application needs.
|
// 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.
|
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
|
||||||
minSdkVersion 21
|
minSdkVersion flutter.minSdkVersion
|
||||||
targetSdkVersion 35
|
targetSdkVersion 35
|
||||||
versionCode flutterVersionCode.toInteger()
|
versionCode flutterVersionCode.toInteger()
|
||||||
versionName flutterVersionName
|
versionName flutterVersionName
|
||||||
@@ -69,4 +71,6 @@ dependencies {
|
|||||||
//multiDex
|
//multiDex
|
||||||
implementation 'com.android.support:multidex:1.0.3'
|
implementation 'com.android.support:multidex:1.0.3'
|
||||||
implementation 'androidx.multidex:multidex:2.0.1'
|
implementation 'androidx.multidex:multidex:2.0.1'
|
||||||
|
implementation platform('com.google.firebase:firebase-bom:34.2.0')
|
||||||
|
implementation 'com.google.firebase:firebase-crashlytics'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"project_info": {
|
||||||
|
"project_number": "1094037575589",
|
||||||
|
"project_id": "apskel-pos",
|
||||||
|
"storage_bucket": "apskel-pos.firebasestorage.app"
|
||||||
|
},
|
||||||
|
"client": [
|
||||||
|
{
|
||||||
|
"client_info": {
|
||||||
|
"mobilesdk_app_id": "1:1094037575589:android:5157684038a971a3d3fa4c",
|
||||||
|
"android_client_info": {
|
||||||
|
"package_name": "com.appscale.pos"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oauth_client": [],
|
||||||
|
"api_key": [
|
||||||
|
{
|
||||||
|
"current_key": "AIzaSyAle1ZcO4Z7wtNJUHkHEVkuBHr6mHcvPvI"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"services": {
|
||||||
|
"appinvite_service": {
|
||||||
|
"other_platform_oauth_client": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"configuration_version": "1"
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package com.example.enaklo_pos
|
package com.appscale.pos
|
||||||
|
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 5.6 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 9.4 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 983 B After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 8.3 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 7.4 KiB After Width: | Height: | Size: 19 KiB |
@@ -7,6 +7,8 @@ buildscript {
|
|||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||||
|
classpath 'com.google.gms:google-services:4.4.3'
|
||||||
|
classpath 'com.google.firebase:firebase-crashlytics-gradle:3.0.6'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<g clip-path="url(#clip0_17_4760)">
|
||||||
|
<path d="M9 13.75C6.66 13.75 2 14.92 2 17.25V19H16V17.25C16 14.92 11.34 13.75 9 13.75ZM4.34 17C5.18 16.42 7.21 15.75 9 15.75C10.79 15.75 12.82 16.42 13.66 17H4.34ZM9 12C10.93 12 12.5 10.43 12.5 8.5C12.5 6.57 10.93 5 9 5C7.07 5 5.5 6.57 5.5 8.5C5.5 10.43 7.07 12 9 12ZM9 7C9.83 7 10.5 7.67 10.5 8.5C10.5 9.33 9.83 10 9 10C8.17 10 7.5 9.33 7.5 8.5C7.5 7.67 8.17 7 9 7ZM16.04 13.81C17.2 14.65 18 15.77 18 17.25V19H22V17.25C22 15.23 18.5 14.08 16.04 13.81ZM15 12C16.93 12 18.5 10.43 18.5 8.5C18.5 6.57 16.93 5 15 5C14.46 5 13.96 5.13 13.5 5.35C14.13 6.24 14.5 7.33 14.5 8.5C14.5 9.67 14.13 10.76 13.5 11.65C13.96 11.87 14.46 12 15 12Z" fill="white"/>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<clipPath id="clip0_17_4760">
|
||||||
|
<rect width="24" height="24" fill="white"/>
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 892 B |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
Before Width: | Height: | Size: 88 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 79 KiB |
|
Before Width: | Height: | Size: 120 KiB After Width: | Height: | Size: 150 KiB |
|
Before Width: | Height: | Size: 320 B After Width: | Height: | Size: 666 B |
|
Before Width: | Height: | Size: 804 B After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 492 B After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 6.4 KiB |
|
Before Width: | Height: | Size: 804 B After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 9.8 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 9.1 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 9.8 KiB |
|
Before Width: | Height: | Size: 6.7 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 5.1 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 5.9 KiB After Width: | Height: | Size: 15 KiB |
@@ -3,15 +3,15 @@
|
|||||||
flutter_launcher_icons:
|
flutter_launcher_icons:
|
||||||
android: "launcher_icon"
|
android: "launcher_icon"
|
||||||
ios: true
|
ios: true
|
||||||
image_path: "assets/logo/ic_launcher.png"
|
image_path: "assets/logo/logo.png"
|
||||||
remove_alpha_ios: true
|
remove_alpha_ios: true
|
||||||
min_sdk_android: 21 # android min sdk min:16, default 21
|
min_sdk_android: 21 # android min sdk min:16, default 21
|
||||||
adaptive_icon_background: "#ffffff"
|
adaptive_icon_background: "#ffffff"
|
||||||
adaptive_icon_foreground: "assets/logo/ic_launcher.png"
|
adaptive_icon_foreground: "assets/logo/logo.png"
|
||||||
web:
|
web:
|
||||||
generate: true
|
generate: true
|
||||||
image_path: "assets/logo/ic_launcher.png"
|
image_path: "assets/logo/logo.png"
|
||||||
windows:
|
windows:
|
||||||
generate: true
|
generate: true
|
||||||
image_path: "assets/logo/ic_launcher.png"
|
image_path: "assets/logo/logo.png"
|
||||||
icon_size: 48
|
icon_size: 48
|
||||||
|
|||||||
@@ -101,6 +101,9 @@ class $AssetsIconsGen {
|
|||||||
/// File path: assets/icons/payments.svg
|
/// File path: assets/icons/payments.svg
|
||||||
SvgGenImage get payments => const SvgGenImage('assets/icons/payments.svg');
|
SvgGenImage get payments => const SvgGenImage('assets/icons/payments.svg');
|
||||||
|
|
||||||
|
/// File path: assets/icons/people.svg
|
||||||
|
SvgGenImage get people => const SvgGenImage('assets/icons/people.svg');
|
||||||
|
|
||||||
/// File path: assets/icons/print.svg
|
/// File path: assets/icons/print.svg
|
||||||
SvgGenImage get print => const SvgGenImage('assets/icons/print.svg');
|
SvgGenImage get print => const SvgGenImage('assets/icons/print.svg');
|
||||||
|
|
||||||
@@ -152,6 +155,7 @@ class $AssetsIconsGen {
|
|||||||
orders,
|
orders,
|
||||||
pajak,
|
pajak,
|
||||||
payments,
|
payments,
|
||||||
|
people,
|
||||||
print,
|
print,
|
||||||
qrCode,
|
qrCode,
|
||||||
report,
|
report,
|
||||||
@@ -186,6 +190,12 @@ class $AssetsImagesGen {
|
|||||||
/// File path: assets/images/drink7.png
|
/// File path: assets/images/drink7.png
|
||||||
AssetGenImage get drink7 => const AssetGenImage('assets/images/drink7.png');
|
AssetGenImage get drink7 => const AssetGenImage('assets/images/drink7.png');
|
||||||
|
|
||||||
|
/// File path: assets/images/gojek.png
|
||||||
|
AssetGenImage get gojek => const AssetGenImage('assets/images/gojek.png');
|
||||||
|
|
||||||
|
/// File path: assets/images/grab.png
|
||||||
|
AssetGenImage get grab => const AssetGenImage('assets/images/grab.png');
|
||||||
|
|
||||||
/// File path: assets/images/logo.png
|
/// File path: assets/images/logo.png
|
||||||
AssetGenImage get logo => const AssetGenImage('assets/images/logo.png');
|
AssetGenImage get logo => const AssetGenImage('assets/images/logo.png');
|
||||||
|
|
||||||
@@ -265,6 +275,8 @@ class $AssetsImagesGen {
|
|||||||
drink5,
|
drink5,
|
||||||
drink6,
|
drink6,
|
||||||
drink7,
|
drink7,
|
||||||
|
gojek,
|
||||||
|
grab,
|
||||||
logo,
|
logo,
|
||||||
managePrinter,
|
managePrinter,
|
||||||
manageProduct,
|
manageProduct,
|
||||||
@@ -292,12 +304,8 @@ class $AssetsImagesGen {
|
|||||||
class $AssetsLogoGen {
|
class $AssetsLogoGen {
|
||||||
const $AssetsLogoGen();
|
const $AssetsLogoGen();
|
||||||
|
|
||||||
/// File path: assets/logo/ic_launcher.png
|
/// File path: assets/logo/logo.png
|
||||||
AssetGenImage get icLauncher =>
|
AssetGenImage get logo => const AssetGenImage('assets/logo/logo.png');
|
||||||
const AssetGenImage('assets/logo/ic_launcher.png');
|
|
||||||
|
|
||||||
/// File path: assets/logo/logo.jpeg
|
|
||||||
AssetGenImage get logo => const AssetGenImage('assets/logo/logo.jpeg');
|
|
||||||
|
|
||||||
/// File path: assets/logo/logo2.png
|
/// File path: assets/logo/logo2.png
|
||||||
AssetGenImage get logo2 => const AssetGenImage('assets/logo/logo2.png');
|
AssetGenImage get logo2 => const AssetGenImage('assets/logo/logo2.png');
|
||||||
@@ -322,17 +330,8 @@ class $AssetsLogoGen {
|
|||||||
AssetGenImage get mylogo => const AssetGenImage('assets/logo/mylogo.png');
|
AssetGenImage get mylogo => const AssetGenImage('assets/logo/mylogo.png');
|
||||||
|
|
||||||
/// List of all assets
|
/// List of all assets
|
||||||
List<AssetGenImage> get values => [
|
List<AssetGenImage> get values =>
|
||||||
icLauncher,
|
[logo, logo2, logo3, logo4, logo5, logo6, logoAppIcon, mylogo];
|
||||||
logo,
|
|
||||||
logo2,
|
|
||||||
logo3,
|
|
||||||
logo4,
|
|
||||||
logo5,
|
|
||||||
logo6,
|
|
||||||
logoAppIcon,
|
|
||||||
mylogo
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class Assets {
|
class Assets {
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ class Button extends StatelessWidget {
|
|||||||
this.crossAxisAlignment = CrossAxisAlignment.center,
|
this.crossAxisAlignment = CrossAxisAlignment.center,
|
||||||
});
|
});
|
||||||
|
|
||||||
final Function() onPressed;
|
final Function()? onPressed;
|
||||||
final String label;
|
final String label;
|
||||||
final ButtonStyle style;
|
final ButtonStyle style;
|
||||||
final Color color;
|
final Color color;
|
||||||
|
|||||||
@@ -70,7 +70,8 @@ class _CustomDatePickerState extends State<CustomDatePicker> {
|
|||||||
),
|
),
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
suffixIcon: Padding(
|
suffixIcon: Padding(
|
||||||
padding: const EdgeInsets.all(16.0),
|
padding: const EdgeInsets.symmetric(
|
||||||
|
vertical: 8, horizontal: 16),
|
||||||
child: Assets.icons.calendar.svg(),
|
child: Assets.icons.calendar.svg(),
|
||||||
),
|
),
|
||||||
prefix: widget.prefix,
|
prefix: widget.prefix,
|
||||||
|
|||||||
@@ -102,9 +102,11 @@ class CustomModalDialog extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Padding(
|
Flexible(
|
||||||
padding: contentPadding ?? EdgeInsets.zero,
|
child: SingleChildScrollView(
|
||||||
child: child,
|
padding: contentPadding ?? EdgeInsets.zero,
|
||||||
|
child: child,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ class CustomTextField extends StatelessWidget {
|
|||||||
final Widget? prefixIcon;
|
final Widget? prefixIcon;
|
||||||
final Widget? suffixIcon;
|
final Widget? suffixIcon;
|
||||||
final bool readOnly;
|
final bool readOnly;
|
||||||
|
final int maxLines;
|
||||||
|
final String? Function(String?)? validator;
|
||||||
|
|
||||||
const CustomTextField({
|
const CustomTextField({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -28,6 +30,8 @@ class CustomTextField extends StatelessWidget {
|
|||||||
this.prefixIcon,
|
this.prefixIcon,
|
||||||
this.suffixIcon,
|
this.suffixIcon,
|
||||||
this.readOnly = false,
|
this.readOnly = false,
|
||||||
|
this.maxLines = 1,
|
||||||
|
this.validator,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -53,17 +57,11 @@ class CustomTextField extends StatelessWidget {
|
|||||||
textInputAction: textInputAction,
|
textInputAction: textInputAction,
|
||||||
textCapitalization: textCapitalization ?? TextCapitalization.none,
|
textCapitalization: textCapitalization ?? TextCapitalization.none,
|
||||||
readOnly: readOnly,
|
readOnly: readOnly,
|
||||||
|
maxLines: maxLines,
|
||||||
|
validator: validator,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
prefixIcon: prefixIcon,
|
prefixIcon: prefixIcon,
|
||||||
suffixIcon: suffixIcon,
|
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,
|
hintText: label,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,409 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
|
||||||
|
|
||||||
|
class DateRangePickerModal {
|
||||||
|
static Future<DateRangePickerSelectionChangedArgs?> show({
|
||||||
|
required BuildContext context,
|
||||||
|
String title = 'Pilih Rentang Tanggal',
|
||||||
|
DateTime? initialStartDate,
|
||||||
|
DateTime? initialEndDate,
|
||||||
|
DateTime? minDate,
|
||||||
|
DateTime? maxDate,
|
||||||
|
String confirmText = 'Pilih',
|
||||||
|
String cancelText = 'Batal',
|
||||||
|
Color primaryColor = Colors.blue,
|
||||||
|
Function(DateTime? startDate, DateTime? endDate)? onChanged,
|
||||||
|
}) async {
|
||||||
|
return await showDialog<DateRangePickerSelectionChangedArgs?>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (BuildContext context) => _DateRangePickerDialog(
|
||||||
|
title: title,
|
||||||
|
initialStartDate: initialStartDate,
|
||||||
|
initialEndDate: initialEndDate,
|
||||||
|
minDate: minDate,
|
||||||
|
maxDate: maxDate,
|
||||||
|
confirmText: confirmText,
|
||||||
|
cancelText: cancelText,
|
||||||
|
primaryColor: primaryColor,
|
||||||
|
onChanged: onChanged,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DateRangePickerDialog extends StatefulWidget {
|
||||||
|
final String title;
|
||||||
|
final DateTime? initialStartDate;
|
||||||
|
final DateTime? initialEndDate;
|
||||||
|
final DateTime? minDate;
|
||||||
|
final DateTime? maxDate;
|
||||||
|
final String confirmText;
|
||||||
|
final String cancelText;
|
||||||
|
final Color primaryColor;
|
||||||
|
final Function(DateTime? startDate, DateTime? endDate)? onChanged;
|
||||||
|
|
||||||
|
const _DateRangePickerDialog({
|
||||||
|
required this.title,
|
||||||
|
this.initialStartDate,
|
||||||
|
this.initialEndDate,
|
||||||
|
this.minDate,
|
||||||
|
this.maxDate,
|
||||||
|
required this.confirmText,
|
||||||
|
required this.cancelText,
|
||||||
|
required this.primaryColor,
|
||||||
|
this.onChanged,
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_DateRangePickerDialog> createState() => _DateRangePickerDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DateRangePickerDialogState extends State<_DateRangePickerDialog>
|
||||||
|
with TickerProviderStateMixin {
|
||||||
|
DateRangePickerSelectionChangedArgs? _selectionChangedArgs;
|
||||||
|
late AnimationController _animationController;
|
||||||
|
late Animation<double> _scaleAnimation;
|
||||||
|
late Animation<double> _fadeAnimation;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_animationController = AnimationController(
|
||||||
|
duration: const Duration(milliseconds: 300),
|
||||||
|
vsync: this,
|
||||||
|
);
|
||||||
|
_scaleAnimation = Tween<double>(
|
||||||
|
begin: 0.8,
|
||||||
|
end: 1.0,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: _animationController,
|
||||||
|
curve: Curves.elasticOut,
|
||||||
|
));
|
||||||
|
_fadeAnimation = Tween<double>(
|
||||||
|
begin: 0.0,
|
||||||
|
end: 1.0,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: _animationController,
|
||||||
|
curve: Curves.easeInOut,
|
||||||
|
));
|
||||||
|
_animationController.forward();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_animationController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onSelectionChanged(DateRangePickerSelectionChangedArgs args) {
|
||||||
|
setState(() {
|
||||||
|
_selectionChangedArgs = args;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Note: onChanged callback is now called only when confirm button is pressed
|
||||||
|
// This allows users to see real-time selection without triggering callbacks
|
||||||
|
}
|
||||||
|
|
||||||
|
String _getSelectionText() {
|
||||||
|
if (_selectionChangedArgs?.value is PickerDateRange) {
|
||||||
|
final PickerDateRange range = _selectionChangedArgs!.value;
|
||||||
|
if (range.startDate != null && range.endDate != null) {
|
||||||
|
return '${_formatDate(range.startDate!)} - ${_formatDate(range.endDate!)}';
|
||||||
|
} else if (range.startDate != null) {
|
||||||
|
return _formatDate(range.startDate!);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'Belum ada tanggal dipilih';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatDate(DateTime date) {
|
||||||
|
final months = [
|
||||||
|
'Jan',
|
||||||
|
'Feb',
|
||||||
|
'Mar',
|
||||||
|
'Apr',
|
||||||
|
'Mei',
|
||||||
|
'Jun',
|
||||||
|
'Jul',
|
||||||
|
'Agu',
|
||||||
|
'Sep',
|
||||||
|
'Okt',
|
||||||
|
'Nov',
|
||||||
|
'Des'
|
||||||
|
];
|
||||||
|
return '${date.day} ${months[date.month - 1]} ${date.year}';
|
||||||
|
}
|
||||||
|
|
||||||
|
bool get _isValidSelection {
|
||||||
|
if (_selectionChangedArgs?.value is PickerDateRange) {
|
||||||
|
final PickerDateRange range = _selectionChangedArgs!.value;
|
||||||
|
return range.startDate != null && range.endDate != null;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AnimatedBuilder(
|
||||||
|
animation: _animationController,
|
||||||
|
builder: (context, child) {
|
||||||
|
return FadeTransition(
|
||||||
|
opacity: _fadeAnimation,
|
||||||
|
child: ScaleTransition(
|
||||||
|
scale: _scaleAnimation,
|
||||||
|
child: Dialog(
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
elevation: 0,
|
||||||
|
insetPadding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
|
||||||
|
child: Container(
|
||||||
|
width: MediaQuery.of(context).size.width,
|
||||||
|
constraints: BoxConstraints(
|
||||||
|
maxWidth: 400,
|
||||||
|
maxHeight: MediaQuery.of(context).size.height * 0.85,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.white,
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Colors.black.withOpacity(0.1),
|
||||||
|
blurRadius: 20,
|
||||||
|
offset: const Offset(0, 10),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
// Header
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
colors: [
|
||||||
|
widget.primaryColor,
|
||||||
|
widget.primaryColor.withOpacity(0.8),
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
borderRadius: const BorderRadius.only(
|
||||||
|
topLeft: Radius.circular(20),
|
||||||
|
topRight: Radius.circular(20),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.calendar_today_rounded,
|
||||||
|
color: Colors.white,
|
||||||
|
size: 24,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
widget.title,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 18,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Scrollable Content
|
||||||
|
Flexible(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
// Selection Info
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
margin: const EdgeInsets.all(16),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: widget.primaryColor.withOpacity(0.1),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
border: Border.all(
|
||||||
|
color: widget.primaryColor.withOpacity(0.2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Tanggal Terpilih:',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
color: widget.primaryColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
_getSelectionText(),
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Colors.black87,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Date Picker
|
||||||
|
Padding(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Container(
|
||||||
|
height: 320,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
border: Border.all(
|
||||||
|
color: Colors.grey.withOpacity(0.2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: SfDateRangePicker(
|
||||||
|
onSelectionChanged: _onSelectionChanged,
|
||||||
|
selectionMode:
|
||||||
|
DateRangePickerSelectionMode.range,
|
||||||
|
initialSelectedRange:
|
||||||
|
(widget.initialStartDate != null &&
|
||||||
|
widget.initialEndDate != null)
|
||||||
|
? PickerDateRange(
|
||||||
|
widget.initialStartDate,
|
||||||
|
widget.initialEndDate,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
minDate: widget.minDate,
|
||||||
|
maxDate: widget.maxDate,
|
||||||
|
startRangeSelectionColor: widget.primaryColor,
|
||||||
|
endRangeSelectionColor: widget.primaryColor,
|
||||||
|
rangeSelectionColor:
|
||||||
|
widget.primaryColor.withOpacity(0.2),
|
||||||
|
todayHighlightColor: widget.primaryColor,
|
||||||
|
headerStyle: DateRangePickerHeaderStyle(
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
textStyle: const TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
color: Colors.black87,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
monthViewSettings:
|
||||||
|
DateRangePickerMonthViewSettings(
|
||||||
|
viewHeaderStyle:
|
||||||
|
DateRangePickerViewHeaderStyle(
|
||||||
|
backgroundColor:
|
||||||
|
Colors.grey.withOpacity(0.1),
|
||||||
|
textStyle: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: widget.primaryColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
selectionTextStyle: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
fontSize: 14,
|
||||||
|
),
|
||||||
|
rangeTextStyle: TextStyle(
|
||||||
|
color: widget.primaryColor,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
fontSize: 14,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Action Buttons
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: OutlinedButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
style: OutlinedButton.styleFrom(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(vertical: 14),
|
||||||
|
side: BorderSide(color: Colors.grey.shade400),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
widget.cancelText,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Colors.grey,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 16),
|
||||||
|
Expanded(
|
||||||
|
child: ElevatedButton(
|
||||||
|
onPressed: _isValidSelection
|
||||||
|
? () {
|
||||||
|
// Call onChanged when confirm button is pressed
|
||||||
|
if (widget.onChanged != null &&
|
||||||
|
_selectionChangedArgs?.value
|
||||||
|
is PickerDateRange) {
|
||||||
|
final PickerDateRange range =
|
||||||
|
_selectionChangedArgs!.value;
|
||||||
|
widget.onChanged!(
|
||||||
|
range.startDate, range.endDate);
|
||||||
|
}
|
||||||
|
Navigator.of(context)
|
||||||
|
.pop(_selectionChangedArgs);
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
style: ElevatedButton.styleFrom(
|
||||||
|
backgroundColor: widget.primaryColor,
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(vertical: 14),
|
||||||
|
elevation: 2,
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
disabledBackgroundColor: Colors.grey.shade300,
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
widget.confirmText,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: _isValidSelection
|
||||||
|
? Colors.white
|
||||||
|
: Colors.grey.shade600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import 'package:another_flushbar/flushbar.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class AppFlushbar {
|
||||||
|
static void showSuccess(BuildContext context, String message) {
|
||||||
|
Flushbar(
|
||||||
|
messageText: Text(
|
||||||
|
message,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
icon: const Icon(
|
||||||
|
Icons.check_circle,
|
||||||
|
color: Colors.white,
|
||||||
|
),
|
||||||
|
duration: const Duration(seconds: 2),
|
||||||
|
flushbarPosition: FlushbarPosition.BOTTOM,
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
margin: const EdgeInsets.all(12),
|
||||||
|
).show(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void showError(BuildContext context, String message) {
|
||||||
|
Flushbar(
|
||||||
|
messageText: Text(
|
||||||
|
message,
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
icon: const Icon(
|
||||||
|
Icons.error,
|
||||||
|
color: Colors.white,
|
||||||
|
),
|
||||||
|
duration: const Duration(seconds: 3),
|
||||||
|
flushbarPosition: FlushbarPosition.BOTTOM,
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
margin: const EdgeInsets.all(12),
|
||||||
|
).show(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,91 +1,189 @@
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:enaklo_pos/presentation/setting/bloc/upload_file/upload_file_bloc.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||||
import 'package:image_picker/image_picker.dart';
|
import 'package:image_picker/image_picker.dart';
|
||||||
import 'package:cached_network_image/cached_network_image.dart';
|
import 'package:cached_network_image/cached_network_image.dart';
|
||||||
|
|
||||||
import '../assets/assets.gen.dart';
|
|
||||||
import '../constants/colors.dart';
|
import '../constants/colors.dart';
|
||||||
import '../constants/variables.dart';
|
import '../constants/variables.dart';
|
||||||
import 'buttons.dart';
|
|
||||||
import 'spaces.dart';
|
import 'spaces.dart';
|
||||||
|
|
||||||
class ImagePickerWidget extends StatefulWidget {
|
class ImagePickerWidget extends StatefulWidget {
|
||||||
final String label;
|
final String label;
|
||||||
final void Function(XFile? file) onChanged;
|
final void Function(XFile? file) onChanged;
|
||||||
|
final void Function(String? uploadedUrl)? onUploaded;
|
||||||
final bool showLabel;
|
final bool showLabel;
|
||||||
final String? initialImageUrl;
|
final String? initialImageUrl;
|
||||||
|
final bool autoUpload;
|
||||||
|
|
||||||
const ImagePickerWidget({
|
const ImagePickerWidget({
|
||||||
super.key,
|
super.key,
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.onChanged,
|
required this.onChanged,
|
||||||
|
this.onUploaded,
|
||||||
this.showLabel = true,
|
this.showLabel = true,
|
||||||
this.initialImageUrl,
|
this.initialImageUrl,
|
||||||
|
this.autoUpload = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
|
State<ImagePickerWidget> createState() => _ImagePickerWidgetState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _ImagePickerWidgetState extends State<ImagePickerWidget> {
|
class _ImagePickerWidgetState extends State<ImagePickerWidget>
|
||||||
|
with TickerProviderStateMixin {
|
||||||
String? imagePath;
|
String? imagePath;
|
||||||
|
String? uploadedImageUrl;
|
||||||
bool hasInitialImage = false;
|
bool hasInitialImage = false;
|
||||||
|
bool isHovering = false;
|
||||||
|
bool isUploading = false;
|
||||||
|
late AnimationController _scaleController;
|
||||||
|
late AnimationController _fadeController;
|
||||||
|
late AnimationController _uploadController;
|
||||||
|
late Animation<double> _scaleAnimation;
|
||||||
|
late Animation<double> _fadeAnimation;
|
||||||
|
late Animation<double> _uploadAnimation;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
hasInitialImage = widget.initialImageUrl != null;
|
hasInitialImage = widget.initialImageUrl != null;
|
||||||
|
|
||||||
|
_scaleController = AnimationController(
|
||||||
|
duration: const Duration(milliseconds: 200),
|
||||||
|
vsync: this,
|
||||||
|
);
|
||||||
|
_fadeController = AnimationController(
|
||||||
|
duration: const Duration(milliseconds: 300),
|
||||||
|
vsync: this,
|
||||||
|
);
|
||||||
|
_uploadController = AnimationController(
|
||||||
|
duration: const Duration(milliseconds: 1000),
|
||||||
|
vsync: this,
|
||||||
|
);
|
||||||
|
|
||||||
|
_scaleAnimation = Tween<double>(
|
||||||
|
begin: 1.0,
|
||||||
|
end: 0.95,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: _scaleController,
|
||||||
|
curve: Curves.easeInOut,
|
||||||
|
));
|
||||||
|
|
||||||
|
_fadeAnimation = Tween<double>(
|
||||||
|
begin: 0.0,
|
||||||
|
end: 1.0,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: _fadeController,
|
||||||
|
curve: Curves.easeInOut,
|
||||||
|
));
|
||||||
|
|
||||||
|
_uploadAnimation = Tween<double>(
|
||||||
|
begin: 0.0,
|
||||||
|
end: 1.0,
|
||||||
|
).animate(CurvedAnimation(
|
||||||
|
parent: _uploadController,
|
||||||
|
curve: Curves.easeInOut,
|
||||||
|
));
|
||||||
|
|
||||||
|
_fadeController.forward();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_scaleController.dispose();
|
||||||
|
_fadeController.dispose();
|
||||||
|
_uploadController.dispose();
|
||||||
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _pickImage() async {
|
Future<void> _pickImage() async {
|
||||||
|
_scaleController.forward().then((_) {
|
||||||
|
_scaleController.reverse();
|
||||||
|
});
|
||||||
|
|
||||||
final pickedFile = await ImagePicker().pickImage(
|
final pickedFile = await ImagePicker().pickImage(
|
||||||
source: ImageSource.gallery,
|
source: ImageSource.gallery,
|
||||||
);
|
);
|
||||||
|
|
||||||
setState(() {
|
if (pickedFile != null) {
|
||||||
if (pickedFile != null) {
|
setState(() {
|
||||||
imagePath = pickedFile.path;
|
imagePath = pickedFile.path;
|
||||||
hasInitialImage = false; // Clear initial image when new image is picked
|
hasInitialImage = false;
|
||||||
widget.onChanged(pickedFile);
|
uploadedImageUrl = null;
|
||||||
} else {
|
});
|
||||||
debugPrint('No image selected.');
|
|
||||||
widget.onChanged(null);
|
widget.onChanged(pickedFile);
|
||||||
|
|
||||||
|
// Auto upload if enabled
|
||||||
|
if (widget.autoUpload) {
|
||||||
|
_uploadImage(pickedFile.path);
|
||||||
}
|
}
|
||||||
});
|
} else {
|
||||||
|
debugPrint('No image selected.');
|
||||||
|
widget.onChanged(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
void _uploadImage(String filePath) {
|
||||||
Widget build(BuildContext context) {
|
setState(() {
|
||||||
return Column(
|
isUploading = true;
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
});
|
||||||
children: [
|
_uploadController.forward();
|
||||||
if (widget.showLabel) ...[
|
|
||||||
Text(
|
context.read<UploadFileBloc>().add(
|
||||||
widget.label,
|
UploadFileEvent.upload(filePath),
|
||||||
style: const TextStyle(
|
);
|
||||||
fontSize: 14,
|
}
|
||||||
fontWeight: FontWeight.w700,
|
|
||||||
),
|
Widget _buildImageContainer() {
|
||||||
|
return Container(
|
||||||
|
width: 100.0,
|
||||||
|
height: 100.0,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(20.0),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Colors.black.withOpacity(0.1),
|
||||||
|
blurRadius: 10,
|
||||||
|
offset: const Offset(0, 4),
|
||||||
),
|
),
|
||||||
const SpaceHeight(12.0),
|
|
||||||
],
|
],
|
||||||
Container(
|
),
|
||||||
padding: const EdgeInsets.all(6.0),
|
child: ClipRRect(
|
||||||
decoration: BoxDecoration(
|
borderRadius: BorderRadius.circular(20.0),
|
||||||
borderRadius: BorderRadius.circular(16.0),
|
child: Stack(
|
||||||
border: Border.all(color: AppColors.primary),
|
children: [
|
||||||
),
|
Positioned.fill(
|
||||||
child: Row(
|
child: imagePath != null
|
||||||
children: [
|
? Image.file(
|
||||||
SizedBox(
|
File(imagePath!),
|
||||||
width: 80.0,
|
fit: BoxFit.cover,
|
||||||
height: 80.0,
|
)
|
||||||
child: ClipRRect(
|
: uploadedImageUrl != null
|
||||||
borderRadius: BorderRadius.circular(10.0),
|
? CachedNetworkImage(
|
||||||
child: imagePath != null
|
imageUrl: uploadedImageUrl!.contains('http')
|
||||||
? Image.file(
|
? uploadedImageUrl!
|
||||||
File(imagePath!),
|
: '${Variables.baseUrl}/$uploadedImageUrl',
|
||||||
|
placeholder: (context, url) => Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
colors: [
|
||||||
|
AppColors.primary.withOpacity(0.1),
|
||||||
|
AppColors.primary.withOpacity(0.05),
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Center(
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
errorWidget: (context, url, error) =>
|
||||||
|
_buildPlaceholder(),
|
||||||
fit: BoxFit.cover,
|
fit: BoxFit.cover,
|
||||||
)
|
)
|
||||||
: hasInitialImage && widget.initialImageUrl != null
|
: hasInitialImage && widget.initialImageUrl != null
|
||||||
@@ -93,38 +191,493 @@ class _ImagePickerWidgetState extends State<ImagePickerWidget> {
|
|||||||
imageUrl: widget.initialImageUrl!.contains('http')
|
imageUrl: widget.initialImageUrl!.contains('http')
|
||||||
? widget.initialImageUrl!
|
? widget.initialImageUrl!
|
||||||
: '${Variables.baseUrl}/${widget.initialImageUrl}',
|
: '${Variables.baseUrl}/${widget.initialImageUrl}',
|
||||||
placeholder: (context, url) =>
|
placeholder: (context, url) => Container(
|
||||||
const Center(child: CircularProgressIndicator()),
|
decoration: BoxDecoration(
|
||||||
errorWidget: (context, url, error) => Container(
|
gradient: LinearGradient(
|
||||||
padding: const EdgeInsets.all(16.0),
|
colors: [
|
||||||
color: AppColors.black.withOpacity(0.05),
|
AppColors.primary.withOpacity(0.1),
|
||||||
child: Assets.icons.image.svg(),
|
AppColors.primary.withOpacity(0.05),
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Center(
|
||||||
|
child:
|
||||||
|
CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
|
errorWidget: (context, url, error) =>
|
||||||
|
_buildPlaceholder(),
|
||||||
fit: BoxFit.cover,
|
fit: BoxFit.cover,
|
||||||
)
|
)
|
||||||
: Container(
|
: _buildPlaceholder(),
|
||||||
padding: const EdgeInsets.all(16.0),
|
),
|
||||||
color: AppColors.black.withOpacity(0.05),
|
// Upload progress overlay
|
||||||
child: Assets.icons.image.svg(),
|
if (isUploading)
|
||||||
),
|
Positioned.fill(
|
||||||
|
child: Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.black.withOpacity(0.6),
|
||||||
|
),
|
||||||
|
child: Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
color: Colors.white,
|
||||||
|
strokeWidth: 2,
|
||||||
|
value: _uploadAnimation.value == 1.0
|
||||||
|
? null
|
||||||
|
: _uploadAnimation.value,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const Text(
|
||||||
|
'Uploading...',
|
||||||
|
style: TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const Spacer(),
|
// Overlay gradient for better button visibility
|
||||||
Padding(
|
if ((imagePath != null ||
|
||||||
padding: const EdgeInsets.only(right: 10.0),
|
uploadedImageUrl != null ||
|
||||||
child: Button.filled(
|
(hasInitialImage && widget.initialImageUrl != null)) &&
|
||||||
height: 30.0,
|
!isUploading)
|
||||||
width: 140.0,
|
Positioned.fill(
|
||||||
onPressed: _pickImage,
|
child: Container(
|
||||||
label: 'Choose Photo',
|
decoration: BoxDecoration(
|
||||||
fontSize: 12.0,
|
gradient: LinearGradient(
|
||||||
borderRadius: 5.0,
|
colors: [
|
||||||
|
Colors.transparent,
|
||||||
|
Colors.black.withOpacity(0.3),
|
||||||
|
],
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildPlaceholder() {
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
colors: [
|
||||||
|
AppColors.primary.withOpacity(0.1),
|
||||||
|
AppColors.primary.withOpacity(0.05),
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.add_photo_alternate_outlined,
|
||||||
|
size: 32,
|
||||||
|
color: AppColors.primary.withOpacity(0.6),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'Photo',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
color: AppColors.primary.withOpacity(0.6),
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildActionButton() {
|
||||||
|
bool hasImage = imagePath != null ||
|
||||||
|
uploadedImageUrl != null ||
|
||||||
|
(hasInitialImage && widget.initialImageUrl != null);
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
gradient: LinearGradient(
|
||||||
|
colors: [
|
||||||
|
AppColors.primary,
|
||||||
|
AppColors.primary.withOpacity(0.8),
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: AppColors.primary.withOpacity(0.3),
|
||||||
|
blurRadius: 8,
|
||||||
|
offset: const Offset(0, 4),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
child: Material(
|
||||||
|
color: Colors.transparent,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: isUploading ? null : _pickImage,
|
||||||
|
onHover: (hover) {
|
||||||
|
setState(() {
|
||||||
|
isHovering = hover;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: AnimatedContainer(
|
||||||
|
duration: const Duration(milliseconds: 200),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
color: isHovering
|
||||||
|
? Colors.white.withOpacity(0.1)
|
||||||
|
: Colors.transparent,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
isUploading
|
||||||
|
? Icons.cloud_upload_outlined
|
||||||
|
: hasImage
|
||||||
|
? Icons.edit_outlined
|
||||||
|
: Icons.add_photo_alternate_outlined,
|
||||||
|
color: Colors.white,
|
||||||
|
size: 18,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
isUploading
|
||||||
|
? 'Uploading...'
|
||||||
|
: hasImage
|
||||||
|
? 'Change Photo'
|
||||||
|
: 'Choose Photo',
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildUploadButton() {
|
||||||
|
if (!widget.autoUpload &&
|
||||||
|
imagePath != null &&
|
||||||
|
uploadedImageUrl == null &&
|
||||||
|
!isUploading) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 12),
|
||||||
|
child: Container(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
gradient: LinearGradient(
|
||||||
|
colors: [
|
||||||
|
Colors.green.shade600,
|
||||||
|
Colors.green.shade500,
|
||||||
|
],
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Colors.green.withOpacity(0.3),
|
||||||
|
blurRadius: 8,
|
||||||
|
offset: const Offset(0, 4),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
child: Material(
|
||||||
|
color: Colors.transparent,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () => _uploadImage(imagePath!),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
child: Container(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.cloud_upload_outlined,
|
||||||
|
color: Colors.white,
|
||||||
|
size: 16,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
'Upload to Server',
|
||||||
|
style: const TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
);
|
||||||
|
}
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return BlocListener<UploadFileBloc, UploadFileState>(
|
||||||
|
listener: (context, state) {
|
||||||
|
state.when(
|
||||||
|
initial: () {},
|
||||||
|
loading: () {
|
||||||
|
if (!isUploading) {
|
||||||
|
setState(() {
|
||||||
|
isUploading = true;
|
||||||
|
});
|
||||||
|
_uploadController.repeat();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
success: (fileData) {
|
||||||
|
setState(() {
|
||||||
|
isUploading = false;
|
||||||
|
uploadedImageUrl = fileData.fileUrl;
|
||||||
|
});
|
||||||
|
_uploadController.reset();
|
||||||
|
|
||||||
|
if (widget.onUploaded != null) {
|
||||||
|
widget.onUploaded!(fileData.fileUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.check_circle, color: Colors.white),
|
||||||
|
SizedBox(width: 8),
|
||||||
|
Text('Image uploaded successfully!'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
backgroundColor: Colors.green,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
duration: Duration(seconds: 2),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
error: (message) {
|
||||||
|
setState(() {
|
||||||
|
isUploading = false;
|
||||||
|
});
|
||||||
|
_uploadController.reset();
|
||||||
|
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Icons.error_outline, color: Colors.white),
|
||||||
|
SizedBox(width: 8),
|
||||||
|
Expanded(child: Text('Upload failed: $message')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
backgroundColor: Colors.red,
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
),
|
||||||
|
duration: Duration(seconds: 3),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
child: FadeTransition(
|
||||||
|
opacity: _fadeAnimation,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (widget.showLabel) ...[
|
||||||
|
Text(
|
||||||
|
widget.label,
|
||||||
|
style: const TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
color: Colors.black87,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SpaceHeight(16.0),
|
||||||
|
],
|
||||||
|
ScaleTransition(
|
||||||
|
scale: _scaleAnimation,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.all(20.0),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(24.0),
|
||||||
|
color: Colors.white,
|
||||||
|
border: Border.all(
|
||||||
|
color: isUploading
|
||||||
|
? Colors.orange.withOpacity(0.5)
|
||||||
|
: uploadedImageUrl != null
|
||||||
|
? Colors.green.withOpacity(0.5)
|
||||||
|
: AppColors.primary.withOpacity(0.2),
|
||||||
|
width: 1.5,
|
||||||
|
),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: Colors.black.withOpacity(0.05),
|
||||||
|
blurRadius: 20,
|
||||||
|
offset: const Offset(0, 10),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
_buildImageContainer(),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
_buildActionButton(),
|
||||||
|
_buildUploadButton(),
|
||||||
|
if ((imagePath != null ||
|
||||||
|
uploadedImageUrl != null ||
|
||||||
|
(hasInitialImage &&
|
||||||
|
widget.initialImageUrl != null)) &&
|
||||||
|
!isUploading) ...[
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextButton.icon(
|
||||||
|
onPressed: () {
|
||||||
|
setState(() {
|
||||||
|
imagePath = null;
|
||||||
|
hasInitialImage = false;
|
||||||
|
uploadedImageUrl = null;
|
||||||
|
});
|
||||||
|
widget.onChanged(null);
|
||||||
|
if (widget.onUploaded != null) {
|
||||||
|
widget.onUploaded!(null);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
icon: Icon(
|
||||||
|
Icons.delete_outline,
|
||||||
|
size: 16,
|
||||||
|
color: Colors.red.shade400,
|
||||||
|
),
|
||||||
|
label: Text(
|
||||||
|
'Remove Photo',
|
||||||
|
style: TextStyle(
|
||||||
|
color: Colors.red.shade400,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
// Upload status indicator
|
||||||
|
if (uploadedImageUrl != null && !isUploading) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 12, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.green.withOpacity(0.1),
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
border:
|
||||||
|
Border.all(color: Colors.green.withOpacity(0.3)),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.cloud_done_outlined,
|
||||||
|
size: 14,
|
||||||
|
color: Colors.green.shade600,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Text(
|
||||||
|
'Uploaded',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Colors.green.shade600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Cara menggunakan widget ini:
|
||||||
|
///
|
||||||
|
/// ```dart
|
||||||
|
/// // 1. Basic usage tanpa auto upload
|
||||||
|
/// ImagePickerWidget(
|
||||||
|
/// label: 'Product Image',
|
||||||
|
/// onChanged: (file) {
|
||||||
|
/// // Handle selected file
|
||||||
|
/// print('Selected file: ${file?.path}');
|
||||||
|
/// },
|
||||||
|
/// onUploaded: (url) {
|
||||||
|
/// // Handle uploaded URL
|
||||||
|
/// print('Uploaded URL: $url');
|
||||||
|
/// },
|
||||||
|
/// )
|
||||||
|
///
|
||||||
|
/// // 2. Auto upload setelah memilih gambar
|
||||||
|
/// ImagePickerWidget(
|
||||||
|
/// label: 'Profile Picture',
|
||||||
|
/// autoUpload: true,
|
||||||
|
/// onChanged: (file) => setState(() => selectedFile = file),
|
||||||
|
/// onUploaded: (url) => setState(() => profileImageUrl = url),
|
||||||
|
/// )
|
||||||
|
///
|
||||||
|
/// // 3. Dengan initial image
|
||||||
|
/// ImagePickerWidget(
|
||||||
|
/// label: 'Banner Image',
|
||||||
|
/// initialImageUrl: existingImageUrl,
|
||||||
|
/// onChanged: (file) => handleFileChange(file),
|
||||||
|
/// onUploaded: (url) => handleUploadSuccess(url),
|
||||||
|
/// )
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Pastikan untuk wrap widget ini dengan BlocProvider:
|
||||||
|
/// ```dart
|
||||||
|
/// BlocProvider(
|
||||||
|
/// create: (context) => UploadFileBloc(
|
||||||
|
/// context.read<FileRemoteDataSource>(),
|
||||||
|
/// ),
|
||||||
|
/// child: ImagePickerWidget(...),
|
||||||
|
/// )
|
||||||
|
/// ```
|
||||||
@@ -39,4 +39,8 @@ class AppColors {
|
|||||||
static const Color stroke = Color(0xffEFF0F6);
|
static const Color stroke = Color(0xffEFF0F6);
|
||||||
|
|
||||||
static const Color background = Color.fromARGB(255, 241, 241, 241);
|
static const Color background = Color.fromARGB(255, 241, 241, 241);
|
||||||
|
|
||||||
|
static const Color primaryLight = Color(0xFF5A3E8A);
|
||||||
|
static const Color greyLight = Color(0xFFE0E0E0);
|
||||||
|
static const Color greyDark = Color(0xFF707070);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ ThemeData getApplicationTheme = ThemeData(
|
|||||||
useMaterial3: true,
|
useMaterial3: true,
|
||||||
inputDecorationTheme: InputDecorationTheme(
|
inputDecorationTheme: InputDecorationTheme(
|
||||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
|
contentPadding: const EdgeInsets.symmetric(horizontal: 16.0),
|
||||||
|
hintStyle: const TextStyle(
|
||||||
|
color: AppColors.grey,
|
||||||
|
),
|
||||||
border: OutlineInputBorder(
|
border: OutlineInputBorder(
|
||||||
borderRadius: BorderRadius.circular(8.0),
|
borderRadius: BorderRadius.circular(8.0),
|
||||||
borderSide: BorderSide(color: AppColors.primary),
|
borderSide: BorderSide(color: AppColors.primary),
|
||||||
|
|||||||
@@ -2,6 +2,6 @@ class Variables {
|
|||||||
static const String appName = 'POS Kasir Resto App';
|
static const String appName = 'POS Kasir Resto App';
|
||||||
static const String apiVersion = 'v1';
|
static const String apiVersion = 'v1';
|
||||||
// static const String baseUrl = 'http://192.168.1.202:8000';
|
// static const String baseUrl = 'http://192.168.1.202:8000';
|
||||||
static const String baseUrl = 'https://enaklo-pos-be.altru.id';
|
static const String baseUrl = 'https://api-pos.apskel.id';
|
||||||
static const int defaultLimit = 10;
|
static const int defaultLimit = 10;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
import 'package:path/path.dart';
|
||||||
|
|
||||||
|
class DatabaseHelper {
|
||||||
|
static DatabaseHelper? _instance;
|
||||||
|
static Database? _database;
|
||||||
|
|
||||||
|
DatabaseHelper._internal();
|
||||||
|
|
||||||
|
static DatabaseHelper get instance {
|
||||||
|
_instance ??= DatabaseHelper._internal();
|
||||||
|
return _instance!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Database> get database async {
|
||||||
|
_database ??= await _initDatabase();
|
||||||
|
return _database!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Database> _initDatabase() async {
|
||||||
|
String path = join(await getDatabasesPath(), 'pos_database.db');
|
||||||
|
|
||||||
|
return await openDatabase(
|
||||||
|
path,
|
||||||
|
version: 3, // Updated version for categories table
|
||||||
|
onCreate: _onCreate,
|
||||||
|
onUpgrade: _onUpgrade,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onCreate(Database db, int version) async {
|
||||||
|
// Products table
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE products (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
organization_id TEXT,
|
||||||
|
category_id TEXT,
|
||||||
|
sku TEXT,
|
||||||
|
name TEXT,
|
||||||
|
description TEXT,
|
||||||
|
price INTEGER,
|
||||||
|
cost INTEGER,
|
||||||
|
business_type TEXT,
|
||||||
|
image_url TEXT,
|
||||||
|
printer_type TEXT,
|
||||||
|
metadata TEXT,
|
||||||
|
is_active INTEGER,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
// Product Variants table
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE product_variants (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
product_id TEXT,
|
||||||
|
name TEXT,
|
||||||
|
price_modifier INTEGER,
|
||||||
|
cost INTEGER,
|
||||||
|
metadata TEXT,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT,
|
||||||
|
FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
// Categories table - NEW
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE categories (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
organization_id TEXT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
business_type TEXT,
|
||||||
|
metadata TEXT,
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
// Printer table
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE printers (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
code TEXT UNIQUE NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
address TEXT,
|
||||||
|
paper TEXT,
|
||||||
|
type TEXT,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
// Create indexes for better performance
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX idx_products_category_id ON products(category_id)');
|
||||||
|
await db.execute('CREATE INDEX idx_products_name ON products(name)');
|
||||||
|
await db.execute('CREATE INDEX idx_products_sku ON products(sku)');
|
||||||
|
await db.execute('CREATE INDEX idx_categories_name ON categories(name)');
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX idx_categories_organization_id ON categories(organization_id)');
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX idx_categories_is_active ON categories(is_active)');
|
||||||
|
await db.execute('CREATE INDEX idx_printers_code ON printers(code)');
|
||||||
|
await db.execute('CREATE INDEX idx_printers_type ON printers(type)');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
|
||||||
|
if (oldVersion < 2) {
|
||||||
|
// Add printer table in version 2
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE printers (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
code TEXT UNIQUE NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
address TEXT,
|
||||||
|
paper TEXT,
|
||||||
|
type TEXT,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
await db.execute('CREATE INDEX idx_printers_code ON printers(code)');
|
||||||
|
await db.execute('CREATE INDEX idx_printers_type ON printers(type)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldVersion < 3) {
|
||||||
|
// Add categories table in version 3
|
||||||
|
await db.execute('''
|
||||||
|
CREATE TABLE categories (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
organization_id TEXT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
description TEXT,
|
||||||
|
business_type TEXT,
|
||||||
|
metadata TEXT,
|
||||||
|
is_active INTEGER DEFAULT 1,
|
||||||
|
created_at TEXT,
|
||||||
|
updated_at TEXT
|
||||||
|
)
|
||||||
|
''');
|
||||||
|
|
||||||
|
await db.execute('CREATE INDEX idx_categories_name ON categories(name)');
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX idx_categories_organization_id ON categories(organization_id)');
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX idx_categories_is_active ON categories(is_active)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> close() async {
|
||||||
|
final db = await database;
|
||||||
|
await db.close();
|
||||||
|
_database = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
|
||||||
|
class DatabaseMigrationHandler {
|
||||||
|
static Future<void> migrate(
|
||||||
|
Database db, int oldVersion, int newVersion) async {
|
||||||
|
if (oldVersion < 2) {
|
||||||
|
// Add indexes for better performance
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX IF NOT EXISTS idx_products_name_search ON products(name)');
|
||||||
|
await db.execute(
|
||||||
|
'CREATE INDEX IF NOT EXISTS idx_products_sku_search ON products(sku)');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldVersion < 3) {
|
||||||
|
// Add full text search support
|
||||||
|
await db.execute(
|
||||||
|
'CREATE VIRTUAL TABLE products_fts USING fts5(name, sku, description, content=products, content_rowid=rowid)');
|
||||||
|
await db.execute(
|
||||||
|
'INSERT INTO products_fts SELECT name, sku, description FROM products');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (oldVersion < 4) {
|
||||||
|
// Add sync tracking
|
||||||
|
await db.execute('ALTER TABLE products ADD COLUMN last_sync_at TEXT');
|
||||||
|
await db.execute(
|
||||||
|
'ALTER TABLE products ADD COLUMN sync_version INTEGER DEFAULT 1');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
|
||||||
|
class DatabaseErrorHandler {
|
||||||
|
static Future<T> executeWithRetry<T>(
|
||||||
|
Future<T> Function() operation, {
|
||||||
|
int maxRetries = 3,
|
||||||
|
Duration delay = const Duration(milliseconds: 500),
|
||||||
|
}) async {
|
||||||
|
int attempts = 0;
|
||||||
|
|
||||||
|
while (attempts < maxRetries) {
|
||||||
|
try {
|
||||||
|
return await operation();
|
||||||
|
} catch (e) {
|
||||||
|
attempts++;
|
||||||
|
|
||||||
|
if (attempts >= maxRetries) {
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
|
||||||
|
log('Database operation failed (attempt $attempts/$maxRetries): $e');
|
||||||
|
await Future.delayed(delay * attempts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw Exception('Max retries exceeded');
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool isDatabaseCorrupted(dynamic error) {
|
||||||
|
final errorString = error.toString().toLowerCase();
|
||||||
|
return errorString.contains('corrupt') ||
|
||||||
|
errorString.contains('malformed') ||
|
||||||
|
errorString.contains('no such table');
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> handleDatabaseCorruption() async {
|
||||||
|
try {
|
||||||
|
// Delete corrupted database
|
||||||
|
final dbPath = await getDatabasesPath();
|
||||||
|
final file = File('$dbPath/pos_database.db');
|
||||||
|
if (await file.exists()) {
|
||||||
|
await file.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
log('Corrupted database deleted, will be recreated');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error handling database corruption: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:barcode_image/barcode_image.dart';
|
||||||
|
import 'package:enaklo_pos/core/extensions/string_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/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/outlet/outlet_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/printer/printer_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/order_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/type/bussines_type.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/home/models/product_quantity.dart';
|
||||||
|
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:barcode/barcode.dart';
|
||||||
|
import 'package:image/image.dart' as img;
|
||||||
|
|
||||||
|
Future<void> onPrint(
|
||||||
|
BuildContext context, {
|
||||||
|
required List<ProductQuantity> productQuantity,
|
||||||
|
required Order order,
|
||||||
|
}) async {
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
final settings = await SettingsLocalDatasource().getTax();
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
if (outlet.businessType == BusinessType.restaurant) {
|
||||||
|
final checkerPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('checker');
|
||||||
|
final kitchenPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('kitchen');
|
||||||
|
final receiptPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('receipt');
|
||||||
|
final barPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('bar');
|
||||||
|
|
||||||
|
if (receiptPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printOrderV4(
|
||||||
|
order,
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
'',
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
settings.value,
|
||||||
|
receiptPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
outlet,
|
||||||
|
productQuantity);
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(receiptPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Print receipt failed',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
'Printer: ${receiptPrinter.name}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing receipt order: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing receipt order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Receipt printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Receipt printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer receipt')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Checker printer
|
||||||
|
if (checkerPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printChecker(
|
||||||
|
productQuantity,
|
||||||
|
order.tableNumber ?? "",
|
||||||
|
order.orderNumber ?? "",
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
order.metadata?['customer_name'] ?? "",
|
||||||
|
checkerPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (productQuantity.isNotEmpty) {
|
||||||
|
await PrinterService()
|
||||||
|
// ignore: use_build_context_synchronously
|
||||||
|
.printWithPrinter(checkerPrinter, printValue, context);
|
||||||
|
}
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
log("Error printing checker: $e");
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing checker ${checkerPrinter.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: checker',
|
||||||
|
'data: ${checkerPrinter.toMap()}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing checker: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Checker printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Checker printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer checker')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kitchen printer
|
||||||
|
if (kitchenPrinter != null) {
|
||||||
|
try {
|
||||||
|
final productByPrinter = productQuantity
|
||||||
|
.where((item) => item.product.printerType == 'kitchen')
|
||||||
|
.toList();
|
||||||
|
final printValue =
|
||||||
|
await PrintDataoutputs.instance.printKitchenPerProduct(
|
||||||
|
productByPrinter,
|
||||||
|
order.tableNumber ?? "",
|
||||||
|
order.orderNumber ?? "",
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
order.metadata?['customer_name'] ?? "",
|
||||||
|
kitchenPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (productByPrinter.isNotEmpty) {
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(kitchenPrinter, printValue, context);
|
||||||
|
}
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
log("Error printing kitchen order: $e");
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing kitchen ${kitchenPrinter.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: kitchen',
|
||||||
|
'data: ${kitchenPrinter.toMap()}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing kitchen order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Kitchen printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Kitchen printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer kitchen')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bar printer
|
||||||
|
if (barPrinter != null) {
|
||||||
|
try {
|
||||||
|
final productByPrinter = productQuantity
|
||||||
|
.where((item) => item.product.printerType == 'bar')
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final printValue = await PrintDataoutputs.instance.printBar(
|
||||||
|
productByPrinter,
|
||||||
|
order.tableNumber ?? "",
|
||||||
|
order.orderNumber ?? "",
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
order.metadata?['customer_name'] ?? "",
|
||||||
|
barPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
if (productByPrinter.isNotEmpty) {
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(barPrinter, printValue, context);
|
||||||
|
}
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
log("Error printing bar order: $e");
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing bar ${barPrinter.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: bar',
|
||||||
|
'data: ${barPrinter.toMap()}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing bar order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Bar printer not found',
|
||||||
|
null,
|
||||||
|
reason: 'Bar printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer bar')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outlet.businessType == BusinessType.ticketing) {
|
||||||
|
final ticketPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('ticket');
|
||||||
|
|
||||||
|
final barcode = await generateBarcodeAsUint8List(order.orderNumber ?? "");
|
||||||
|
|
||||||
|
if (ticketPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printTicket(
|
||||||
|
order.totalAmount ?? 0,
|
||||||
|
barcode,
|
||||||
|
ticketPrinter.paper.toIntegerFromText,
|
||||||
|
);
|
||||||
|
|
||||||
|
await PrinterService()
|
||||||
|
// ignore: use_build_context_synchronously
|
||||||
|
.printWithPrinter(ticketPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing ticket ${ticketPrinter.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: ticket',
|
||||||
|
'data: ${ticketPrinter.toMap()}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing ticket: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing ticket: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Ticket printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Ticket printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer ticket')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> onPrintBill(
|
||||||
|
BuildContext context, {
|
||||||
|
required List<ProductQuantity> productQuantity,
|
||||||
|
required Order order,
|
||||||
|
}) async {
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
final settings = await SettingsLocalDatasource().getTax();
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
if (outlet.businessType == BusinessType.restaurant) {
|
||||||
|
final receiptPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('receipt');
|
||||||
|
|
||||||
|
if (receiptPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printOrderV4(
|
||||||
|
order,
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
'',
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
settings.value,
|
||||||
|
receiptPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
outlet,
|
||||||
|
productQuantity);
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(receiptPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Print receipt failed',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
'Printer: ${receiptPrinter.name}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing receipt order: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing receipt order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Receipt printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Receipt printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer receipt')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outlet.businessType == BusinessType.ticketing) {
|
||||||
|
final ticketPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('ticket');
|
||||||
|
|
||||||
|
final barcode = await generateBarcodeAsUint8List(order.orderNumber ?? "");
|
||||||
|
|
||||||
|
if (ticketPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printTicket(
|
||||||
|
order.totalAmount ?? 0,
|
||||||
|
barcode,
|
||||||
|
ticketPrinter.paper.toIntegerFromText,
|
||||||
|
);
|
||||||
|
|
||||||
|
await PrinterService()
|
||||||
|
// ignore: use_build_context_synchronously
|
||||||
|
.printWithPrinter(ticketPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing ticket ${ticketPrinter.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: ticket',
|
||||||
|
'data: ${ticketPrinter.toMap()}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing ticket: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing ticket: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Ticket printer not found',
|
||||||
|
null,
|
||||||
|
reason:
|
||||||
|
'Ticket printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer ticket')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> onPrintRecipt(
|
||||||
|
context, {
|
||||||
|
required Order order,
|
||||||
|
required String paymentMethod,
|
||||||
|
required int nominalBayar,
|
||||||
|
required int kembalian,
|
||||||
|
required List<ProductQuantity> productQuantity,
|
||||||
|
}) async {
|
||||||
|
final receiptPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('receipt');
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final settings = await SettingsLocalDatasource().getTax();
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
|
||||||
|
if (receiptPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printOrderV4(
|
||||||
|
order,
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
paymentMethod,
|
||||||
|
nominalBayar,
|
||||||
|
kembalian,
|
||||||
|
settings.value,
|
||||||
|
receiptPrinter.paper.toIntegerFromText,
|
||||||
|
order.orderType ?? "",
|
||||||
|
outlet,
|
||||||
|
productQuantity);
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(receiptPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Print receipt failed',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
'Payment Method: $paymentMethod',
|
||||||
|
'Printer: ${receiptPrinter.name}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing receipt order: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing receipt order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Kitchen printer not found',
|
||||||
|
null,
|
||||||
|
reason: 'Kitchen printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer kitchen')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> onPrinVoidRecipt(
|
||||||
|
context, {
|
||||||
|
required Order order,
|
||||||
|
required List<OrderItem> productItemVoid,
|
||||||
|
required int totalVoid,
|
||||||
|
}) async {
|
||||||
|
final receiptPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('receipt');
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final settings = await SettingsLocalDatasource().getTax();
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
|
||||||
|
if (receiptPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printVoidOrder(
|
||||||
|
order,
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
settings.value,
|
||||||
|
receiptPrinter.paper.toIntegerFromText,
|
||||||
|
totalVoid,
|
||||||
|
outlet,
|
||||||
|
productItemVoid);
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(receiptPrinter, printValue, context);
|
||||||
|
} catch (e) {
|
||||||
|
log("Error printing receipt order: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing receipt order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> onPrintSplit(
|
||||||
|
context, {
|
||||||
|
required Order order,
|
||||||
|
}) async {
|
||||||
|
final receiptPrinter =
|
||||||
|
await PrinterLocalDatasource.instance.getPrinterByCode('receipt');
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final settings = await SettingsLocalDatasource().getTax();
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
|
||||||
|
if (receiptPrinter != null) {
|
||||||
|
try {
|
||||||
|
final printValue = await PrintDataoutputs.instance.printSplitBill(
|
||||||
|
order,
|
||||||
|
authData.user?.name ?? "",
|
||||||
|
receiptPrinter.paper.toIntegerFromText,
|
||||||
|
outlet,
|
||||||
|
);
|
||||||
|
await PrinterService()
|
||||||
|
.printWithPrinter(receiptPrinter, printValue, context);
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Print receipt failed',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
'Printer: ${receiptPrinter.name}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
log("Error printing receipt order: $e");
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Error printing receipt order: $e')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Kitchen printer not found',
|
||||||
|
null,
|
||||||
|
reason: 'Kitchen printer not found / Printer not setting in printer page',
|
||||||
|
information: [
|
||||||
|
'Order ID: ${order.id}',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Anda belum menghubungkan printer kitchen')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Uint8List> generateBarcodeAsUint8List(String data) async {
|
||||||
|
// 1. Buat barcode instance (code128, qrCode, dll)
|
||||||
|
final barcode = Barcode.code128();
|
||||||
|
|
||||||
|
// 2. Siapkan canvas image dari package `image`
|
||||||
|
final image = img.Image(width: 600, height: 200);
|
||||||
|
|
||||||
|
// 3. Gambar barcode ke canvas menggunakan barcode_image
|
||||||
|
drawBarcode(
|
||||||
|
image,
|
||||||
|
barcode,
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Encode image ke Uint8List PNG
|
||||||
|
return Uint8List.fromList(img.encodePng(image));
|
||||||
|
}
|
||||||
@@ -1,15 +1,22 @@
|
|||||||
// lib/core/network/dio_client.dart
|
|
||||||
import 'package:awesome_dio_interceptor/awesome_dio_interceptor.dart';
|
import 'package:awesome_dio_interceptor/awesome_dio_interceptor.dart';
|
||||||
import 'package:dio/dio.dart';
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/constants/variables.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/data/models/response/auth_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/auth/login_page.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
class DioClient {
|
class DioClient {
|
||||||
static final Dio _dio = Dio(BaseOptions(
|
static final Dio _dio = Dio(BaseOptions(
|
||||||
connectTimeout: const Duration(seconds: 10),
|
connectTimeout: const Duration(minutes: 1),
|
||||||
receiveTimeout: const Duration(seconds: 10),
|
receiveTimeout: const Duration(minutes: 1),
|
||||||
headers: {
|
headers: {
|
||||||
'Accept': 'application/json',
|
'Accept': 'application/json',
|
||||||
},
|
},
|
||||||
))
|
))
|
||||||
|
..interceptors.add(AuthInterceptor())
|
||||||
..interceptors.add(
|
..interceptors.add(
|
||||||
AwesomeDioInterceptor(
|
AwesomeDioInterceptor(
|
||||||
logRequestTimeout: true,
|
logRequestTimeout: true,
|
||||||
@@ -20,3 +27,167 @@ class DioClient {
|
|||||||
|
|
||||||
static Dio get instance => _dio;
|
static Dio get instance => _dio;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class AuthInterceptor extends Interceptor {
|
||||||
|
static final GlobalKey<NavigatorState> navigatorKey =
|
||||||
|
GlobalKey<NavigatorState>();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onRequest(
|
||||||
|
RequestOptions options, RequestInterceptorHandler handler) async {
|
||||||
|
// Add token to request headers
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final token = prefs.getString('auth_token');
|
||||||
|
|
||||||
|
if (token != null) {
|
||||||
|
options.headers['Authorization'] = 'Bearer $token';
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.next(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onResponse(Response response, ResponseInterceptorHandler handler) {
|
||||||
|
handler.next(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||||
|
// Check if error is 401 (Unauthorized) - token expired
|
||||||
|
if (err.response?.statusCode == 401) {
|
||||||
|
await _handleTokenExpired();
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.next(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handleTokenExpired() async {
|
||||||
|
// Clear stored token
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.remove('auth_token');
|
||||||
|
await prefs.remove('refresh_token');
|
||||||
|
await prefs.clear(); // Optional: clear all user data
|
||||||
|
|
||||||
|
// Navigate to login page
|
||||||
|
final context = navigatorKey.currentContext;
|
||||||
|
if (context != null) {
|
||||||
|
// Option 1: Navigate and remove all previous routes
|
||||||
|
context.pushReplacement(LoginPage());
|
||||||
|
|
||||||
|
// Option 2: If using GoRouter, uncomment below:
|
||||||
|
// GoRouter.of(context).go('/login');
|
||||||
|
|
||||||
|
// Option 3: If using custom routing, uncomment below:
|
||||||
|
// Navigator.of(context).pushAndRemoveUntil(
|
||||||
|
// MaterialPageRoute(builder: (context) => LoginPage()),
|
||||||
|
// (route) => false,
|
||||||
|
// );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alternative: Dengan Refresh Token Logic
|
||||||
|
class AuthInterceptorWithRefresh extends Interceptor {
|
||||||
|
static final GlobalKey<NavigatorState> navigatorKey =
|
||||||
|
GlobalKey<NavigatorState>();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onRequest(
|
||||||
|
RequestOptions options, RequestInterceptorHandler handler) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final token = prefs.getString('auth_token');
|
||||||
|
|
||||||
|
if (token != null) {
|
||||||
|
options.headers['Authorization'] = 'Bearer $token';
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.next(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||||
|
if (err.response?.statusCode == 401) {
|
||||||
|
// Try refresh token first
|
||||||
|
final success = await _tryRefreshToken();
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
// Retry the original request
|
||||||
|
final response = await _retryRequest(err.requestOptions);
|
||||||
|
handler.resolve(response);
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
// Refresh failed, redirect to login
|
||||||
|
await _handleTokenExpired();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.next(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> _tryRefreshToken() async {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/auth/refresh';
|
||||||
|
|
||||||
|
final response = await Dio().post(
|
||||||
|
url,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.refreshToken}',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final newToken = response.data['access_token'];
|
||||||
|
final newRefreshToken = response.data['refresh_token'];
|
||||||
|
|
||||||
|
await prefs.setString('auth_token', newToken);
|
||||||
|
await prefs.setString('refresh_token', newRefreshToken);
|
||||||
|
|
||||||
|
AuthResponseModel authResponseModel =
|
||||||
|
AuthResponseModel.fromMap(response.data['data']);
|
||||||
|
|
||||||
|
AuthLocalDataSource().saveAuthData(authResponseModel);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
print('Refresh token failed: $e');
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Response> _retryRequest(RequestOptions options) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final token = prefs.getString('auth_token');
|
||||||
|
|
||||||
|
options.headers['Authorization'] = 'Bearer $token';
|
||||||
|
|
||||||
|
return await DioClient.instance.request(
|
||||||
|
options.path,
|
||||||
|
options: Options(
|
||||||
|
method: options.method,
|
||||||
|
headers: options.headers,
|
||||||
|
),
|
||||||
|
data: options.data,
|
||||||
|
queryParameters: options.queryParameters,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _handleTokenExpired() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.clear();
|
||||||
|
|
||||||
|
final context = navigatorKey.currentContext;
|
||||||
|
if (context != null) {
|
||||||
|
Navigator.of(context).pushNamedAndRemoveUntil(
|
||||||
|
'/login',
|
||||||
|
(route) => false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
class DatabasePerformanceMonitor {
|
||||||
|
static final Map<String, List<int>> _queryTimes = {};
|
||||||
|
|
||||||
|
static Future<T> monitorQuery<T>(
|
||||||
|
String queryName,
|
||||||
|
Future<T> Function() query,
|
||||||
|
) async {
|
||||||
|
final stopwatch = Stopwatch()..start();
|
||||||
|
|
||||||
|
try {
|
||||||
|
final result = await query();
|
||||||
|
stopwatch.stop();
|
||||||
|
|
||||||
|
_recordQueryTime(queryName, stopwatch.elapsedMilliseconds);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
stopwatch.stop();
|
||||||
|
log('Query "$queryName" failed after ${stopwatch.elapsedMilliseconds}ms: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void _recordQueryTime(String queryName, int milliseconds) {
|
||||||
|
if (!_queryTimes.containsKey(queryName)) {
|
||||||
|
_queryTimes[queryName] = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
_queryTimes[queryName]!.add(milliseconds);
|
||||||
|
|
||||||
|
// Keep only last 100 entries
|
||||||
|
if (_queryTimes[queryName]!.length > 100) {
|
||||||
|
_queryTimes[queryName]!.removeAt(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log slow queries
|
||||||
|
if (milliseconds > 1000) {
|
||||||
|
log('Slow query detected: "$queryName" took ${milliseconds}ms');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static Map<String, dynamic> getPerformanceStats() {
|
||||||
|
final stats = <String, dynamic>{};
|
||||||
|
|
||||||
|
_queryTimes.forEach((queryName, times) {
|
||||||
|
if (times.isNotEmpty) {
|
||||||
|
final avgTime = times.reduce((a, b) => a + b) / times.length;
|
||||||
|
final maxTime = times.reduce((a, b) => a > b ? a : b);
|
||||||
|
final minTime = times.reduce((a, b) => a < b ? a : b);
|
||||||
|
|
||||||
|
stats[queryName] = {
|
||||||
|
'average_ms': avgTime.round(),
|
||||||
|
'max_ms': maxTime,
|
||||||
|
'min_ms': minTime,
|
||||||
|
'total_queries': times.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,568 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:enaklo_pos/core/utils/helper_pdf_service.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/outlet/outlet_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/inventory_analytic_response_model.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:pdf/pdf.dart';
|
||||||
|
import 'package:pdf/widgets.dart' as pw;
|
||||||
|
|
||||||
|
class InventoryReport {
|
||||||
|
static final primaryColor = PdfColor.fromHex("36175e");
|
||||||
|
|
||||||
|
static Future<File> previewPdf({
|
||||||
|
required String searchDateFormatted,
|
||||||
|
required InventoryAnalyticData? inventory,
|
||||||
|
}) async {
|
||||||
|
final pdf = pw.Document();
|
||||||
|
final ByteData dataImage = await rootBundle.load('assets/logo/logo.png');
|
||||||
|
final Uint8List bytes = dataImage.buffer.asUint8List();
|
||||||
|
final outlet = await OutletLocalDatasource().get();
|
||||||
|
|
||||||
|
final image = pw.MemoryImage(bytes);
|
||||||
|
pdf.addPage(
|
||||||
|
pw.MultiPage(
|
||||||
|
pageFormat: PdfPageFormat.a4,
|
||||||
|
margin: pw.EdgeInsets.zero,
|
||||||
|
build: (pw.Context context) {
|
||||||
|
return [
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Row(
|
||||||
|
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Bagian kiri - Logo dan Info Perusahaan
|
||||||
|
pw.Row(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
// Icon/Logo placeholder (bisa diganti dengan gambar logo)
|
||||||
|
pw.Container(
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
child: pw.Image(image),
|
||||||
|
),
|
||||||
|
pw.SizedBox(width: 15),
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
pw.Text(
|
||||||
|
'Apskel',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 28,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 4),
|
||||||
|
pw.Text(
|
||||||
|
outlet.name ?? "",
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
color: PdfColors.grey700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 2),
|
||||||
|
pw.Text(
|
||||||
|
outlet.address ?? "",
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: PdfColors.grey600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
// Bagian kanan - Info Laporan
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
pw.Text(
|
||||||
|
'Laporan Transaksi',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: PdfColors.grey800,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 8),
|
||||||
|
pw.Text(
|
||||||
|
searchDateFormatted,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: PdfColors.grey600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 4),
|
||||||
|
pw.Text(
|
||||||
|
'Laporan',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: PdfColors.grey500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
width: double.infinity,
|
||||||
|
height: 3,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('1. Ringkasan'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Row(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
pw.Expanded(
|
||||||
|
flex: 1,
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Item',
|
||||||
|
(inventory?.summary.totalProducts ?? 0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Item Masuk',
|
||||||
|
(inventory?.products.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalIn)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Item Keluar',
|
||||||
|
(inventory?.products.fold<num>(0,
|
||||||
|
(sum, item) => sum + (item.totalOut)))
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(width: 20),
|
||||||
|
pw.Expanded(
|
||||||
|
flex: 1,
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Ingredient',
|
||||||
|
(inventory?.summary.totalIngredients ?? 0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Ingredient Masuk',
|
||||||
|
(inventory?.ingredients.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalIn)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Ingredient Keluar',
|
||||||
|
(inventory?.ingredients.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalOut)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary Item
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('2. Item'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // Stock
|
||||||
|
3: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
4: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Nama'),
|
||||||
|
_buildHeaderCell('Kategori'),
|
||||||
|
_buildHeaderCell('Stock'),
|
||||||
|
_buildHeaderCell('Masuk'),
|
||||||
|
_buildHeaderCell('Keluar'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // Stock
|
||||||
|
3: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
4: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: inventory?.products
|
||||||
|
.map((item) => _buildProductDataRow(
|
||||||
|
item,
|
||||||
|
inventory.products.indexOf(item) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
))
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // Stock
|
||||||
|
3: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
4: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.products.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.quantity)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.products.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalIn)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.products.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalOut)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary Ingredient
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('3. Ingredient'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Name
|
||||||
|
1: pw.FlexColumnWidth(1), // Stock
|
||||||
|
2: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
3: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Nama'),
|
||||||
|
_buildHeaderCell('Stock'),
|
||||||
|
_buildHeaderCell('Masuk'),
|
||||||
|
_buildHeaderCell('Keluar'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Name
|
||||||
|
1: pw.FlexColumnWidth(1), // Stock
|
||||||
|
2: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
3: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: inventory?.ingredients
|
||||||
|
.map((item) => _buildIngredientsDataRow(
|
||||||
|
item,
|
||||||
|
inventory.ingredients.indexOf(item) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
))
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Name
|
||||||
|
1: pw.FlexColumnWidth(1), // Stock
|
||||||
|
2: pw.FlexColumnWidth(2), // Masuk
|
||||||
|
3: pw.FlexColumnWidth(2), // Keluar
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.ingredients.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.quantity)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.ingredients.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalIn)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildTotalCell(
|
||||||
|
(inventory?.ingredients.fold<num>(
|
||||||
|
0,
|
||||||
|
(sum, item) =>
|
||||||
|
sum + (item.totalOut)) ??
|
||||||
|
0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return HelperPdfService.saveDocument(
|
||||||
|
name:
|
||||||
|
'Apskel POS | Inventory Report | ${DateTime.now().millisecondsSinceEpoch}.pdf',
|
||||||
|
pdf: pdf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildSectionWidget(String title) {
|
||||||
|
return pw.Text(
|
||||||
|
title,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 20,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildSummaryItem(
|
||||||
|
String label,
|
||||||
|
String value, {
|
||||||
|
pw.TextStyle? valueStyle,
|
||||||
|
pw.TextStyle? labelStyle,
|
||||||
|
}) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.only(bottom: 8),
|
||||||
|
margin: pw.EdgeInsets.only(bottom: 16),
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
border: pw.Border(
|
||||||
|
bottom: pw.BorderSide(
|
||||||
|
color: PdfColors.grey300,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Row(
|
||||||
|
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
pw.Text(label, style: labelStyle),
|
||||||
|
pw.Text(
|
||||||
|
value,
|
||||||
|
style: valueStyle ??
|
||||||
|
pw.TextStyle(
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildHeaderCell(String text) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
color: PdfColors.white,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 12,
|
||||||
|
),
|
||||||
|
textAlign: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildDataCell(String text,
|
||||||
|
{pw.Alignment alignment = pw.Alignment.center, PdfColor? textColor}) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
alignment: alignment,
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: textColor ?? PdfColors.black,
|
||||||
|
fontWeight: pw.FontWeight.normal,
|
||||||
|
),
|
||||||
|
textAlign: alignment == pw.Alignment.centerLeft
|
||||||
|
? pw.TextAlign.left
|
||||||
|
: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildTotalCell(String text) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
color: PdfColors.white,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 12,
|
||||||
|
),
|
||||||
|
textAlign: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildProductDataRow(
|
||||||
|
InventoryProductItem product, bool isEven) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: product.isZeroStock
|
||||||
|
? PdfColors.red100
|
||||||
|
: product.isLowStock
|
||||||
|
? PdfColors.yellow100
|
||||||
|
: isEven
|
||||||
|
? PdfColors.grey50
|
||||||
|
: PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(product.productName, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(product.categoryName,
|
||||||
|
alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(product.quantity.toString()),
|
||||||
|
_buildDataCell(product.totalIn.toString()),
|
||||||
|
_buildDataCell(product.totalOut.toString()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildIngredientsDataRow(
|
||||||
|
InventoryIngredientItem item, bool isEven) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: item.isZeroStock
|
||||||
|
? PdfColors.red100
|
||||||
|
: item.isLowStock
|
||||||
|
? PdfColors.yellow100
|
||||||
|
: isEven
|
||||||
|
? PdfColors.grey50
|
||||||
|
: PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(item.ingredientName, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(item.quantity.toString()),
|
||||||
|
_buildDataCell(item.totalIn.toString()),
|
||||||
|
_buildDataCell(item.totalOut.toString()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
import 'dart:developer';
|
import 'dart:developer';
|
||||||
|
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart';
|
import 'package:flutter_esc_pos_network/flutter_esc_pos_network.dart';
|
||||||
import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart';
|
import 'package:print_bluetooth_thermal/print_bluetooth_thermal.dart';
|
||||||
import 'package:enaklo_pos/data/models/response/print_model.dart';
|
import 'package:enaklo_pos/data/models/response/print_model.dart';
|
||||||
|
import 'package:synchronized/synchronized.dart';
|
||||||
|
|
||||||
class PrinterService {
|
class PrinterService {
|
||||||
static final PrinterService _instance = PrinterService._internal();
|
static final PrinterService _instance = PrinterService._internal();
|
||||||
factory PrinterService() => _instance;
|
factory PrinterService() => _instance;
|
||||||
PrinterService._internal();
|
PrinterService._internal();
|
||||||
|
|
||||||
|
final Map<String, Lock> _locks = {};
|
||||||
|
String? _connectedMac;
|
||||||
|
|
||||||
/// Connect to Bluetooth printer
|
/// Connect to Bluetooth printer
|
||||||
Future<bool> connectBluetoothPrinter(String macAddress) async {
|
Future<bool> connectBluetoothPrinter(String macAddress) async {
|
||||||
try {
|
try {
|
||||||
@@ -20,22 +25,106 @@ class PrinterService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Connect to the printer
|
// Connect to the printer
|
||||||
bool connected = await PrintBluetoothThermal.connect(
|
bool connected =
|
||||||
macPrinterAddress: macAddress);
|
await PrintBluetoothThermal.connect(macPrinterAddress: macAddress);
|
||||||
|
|
||||||
if (connected) {
|
if (connected) {
|
||||||
log("Successfully connected to Bluetooth printer: $macAddress");
|
log("Successfully connected to Bluetooth printer: $macAddress");
|
||||||
} else {
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Failed to connect to Bluetooth printer',
|
||||||
|
null,
|
||||||
|
reason: 'Failed to connect to Bluetooth printe',
|
||||||
|
information: [
|
||||||
|
'function: connectBluetoothPrinter(String macAddress)',
|
||||||
|
'macAddress: $macAddress',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Failed to connect to Bluetooth printer: $macAddress");
|
log("Failed to connect to Bluetooth printer: $macAddress");
|
||||||
}
|
}
|
||||||
|
|
||||||
return connected;
|
return connected;
|
||||||
} catch (e) {
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error connecting to Bluetooth printer',
|
||||||
|
information: [
|
||||||
|
'function: connectBluetoothPrinter(String macAddress)',
|
||||||
|
'Printer: Bluetooth printer',
|
||||||
|
'macAddress: $macAddress',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Error connecting to Bluetooth printer: $e");
|
log("Error connecting to Bluetooth printer: $e");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Lock _getLock(String address) {
|
||||||
|
return _locks.putIfAbsent(address, () => Lock());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> printWithPrinter(
|
||||||
|
PrintModel printer, List<int> printData, BuildContext context) async {
|
||||||
|
if (printer.type == 'Bluetooth') {
|
||||||
|
return await _getLock(printer.address).synchronized(() async {
|
||||||
|
try {
|
||||||
|
bool isConnected = await PrintBluetoothThermal.connectionStatus;
|
||||||
|
if (!isConnected || _connectedMac != printer.address) {
|
||||||
|
if (isConnected) {
|
||||||
|
await PrintBluetoothThermal.disconnect;
|
||||||
|
await Future.delayed(const Duration(milliseconds: 1500));
|
||||||
|
}
|
||||||
|
bool connected = await PrintBluetoothThermal.connect(
|
||||||
|
macPrinterAddress: printer.address);
|
||||||
|
if (!connected) {
|
||||||
|
if (context.mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Gagal connect ke ${printer.name}')),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_connectedMac = printer.address;
|
||||||
|
await Future.delayed(
|
||||||
|
const Duration(milliseconds: 1000)); // naikkan dari 500ms
|
||||||
|
}
|
||||||
|
|
||||||
|
bool result = await _writeBytesChunked(printData);
|
||||||
|
|
||||||
|
// Beri waktu printer flush sebelum job berikutnya
|
||||||
|
await Future.delayed(const Duration(milliseconds: 1000));
|
||||||
|
|
||||||
|
log("Print result ${printer.name}: $result");
|
||||||
|
return result;
|
||||||
|
} catch (e, stackTrace) {
|
||||||
|
_connectedMac = null;
|
||||||
|
FirebaseCrashlytics.instance.recordError(e, stackTrace,
|
||||||
|
reason: 'Error printing ${printer.name}',
|
||||||
|
information: [
|
||||||
|
'Printer: ${printer.name}',
|
||||||
|
'MAC: ${printer.address}'
|
||||||
|
]);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
return await printNetwork(printer, printData, context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kirim data per chunk untuk hindari buffer overflow Bluetooth
|
||||||
|
Future<bool> _writeBytesChunked(List<int> data, {int chunkSize = 512}) async {
|
||||||
|
for (int i = 0; i < data.length; i += chunkSize) {
|
||||||
|
final end = (i + chunkSize > data.length) ? data.length : i + chunkSize;
|
||||||
|
final chunk = data.sublist(i, end);
|
||||||
|
bool result = await PrintBluetoothThermal.writeBytes(chunk);
|
||||||
|
if (!result) return false;
|
||||||
|
await Future.delayed(const Duration(milliseconds: 30));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// Print using Bluetooth printer
|
/// Print using Bluetooth printer
|
||||||
Future<bool> printBluetooth(List<int> printData) async {
|
Future<bool> printBluetooth(List<int> printData) async {
|
||||||
try {
|
try {
|
||||||
@@ -49,76 +138,96 @@ class PrinterService {
|
|||||||
if (printResult) {
|
if (printResult) {
|
||||||
log("Successfully printed via Bluetooth");
|
log("Successfully printed via Bluetooth");
|
||||||
} else {
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Failed to print via Bluetooth',
|
||||||
|
null,
|
||||||
|
reason: 'Failed to print via Bluetooth',
|
||||||
|
information: [
|
||||||
|
'function: printBluetooth(List<int> printData)',
|
||||||
|
'printData: $printData',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Failed to print via Bluetooth");
|
log("Failed to print via Bluetooth");
|
||||||
}
|
}
|
||||||
|
|
||||||
return printResult;
|
return printResult;
|
||||||
} catch (e) {
|
} catch (e, stackTrace) {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
e,
|
||||||
|
stackTrace,
|
||||||
|
reason: 'Error printing via Bluetooth',
|
||||||
|
information: [
|
||||||
|
'function: printBluetooth(List<int> printData)',
|
||||||
|
'Printer: Bluetooth printer',
|
||||||
|
'printData: $printData',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Error printing via Bluetooth: $e");
|
log("Error printing via Bluetooth: $e");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Print using Network printer
|
/// Print using Network printer
|
||||||
Future<bool> printNetwork(String ipAddress, List<int> printData) async {
|
Future<bool> printNetwork(
|
||||||
|
PrintModel printer, List<int> printData, BuildContext context) async {
|
||||||
try {
|
try {
|
||||||
final printer = PrinterNetworkManager(ipAddress);
|
final networkPrinter = PrinterNetworkManager(printer.address);
|
||||||
PosPrintResult connect = await printer.connect();
|
PosPrintResult connect = await networkPrinter.connect();
|
||||||
|
|
||||||
if (connect == PosPrintResult.success) {
|
if (connect == PosPrintResult.success) {
|
||||||
PosPrintResult printing = await printer.printTicket(printData);
|
PosPrintResult printing = await networkPrinter.printTicket(printData);
|
||||||
printer.disconnect();
|
networkPrinter.disconnect();
|
||||||
|
|
||||||
if (printing == PosPrintResult.success) {
|
if (printing == PosPrintResult.success) {
|
||||||
log("Successfully printed via Network printer: $ipAddress");
|
log("Successfully printed via Network printer: ${printer.address}");
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Failed to print via Network printer: ${printing.msg}',
|
||||||
|
null,
|
||||||
|
reason: 'Failed to print via Network printer',
|
||||||
|
information: [
|
||||||
|
'Printer: ${printer.name}',
|
||||||
|
'ipAddress: ${printer.address}',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Failed to print via Network printer: ${printing.msg}");
|
log("Failed to print via Network printer: ${printing.msg}");
|
||||||
|
if (context.mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Gagal print ke ${printer.name}')),
|
||||||
|
);
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
FirebaseCrashlytics.instance.recordError(
|
||||||
|
'Failed to connect to Network printer: ${connect.msg}',
|
||||||
|
null,
|
||||||
|
reason: 'Failed to connect Network printer',
|
||||||
|
information: [
|
||||||
|
'Printer: ${printer.name}',
|
||||||
|
'ipAddress: ${printer.address}',
|
||||||
|
],
|
||||||
|
);
|
||||||
log("Failed to connect to Network printer: ${connect.msg}");
|
log("Failed to connect to Network printer: ${connect.msg}");
|
||||||
|
if (context.mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(content: Text('Gagal connect ke ${printer.name}')),
|
||||||
|
);
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e, stackTrace) {
|
||||||
log("Error printing via Network: $e");
|
FirebaseCrashlytics.instance.recordError(
|
||||||
return false;
|
e,
|
||||||
}
|
stackTrace,
|
||||||
}
|
reason: 'Error printing via Network',
|
||||||
|
information: [
|
||||||
/// Print with automatic printer type detection
|
'Printer: ${printer.name}',
|
||||||
Future<bool> printWithPrinter(PrintModel printer, List<int> printData, BuildContext context) async {
|
'ipAddress: ${printer.address}',
|
||||||
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')),
|
|
||||||
);
|
);
|
||||||
|
log("Error printing via Network: $e");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,4 +263,4 @@ class PrinterService {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,912 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:enaklo_pos/core/extensions/string_ext.dart';
|
||||||
|
import 'package:enaklo_pos/core/utils/helper_pdf_service.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/category_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/payment_method_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/product_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/profit_loss_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:pdf/pdf.dart';
|
||||||
|
import 'package:pdf/widgets.dart' as pw;
|
||||||
|
|
||||||
|
class TransactionReport {
|
||||||
|
static final primaryColor = PdfColor.fromHex("36175e");
|
||||||
|
|
||||||
|
static Future<File> previewPdf({
|
||||||
|
required Outlet outlet,
|
||||||
|
required String searchDateFormatted,
|
||||||
|
required CategoryAnalyticData? categoryAnalyticData,
|
||||||
|
required ProfitLossData? profitLossData,
|
||||||
|
required PaymentMethodAnalyticData? paymentMethodAnalyticData,
|
||||||
|
required ProductAnalyticData? productAnalyticData,
|
||||||
|
}) async {
|
||||||
|
final pdf = pw.Document();
|
||||||
|
final ByteData dataImage = await rootBundle.load('assets/logo/logo.png');
|
||||||
|
final Uint8List bytes = dataImage.buffer.asUint8List();
|
||||||
|
|
||||||
|
final profitLossProductSummary = {
|
||||||
|
'totalRevenue': profitLossData?.productData
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.revenue)) ??
|
||||||
|
0,
|
||||||
|
'totalCost': profitLossData?.productData
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.cost)) ??
|
||||||
|
0,
|
||||||
|
'totalGrossProfit': profitLossData?.productData
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.grossProfit)) ??
|
||||||
|
0,
|
||||||
|
'totalQuantity': profitLossData?.productData
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.quantitySold)) ??
|
||||||
|
0,
|
||||||
|
};
|
||||||
|
|
||||||
|
final categorySummary = {
|
||||||
|
'totalRevenue': categoryAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.totalRevenue)) ??
|
||||||
|
0,
|
||||||
|
'orderCount': categoryAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.orderCount)) ??
|
||||||
|
0,
|
||||||
|
'productCount': categoryAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.productCount)) ??
|
||||||
|
0,
|
||||||
|
'totalQuantity': categoryAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.totalQuantity)) ??
|
||||||
|
0,
|
||||||
|
};
|
||||||
|
|
||||||
|
final productItemSummary = {
|
||||||
|
'totalRevenue': productAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.revenue)) ??
|
||||||
|
0,
|
||||||
|
'orderCount': productAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.orderCount)) ??
|
||||||
|
0,
|
||||||
|
'totalQuantitySold': productAnalyticData?.data
|
||||||
|
.fold<num>(0, (sum, item) => sum + (item.quantitySold)) ??
|
||||||
|
0,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Membuat objek Image dari gambar
|
||||||
|
final image = pw.MemoryImage(bytes);
|
||||||
|
pdf.addPage(
|
||||||
|
pw.MultiPage(
|
||||||
|
pageFormat: PdfPageFormat.a4,
|
||||||
|
margin: pw.EdgeInsets.zero,
|
||||||
|
build: (pw.Context context) {
|
||||||
|
return [
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Row(
|
||||||
|
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Bagian kiri - Logo dan Info Perusahaan
|
||||||
|
pw.Row(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
// Icon/Logo placeholder (bisa diganti dengan gambar logo)
|
||||||
|
pw.Container(
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
child: pw.Image(image),
|
||||||
|
),
|
||||||
|
pw.SizedBox(width: 15),
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
pw.Text(
|
||||||
|
'Apskel',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 28,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 4),
|
||||||
|
pw.Text(
|
||||||
|
outlet.name ?? "",
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
color: PdfColors.grey700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 2),
|
||||||
|
pw.Text(
|
||||||
|
outlet.address ?? "",
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: PdfColors.grey600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
// Bagian kanan - Info Laporan
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
pw.Text(
|
||||||
|
'Laporan Transaksi',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 24,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: PdfColors.grey800,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 8),
|
||||||
|
pw.Text(
|
||||||
|
searchDateFormatted,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: PdfColors.grey600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 4),
|
||||||
|
pw.Text(
|
||||||
|
'Laporan',
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: PdfColors.grey500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
width: double.infinity,
|
||||||
|
height: 3,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('1. Ringkasan'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Row(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
pw.Expanded(
|
||||||
|
flex: 1,
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Penjualan (termasuk rasik)',
|
||||||
|
(profitLossData?.summary.totalRevenue ?? 0)
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Total Terjual',
|
||||||
|
(profitLossData?.summary.totalOrders ?? 0)
|
||||||
|
.toString(),
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'HPP',
|
||||||
|
'${(profitLossData?.summary.totalCost ?? 0).toString().currencyFormatRpV2} | ${(((profitLossData?.summary.totalCost ?? 0) / (profitLossData?.summary.totalRevenue ?? 1)) * 100).round()}%',
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Laba Kotor',
|
||||||
|
'${(profitLossData?.summary.grossProfit ?? 0).toString().currencyFormatRpV2} | ${(profitLossData?.summary.grossProfitMargin ?? 0).round()}%',
|
||||||
|
valueStyle: pw.TextStyle(
|
||||||
|
color: PdfColors.green800,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
labelStyle: pw.TextStyle(
|
||||||
|
color: PdfColors.green800,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(width: 20),
|
||||||
|
pw.Expanded(
|
||||||
|
flex: 1,
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Biaya Lain lain',
|
||||||
|
'${(profitLossData?.summary.totalTax ?? 0).toString().currencyFormatRpV2} | ${(((profitLossData?.summary.totalTax ?? 0) / (profitLossData?.summary.totalRevenue ?? 1)) * 100).round()}%',
|
||||||
|
),
|
||||||
|
_buildSummaryItem(
|
||||||
|
'Laba/Rugi',
|
||||||
|
'${(profitLossData?.summary.netProfit ?? 0).toString().currencyFormatRpV2} | ${(profitLossData?.summary.netProfitMargin ?? 0).round()}%',
|
||||||
|
valueStyle: pw.TextStyle(
|
||||||
|
color: PdfColors.blue800,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
labelStyle: pw.TextStyle(
|
||||||
|
color: PdfColors.blue800,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 16,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 16),
|
||||||
|
pw.Text(
|
||||||
|
"Laba Rugi Perproduk",
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.SizedBox(height: 20),
|
||||||
|
pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(1), // Qty
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Pendapatan
|
||||||
|
3: pw.FlexColumnWidth(2), // HPP
|
||||||
|
4: pw.FlexColumnWidth(2), // Laba Kotor
|
||||||
|
5: pw.FlexColumnWidth(2), // Margin (%)
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Produk'),
|
||||||
|
_buildHeaderCell('Qty'),
|
||||||
|
_buildHeaderCell('Pendapatan'),
|
||||||
|
_buildHeaderCell('HPP'),
|
||||||
|
_buildHeaderCell('Laba Kotor'),
|
||||||
|
_buildHeaderCell('Margin (%)'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(1), // Qty
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Pendapatan
|
||||||
|
3: pw.FlexColumnWidth(2), // HPP
|
||||||
|
4: pw.FlexColumnWidth(2), // Laba Kotor
|
||||||
|
5: pw.FlexColumnWidth(2), // Margin (%)
|
||||||
|
},
|
||||||
|
children: profitLossData?.productData
|
||||||
|
.map(
|
||||||
|
(profitLoss) => _buildPerProductDataRow(
|
||||||
|
product: profitLoss.productName,
|
||||||
|
qty: profitLoss.quantitySold.toString(),
|
||||||
|
pendapatan: profitLoss.revenue
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
hpp: profitLoss.cost
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
labaKotor: profitLoss.grossProfit
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
margin:
|
||||||
|
'${profitLoss.grossProfitMargin.round()}%',
|
||||||
|
isEven: profitLossData.productData
|
||||||
|
.indexOf(profitLoss) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(1), // Qty
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Pendapatan
|
||||||
|
3: pw.FlexColumnWidth(2), // HPP
|
||||||
|
4: pw.FlexColumnWidth(2), // Laba Kotor
|
||||||
|
5: pw.FlexColumnWidth(2), // Margin (%)
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(
|
||||||
|
profitLossProductSummary['totalQuantity']
|
||||||
|
.toString()),
|
||||||
|
_buildTotalCell(
|
||||||
|
profitLossProductSummary['totalRevenue']
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
_buildTotalCell(
|
||||||
|
profitLossProductSummary['totalCost']
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
_buildTotalCell(
|
||||||
|
profitLossProductSummary['totalGrossProfit']
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary Payment Method
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('2. Ringkasan Metode Pembayaran'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Nama
|
||||||
|
1: pw.FlexColumnWidth(1), // Tipe
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Jumlah Order
|
||||||
|
3: pw.FlexColumnWidth(2), // Total Amount
|
||||||
|
4: pw.FlexColumnWidth(2), // Presentase
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Nama'),
|
||||||
|
_buildHeaderCell('Tipe'),
|
||||||
|
_buildHeaderCell('Jumlah Order'),
|
||||||
|
_buildHeaderCell('Total Amount'),
|
||||||
|
_buildHeaderCell('Presentase'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Nama
|
||||||
|
1: pw.FlexColumnWidth(1), // Tipe
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Jumlah Order
|
||||||
|
3: pw.FlexColumnWidth(2), // Total Amount
|
||||||
|
4: pw.FlexColumnWidth(2), // Presentase
|
||||||
|
},
|
||||||
|
children: paymentMethodAnalyticData?.data
|
||||||
|
.map(
|
||||||
|
(payment) => _buildPaymentMethodDataRow(
|
||||||
|
name: payment.paymentMethodName,
|
||||||
|
tipe: payment.paymentMethodType
|
||||||
|
.toTitleCase(),
|
||||||
|
jumlahOrder:
|
||||||
|
payment.orderCount.toString(),
|
||||||
|
totalAmount: payment.totalAmount
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
presentase:
|
||||||
|
'${payment.percentage.round()}%',
|
||||||
|
isEven: paymentMethodAnalyticData.data
|
||||||
|
.indexOf(payment) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(1), // Qty
|
||||||
|
2: pw.FlexColumnWidth(2.5), // Pendapatan
|
||||||
|
3: pw.FlexColumnWidth(2), // HPP
|
||||||
|
4: pw.FlexColumnWidth(2), // Laba Kotor
|
||||||
|
5: pw.FlexColumnWidth(2), // Margin (%)
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
_buildTotalCell((paymentMethodAnalyticData
|
||||||
|
?.summary.totalOrders ??
|
||||||
|
0)
|
||||||
|
.toString()),
|
||||||
|
_buildTotalCell((paymentMethodAnalyticData
|
||||||
|
?.summary.totalAmount ??
|
||||||
|
0)
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary Category
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('3. Ringkasan Kategori'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Nama
|
||||||
|
1: pw.FlexColumnWidth(2), // Total Product
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Jumlah Order
|
||||||
|
4: pw.FlexColumnWidth(2.5), // Presentase
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Nama'),
|
||||||
|
_buildHeaderCell('Total Produk'),
|
||||||
|
_buildHeaderCell('Qty'),
|
||||||
|
_buildHeaderCell('Jumlah Order'),
|
||||||
|
_buildHeaderCell('Pendapatan'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Nama
|
||||||
|
1: pw.FlexColumnWidth(2), // Total Product
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Jumlah Order
|
||||||
|
4: pw.FlexColumnWidth(2.5), // Presentase
|
||||||
|
},
|
||||||
|
children: categoryAnalyticData?.data
|
||||||
|
.map((category) => _buildCategoryDataRow(
|
||||||
|
name: category.categoryName,
|
||||||
|
totalProduct:
|
||||||
|
category.productCount.toString(),
|
||||||
|
qty: category.totalQuantity.toString(),
|
||||||
|
jumlahOrder:
|
||||||
|
category.orderCount.toString(),
|
||||||
|
pendapatan: category.totalRevenue
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
isEven: categoryAnalyticData.data
|
||||||
|
.indexOf(category) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
))
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Nama
|
||||||
|
1: pw.FlexColumnWidth(2), // Total Product
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Jumlah Order
|
||||||
|
4: pw.FlexColumnWidth(2.5), // Presentase
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(
|
||||||
|
categorySummary['productCount'].toString()),
|
||||||
|
_buildTotalCell(categorySummary['totalQuantity']
|
||||||
|
.toString()),
|
||||||
|
_buildTotalCell(
|
||||||
|
categorySummary['orderCount'].toString()),
|
||||||
|
_buildTotalCell(categorySummary['totalRevenue']
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
// Summary Item
|
||||||
|
pw.Container(
|
||||||
|
padding: pw.EdgeInsets.all(20),
|
||||||
|
child: pw.Column(
|
||||||
|
children: [
|
||||||
|
pw.Column(
|
||||||
|
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildSectionWidget('4. Ringkasan Item'),
|
||||||
|
pw.SizedBox(height: 30),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
topLeft: pw.Radius.circular(8),
|
||||||
|
topRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Order
|
||||||
|
4: pw.FlexColumnWidth(2), // Pendapatan
|
||||||
|
5: pw.FlexColumnWidth(2), // Average
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildHeaderCell('Produk'),
|
||||||
|
_buildHeaderCell('Kategori'),
|
||||||
|
_buildHeaderCell('Qty'),
|
||||||
|
_buildHeaderCell('Order'),
|
||||||
|
_buildHeaderCell('Pendapatan'),
|
||||||
|
_buildHeaderCell('Rata Rata'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: PdfColors.white,
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Order
|
||||||
|
4: pw.FlexColumnWidth(2), // Pendapatan
|
||||||
|
5: pw.FlexColumnWidth(2), // Average
|
||||||
|
},
|
||||||
|
children: productAnalyticData?.data
|
||||||
|
.map((item) => _buildItemDataRow(
|
||||||
|
product: item.productName,
|
||||||
|
category: item.categoryName,
|
||||||
|
qty: item.quantitySold.toString(),
|
||||||
|
order: item.orderCount.toString(),
|
||||||
|
pendapatan: item.revenue
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
average: item.averagePrice
|
||||||
|
.round()
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2,
|
||||||
|
isEven: productAnalyticData.data
|
||||||
|
.indexOf(item) %
|
||||||
|
2 ==
|
||||||
|
0,
|
||||||
|
))
|
||||||
|
.toList() ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
pw.Container(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: primaryColor, // Purple color
|
||||||
|
borderRadius: pw.BorderRadius.only(
|
||||||
|
bottomLeft: pw.Radius.circular(8),
|
||||||
|
bottomRight: pw.Radius.circular(8),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Table(
|
||||||
|
columnWidths: const {
|
||||||
|
0: pw.FlexColumnWidth(2.5), // Produk
|
||||||
|
1: pw.FlexColumnWidth(2), // Kategori
|
||||||
|
2: pw.FlexColumnWidth(1), // qty
|
||||||
|
3: pw.FlexColumnWidth(2), // Order
|
||||||
|
4: pw.FlexColumnWidth(2), // Pendapatan
|
||||||
|
5: pw.FlexColumnWidth(2), // Average
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
pw.TableRow(
|
||||||
|
children: [
|
||||||
|
_buildTotalCell('TOTAL'),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
_buildTotalCell(
|
||||||
|
productItemSummary['totalQuantitySold']
|
||||||
|
.toString()),
|
||||||
|
_buildTotalCell(productItemSummary['orderCount']
|
||||||
|
.toString()),
|
||||||
|
_buildTotalCell(
|
||||||
|
productItemSummary['totalRevenue']
|
||||||
|
.toString()
|
||||||
|
.currencyFormatRpV2),
|
||||||
|
_buildTotalCell(''),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return HelperPdfService.saveDocument(
|
||||||
|
name: 'Laporan Transaksi | $searchDateFormatted.pdf', pdf: pdf);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildSectionWidget(String title) {
|
||||||
|
return pw.Text(
|
||||||
|
title,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 20,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
color: primaryColor,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildSummaryItem(
|
||||||
|
String label,
|
||||||
|
String value, {
|
||||||
|
pw.TextStyle? valueStyle,
|
||||||
|
pw.TextStyle? labelStyle,
|
||||||
|
}) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.only(bottom: 8),
|
||||||
|
margin: pw.EdgeInsets.only(bottom: 16),
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
border: pw.Border(
|
||||||
|
bottom: pw.BorderSide(
|
||||||
|
color: PdfColors.grey300,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: pw.Row(
|
||||||
|
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
pw.Text(label, style: labelStyle),
|
||||||
|
pw.Text(
|
||||||
|
value,
|
||||||
|
style: valueStyle ??
|
||||||
|
pw.TextStyle(
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildHeaderCell(String text) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
color: PdfColors.white,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 12,
|
||||||
|
),
|
||||||
|
textAlign: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildDataCell(String text,
|
||||||
|
{pw.Alignment alignment = pw.Alignment.center, PdfColor? textColor}) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
alignment: alignment,
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
color: textColor ?? PdfColors.black,
|
||||||
|
fontWeight: pw.FontWeight.normal,
|
||||||
|
),
|
||||||
|
textAlign: alignment == pw.Alignment.centerLeft
|
||||||
|
? pw.TextAlign.left
|
||||||
|
: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.Widget _buildTotalCell(String text) {
|
||||||
|
return pw.Container(
|
||||||
|
padding: pw.EdgeInsets.symmetric(horizontal: 12, vertical: 16),
|
||||||
|
child: pw.Text(
|
||||||
|
text,
|
||||||
|
style: pw.TextStyle(
|
||||||
|
color: PdfColors.white,
|
||||||
|
fontWeight: pw.FontWeight.bold,
|
||||||
|
fontSize: 12,
|
||||||
|
),
|
||||||
|
textAlign: pw.TextAlign.center,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildPerProductDataRow({
|
||||||
|
required String product,
|
||||||
|
required String qty,
|
||||||
|
required String pendapatan,
|
||||||
|
required String hpp,
|
||||||
|
required String labaKotor,
|
||||||
|
required String margin,
|
||||||
|
required bool isEven,
|
||||||
|
}) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: isEven ? PdfColors.grey50 : PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(product, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(qty),
|
||||||
|
_buildDataCell(pendapatan),
|
||||||
|
_buildDataCell(hpp, textColor: PdfColors.red600),
|
||||||
|
_buildDataCell(labaKotor, textColor: PdfColors.green600),
|
||||||
|
_buildDataCell(margin),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildPaymentMethodDataRow({
|
||||||
|
required String name,
|
||||||
|
required String tipe,
|
||||||
|
required String jumlahOrder,
|
||||||
|
required String totalAmount,
|
||||||
|
required String presentase,
|
||||||
|
required bool isEven,
|
||||||
|
}) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: isEven ? PdfColors.grey50 : PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(name, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(tipe),
|
||||||
|
_buildDataCell(jumlahOrder),
|
||||||
|
_buildDataCell(totalAmount),
|
||||||
|
_buildDataCell(presentase),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildCategoryDataRow({
|
||||||
|
required String name,
|
||||||
|
required String totalProduct,
|
||||||
|
required String qty,
|
||||||
|
required String jumlahOrder,
|
||||||
|
required String pendapatan,
|
||||||
|
required bool isEven,
|
||||||
|
}) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: isEven ? PdfColors.grey50 : PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(name, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(totalProduct),
|
||||||
|
_buildDataCell(qty),
|
||||||
|
_buildDataCell(jumlahOrder),
|
||||||
|
_buildDataCell(pendapatan),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static pw.TableRow _buildItemDataRow({
|
||||||
|
required String product,
|
||||||
|
required String category,
|
||||||
|
required String qty,
|
||||||
|
required String order,
|
||||||
|
required String pendapatan,
|
||||||
|
required String average,
|
||||||
|
required bool isEven,
|
||||||
|
}) {
|
||||||
|
return pw.TableRow(
|
||||||
|
decoration: pw.BoxDecoration(
|
||||||
|
color: isEven ? PdfColors.grey50 : PdfColors.white,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
_buildDataCell(product, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(category, alignment: pw.Alignment.centerLeft),
|
||||||
|
_buildDataCell(qty),
|
||||||
|
_buildDataCell(order),
|
||||||
|
_buildDataCell(pendapatan),
|
||||||
|
_buildDataCell(average),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/category_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/dashboard_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/inventory_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/payment_method_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/product_analytic_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/profit_loss_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/sales_analytic_response_model.dart';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
|
||||||
|
class AnalyticRemoteDatasource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, PaymentMethodAnalyticResponseModel>> getPaymentMethod({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/payment-methods',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(PaymentMethodAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, SalesAnalyticResponseModel>> getSales({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/sales',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(SalesAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, ProductAnalyticResponseModel>> getProduct({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/products',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(ProductAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, DashboardAnalyticResponseModel>> getDashboard({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/dashboard',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(DashboardAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, ProfitLossResponseModel>> getProfitLoss({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/profit-loss',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(ProfitLossResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, CategoryAnalyticResponseModel>> getCategory({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/analytics/categories',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(CategoryAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, InventoryAnalyticResponseModel>> getInventory({
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/inventory/report/details/${authData.user?.outletId}',
|
||||||
|
queryParameters: {
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(InventoryAnalyticResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left('Terjadi Kesalahan, Coba lagi nanti.');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:developer';
|
||||||
|
import 'package:enaklo_pos/core/database/database_handler.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
|
||||||
|
class CategoryLocalDatasource {
|
||||||
|
static CategoryLocalDatasource? _instance;
|
||||||
|
|
||||||
|
CategoryLocalDatasource._internal();
|
||||||
|
|
||||||
|
static CategoryLocalDatasource get instance {
|
||||||
|
_instance ??= CategoryLocalDatasource._internal();
|
||||||
|
return _instance!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Database> get _db async => await DatabaseHelper.instance.database;
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHING SYSTEM
|
||||||
|
// ========================================
|
||||||
|
final Map<String, List<CategoryModel>> _queryCache = {};
|
||||||
|
final Duration _cacheExpiry =
|
||||||
|
Duration(minutes: 10); // Lebih lama untuk categories
|
||||||
|
final Map<String, DateTime> _cacheTimestamps = {};
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// BATCH SAVE CATEGORIES
|
||||||
|
// ========================================
|
||||||
|
Future<void> saveCategoriesBatch(List<CategoryModel> categories,
|
||||||
|
{bool clearFirst = false}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.transaction((txn) async {
|
||||||
|
if (clearFirst) {
|
||||||
|
log('🗑️ Clearing existing categories...');
|
||||||
|
await txn.delete('categories');
|
||||||
|
}
|
||||||
|
|
||||||
|
log('đź’ľ Batch saving ${categories.length} categories...');
|
||||||
|
|
||||||
|
// Batch insert categories
|
||||||
|
final batch = txn.batch();
|
||||||
|
for (final category in categories) {
|
||||||
|
batch.insert(
|
||||||
|
'categories',
|
||||||
|
_categoryToMap(category),
|
||||||
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await batch.commit(noResult: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Clear cache after update
|
||||||
|
clearCache();
|
||||||
|
log('âś… Successfully batch saved ${categories.length} categories');
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error batch saving categories: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHED QUERY
|
||||||
|
// ========================================
|
||||||
|
Future<List<CategoryModel>> getCachedCategories({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 10,
|
||||||
|
bool isActive = true,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
|
final cacheKey = _generateCacheKey(page, limit, isActive, search);
|
||||||
|
final now = DateTime.now();
|
||||||
|
|
||||||
|
// Check cache first
|
||||||
|
if (_queryCache.containsKey(cacheKey) &&
|
||||||
|
_cacheTimestamps.containsKey(cacheKey)) {
|
||||||
|
final cacheTime = _cacheTimestamps[cacheKey]!;
|
||||||
|
if (now.difference(cacheTime) < _cacheExpiry) {
|
||||||
|
log('🚀 Cache HIT: $cacheKey (${_queryCache[cacheKey]!.length} categories)');
|
||||||
|
return _queryCache[cacheKey]!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log('đź“€ Cache MISS: $cacheKey, querying database...');
|
||||||
|
|
||||||
|
// Cache miss, query database
|
||||||
|
final categories = await getCategories(
|
||||||
|
page: page,
|
||||||
|
limit: limit,
|
||||||
|
isActive: isActive,
|
||||||
|
search: search,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Store in cache
|
||||||
|
_queryCache[cacheKey] = categories;
|
||||||
|
_cacheTimestamps[cacheKey] = now;
|
||||||
|
|
||||||
|
log('đź’ľ Cached ${categories.length} categories for key: $cacheKey');
|
||||||
|
return categories;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// REGULAR GET CATEGORIES
|
||||||
|
// ========================================
|
||||||
|
Future<List<CategoryModel>> getCategories({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 10,
|
||||||
|
bool isActive = true,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String query = 'SELECT * FROM categories WHERE 1=1';
|
||||||
|
List<dynamic> whereArgs = [];
|
||||||
|
|
||||||
|
// Note: Assuming is_active will be added to database schema
|
||||||
|
if (isActive) {
|
||||||
|
query += ' AND is_active = ?';
|
||||||
|
whereArgs.add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
query += ' AND (name LIKE ? OR description LIKE ?)';
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
}
|
||||||
|
|
||||||
|
// query += ' ORDER BY name ASC';
|
||||||
|
|
||||||
|
if (limit > 0) {
|
||||||
|
query += ' LIMIT ?';
|
||||||
|
whereArgs.add(limit);
|
||||||
|
|
||||||
|
if (page > 1) {
|
||||||
|
query += ' OFFSET ?';
|
||||||
|
whereArgs.add((page - 1) * limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<Map<String, dynamic>> maps =
|
||||||
|
await db.rawQuery(query, whereArgs);
|
||||||
|
|
||||||
|
List<CategoryModel> categories = [];
|
||||||
|
for (final map in maps) {
|
||||||
|
categories.add(_mapToCategory(map));
|
||||||
|
}
|
||||||
|
|
||||||
|
log('📊 Retrieved ${categories.length} categories from database');
|
||||||
|
return categories;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting categories: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// GET ALL CATEGORIES (For dropdowns)
|
||||||
|
// ========================================
|
||||||
|
Future<List<CategoryModel>> getAllCategories() async {
|
||||||
|
const cacheKey = 'all_categories';
|
||||||
|
final now = DateTime.now();
|
||||||
|
|
||||||
|
// Check cache
|
||||||
|
if (_queryCache.containsKey(cacheKey) &&
|
||||||
|
_cacheTimestamps.containsKey(cacheKey)) {
|
||||||
|
final cacheTime = _cacheTimestamps[cacheKey]!;
|
||||||
|
if (now.difference(cacheTime) < _cacheExpiry) {
|
||||||
|
return _queryCache[cacheKey]!;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final List<Map<String, dynamic>> maps = await db.query(
|
||||||
|
'categories',
|
||||||
|
orderBy: 'name ASC',
|
||||||
|
);
|
||||||
|
|
||||||
|
final categories = maps.map((map) => _mapToCategory(map)).toList();
|
||||||
|
|
||||||
|
// Cache all categories
|
||||||
|
_queryCache[cacheKey] = categories;
|
||||||
|
_cacheTimestamps[cacheKey] = now;
|
||||||
|
|
||||||
|
log('📊 Retrieved ${categories.length} total categories');
|
||||||
|
return categories;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting all categories: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// GET CATEGORY BY ID
|
||||||
|
// ========================================
|
||||||
|
Future<CategoryModel?> getCategoryById(String id) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final List<Map<String, dynamic>> maps = await db.query(
|
||||||
|
'categories',
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (maps.isEmpty) {
|
||||||
|
log('❌ Category not found: $id');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final category = _mapToCategory(maps.first);
|
||||||
|
log('âś… Category found: ${category.name}');
|
||||||
|
return category;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting category by ID: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// GET TOTAL COUNT
|
||||||
|
// ========================================
|
||||||
|
Future<int> getTotalCount({bool isActive = true, String? search}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String query = 'SELECT COUNT(*) FROM categories WHERE 1=1';
|
||||||
|
List<dynamic> whereArgs = [];
|
||||||
|
|
||||||
|
if (isActive) {
|
||||||
|
query += ' AND is_active = ?';
|
||||||
|
whereArgs.add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
query += ' AND (name LIKE ? OR description LIKE ?)';
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
}
|
||||||
|
|
||||||
|
final result = await db.rawQuery(query, whereArgs);
|
||||||
|
final count = Sqflite.firstIntValue(result) ?? 0;
|
||||||
|
log('📊 Category total count: $count (isActive: $isActive, search: $search)');
|
||||||
|
return count;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting category total count: $e');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// HAS CATEGORIES
|
||||||
|
// ========================================
|
||||||
|
Future<bool> hasCategories() async {
|
||||||
|
final count = await getTotalCount();
|
||||||
|
final hasData = count > 0;
|
||||||
|
log('🔍 Has categories: $hasData ($count categories)');
|
||||||
|
return hasData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CLEAR ALL CATEGORIES
|
||||||
|
// ========================================
|
||||||
|
Future<void> clearAllCategories() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.delete('categories');
|
||||||
|
clearCache();
|
||||||
|
log('🗑️ All categories cleared from local DB');
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error clearing categories: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHE MANAGEMENT
|
||||||
|
// ========================================
|
||||||
|
String _generateCacheKey(int page, int limit, bool isActive, String? search) {
|
||||||
|
return 'categories_${page}_${limit}_${isActive}_${search ?? 'null'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearCache() {
|
||||||
|
final count = _queryCache.length;
|
||||||
|
_queryCache.clear();
|
||||||
|
_cacheTimestamps.clear();
|
||||||
|
log('đź§ą Category cache cleared: $count entries removed');
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearExpiredCache() {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final expiredKeys = <String>[];
|
||||||
|
|
||||||
|
_cacheTimestamps.forEach((key, timestamp) {
|
||||||
|
if (now.difference(timestamp) > _cacheExpiry) {
|
||||||
|
expiredKeys.add(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (final key in expiredKeys) {
|
||||||
|
_queryCache.remove(key);
|
||||||
|
_cacheTimestamps.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (expiredKeys.isNotEmpty) {
|
||||||
|
log('⏰ Expired category cache cleared: ${expiredKeys.length} entries');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// DATABASE STATS
|
||||||
|
// ========================================
|
||||||
|
Future<Map<String, dynamic>> getDatabaseStats() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final categoryCount = Sqflite.firstIntValue(
|
||||||
|
await db.rawQuery('SELECT COUNT(*) FROM categories')) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
final activeCount = Sqflite.firstIntValue(await db.rawQuery(
|
||||||
|
'SELECT COUNT(*) FROM categories WHERE is_active = 1')) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
final stats = {
|
||||||
|
'total_categories': categoryCount,
|
||||||
|
'active_categories': activeCount,
|
||||||
|
'cache_entries': _queryCache.length,
|
||||||
|
};
|
||||||
|
|
||||||
|
log('📊 Category Database Stats: $stats');
|
||||||
|
return stats;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting category database stats: $e');
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// HELPER METHODS
|
||||||
|
// ========================================
|
||||||
|
Map<String, dynamic> _categoryToMap(CategoryModel category) {
|
||||||
|
return {
|
||||||
|
'id': category.id,
|
||||||
|
'organization_id': category.organizationId,
|
||||||
|
'name': category.name,
|
||||||
|
'description': category.description,
|
||||||
|
'business_type': category.businessType,
|
||||||
|
'metadata': json.encode(category.metadata),
|
||||||
|
'is_active': 1, // Assuming all synced categories are active
|
||||||
|
'created_at': category.createdAt.toIso8601String(),
|
||||||
|
'updated_at': category.updatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
CategoryModel _mapToCategory(Map<String, dynamic> map) {
|
||||||
|
return CategoryModel(
|
||||||
|
id: map['id'],
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
name: map['name'],
|
||||||
|
description: map['description'],
|
||||||
|
businessType: map['business_type'],
|
||||||
|
metadata: map['metadata'] != null ? json.decode(map['metadata']) : {},
|
||||||
|
createdAt: DateTime.parse(map['created_at']),
|
||||||
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||||
|
|
||||||
|
class CategoryRemoteDatasource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, CategoryResponseModel>> getCategories({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 10,
|
||||||
|
bool isActive = true,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final headers = {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/categories',
|
||||||
|
queryParameters: {
|
||||||
|
'page': page,
|
||||||
|
'limit': limit,
|
||||||
|
'is_active': isActive,
|
||||||
|
},
|
||||||
|
options: Options(headers: headers),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return right(CategoryResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return left(response.data.toString());
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log('Dio error: ${e.message}');
|
||||||
|
return left(e.response?.data.toString() ?? e.message ?? 'Unknown error');
|
||||||
|
} catch (e) {
|
||||||
|
log('Unexpected error: $e');
|
||||||
|
return left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
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<Either<String, CategroyResponseModel>> getCategories() async {
|
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
|
||||||
final Map<String, String> 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/customer_response_model.dart';
|
||||||
|
import '../../core/constants/variables.dart';
|
||||||
|
import 'auth_local_datasource.dart';
|
||||||
|
|
||||||
|
class CustomerRemoteDataSource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, CustomerResponseModel>> getCustomers({
|
||||||
|
int page = 1,
|
||||||
|
int limit = Variables.defaultLimit,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/customers';
|
||||||
|
|
||||||
|
final response = await dio.get(
|
||||||
|
url,
|
||||||
|
queryParameters: {
|
||||||
|
'page': page,
|
||||||
|
'limit': limit,
|
||||||
|
'organization_id': authData.user?.organizationId,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(CustomerResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to get customers');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal mengambil customer');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> createCustomer({
|
||||||
|
required String name,
|
||||||
|
required String phone,
|
||||||
|
required String address,
|
||||||
|
required String email,
|
||||||
|
required bool isActive,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/customers';
|
||||||
|
|
||||||
|
Map<String, dynamic> data = {
|
||||||
|
'name': name,
|
||||||
|
'is_active': isActive,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (phone.isNotEmpty) {
|
||||||
|
data['phone'] = phone;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (address.isNotEmpty) {
|
||||||
|
data['address'] = address;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (email.isNotEmpty) {
|
||||||
|
data['email'] = email;
|
||||||
|
}
|
||||||
|
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: data,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
return const Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to create customer ');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal membuat pelanggan');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import 'package:enaklo_pos/core/assets/assets.gen.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/delivery_response_model.dart';
|
||||||
|
|
||||||
|
List<DeliveryModel> deliveries = [
|
||||||
|
DeliveryModel(
|
||||||
|
id: 'gojek',
|
||||||
|
name: 'Gojek',
|
||||||
|
imageUrl: Assets.images.gojek.path,
|
||||||
|
),
|
||||||
|
DeliveryModel(
|
||||||
|
id: 'grab',
|
||||||
|
name: 'Grab',
|
||||||
|
imageUrl: Assets.images.grab.path,
|
||||||
|
),
|
||||||
|
];
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/file_response_model.dart';
|
||||||
|
|
||||||
|
class FileRemoteDataSource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, FileResponseModel>> uploadFile({
|
||||||
|
required String filePath,
|
||||||
|
required String fileType,
|
||||||
|
required String description,
|
||||||
|
}) async {
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/files/upload';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
// Membuat FormData
|
||||||
|
final formData = FormData.fromMap({
|
||||||
|
'file': await MultipartFile.fromFile(filePath,
|
||||||
|
filename: filePath.split('/').last),
|
||||||
|
'file_type': fileType,
|
||||||
|
'description': description,
|
||||||
|
});
|
||||||
|
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: formData,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
// Content-Type otomatis diatur oleh Dio untuk FormData
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 201 || response.statusCode == 200) {
|
||||||
|
// Misal response.data['url'] adalah URL file yang diupload
|
||||||
|
return Right(FileResponseModel.fromJson(response.data));
|
||||||
|
} else {
|
||||||
|
return Left('Upload gagal: ${response.statusMessage}');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
return Left(e.response?.data['message'] ?? 'Upload gagal');
|
||||||
|
} catch (e) {
|
||||||
|
return Left('Unexpected error: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,12 +6,16 @@ import 'package:dio/dio.dart';
|
|||||||
import 'package:enaklo_pos/core/constants/variables.dart';
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||||
import 'package:enaklo_pos/core/network/dio_client.dart';
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/request/payment_request.dart';
|
||||||
import 'package:enaklo_pos/data/models/response/order_response_model.dart';
|
import 'package:enaklo_pos/data/models/response/order_response_model.dart';
|
||||||
import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart';
|
import 'package:enaklo_pos/data/models/response/payment_method_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/payment_methods_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/payment_response_model.dart';
|
||||||
import 'package:enaklo_pos/data/models/response/summary_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:enaklo_pos/presentation/home/models/order_model.dart';
|
||||||
import 'package:enaklo_pos/presentation/home/models/order_request.dart';
|
import 'package:enaklo_pos/presentation/home/models/order_request.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
|
||||||
class OrderRemoteDatasource {
|
class OrderRemoteDatasource {
|
||||||
final Dio dio = DioClient.instance;
|
final Dio dio = DioClient.instance;
|
||||||
@@ -191,7 +195,9 @@ class OrderRemoteDatasource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New Api
|
// New Api
|
||||||
Future<Either<String, bool>> createOrder(OrderRequestModel orderModel) async {
|
Future<Either<String, OrderDetailResponseModel>> createOrder(
|
||||||
|
OrderRequestModel orderModel,
|
||||||
|
) async {
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
final url = '${Variables.baseUrl}/api/v1/orders';
|
final url = '${Variables.baseUrl}/api/v1/orders';
|
||||||
|
|
||||||
@@ -209,12 +215,13 @@ class OrderRemoteDatasource {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
return const Right(true);
|
return Right(OrderDetailResponseModel.fromMap(response.data));
|
||||||
} else {
|
} else {
|
||||||
return const Left('Gagal membuat pesanan');
|
return const Left('Gagal membuat pesanan');
|
||||||
}
|
}
|
||||||
} on DioException catch (e) {
|
} on DioException catch (e) {
|
||||||
final errorMessage = e.response?.data['message'] ?? 'Kesalahan jaringan';
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
log("đź’Ą Dio error: ${e.message}");
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
log("đź’Ą Dio response: ${e.response?.data}");
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
return Left(errorMessage);
|
return Left(errorMessage);
|
||||||
@@ -224,20 +231,15 @@ class OrderRemoteDatasource {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Either<String, OrderResponseModel>> getOrder(
|
Future<Either<String, PaymentSuccessResponseModel>> createPayment(
|
||||||
{int page = 1,
|
PaymentRequestModel orderModel) async {
|
||||||
int limit = Variables.defaultLimit,
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
String status = 'completed'}) async {
|
final url = '${Variables.baseUrl}/api/v1/payments';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
final response = await dio.post(
|
||||||
final response = await dio.get(
|
url,
|
||||||
'${Variables.baseUrl}/api/v1/orders',
|
data: orderModel.toMap(),
|
||||||
queryParameters: {
|
|
||||||
'page': page,
|
|
||||||
'limit': limit,
|
|
||||||
'status': status,
|
|
||||||
'outlet_id': authData.user?.outletId,
|
|
||||||
},
|
|
||||||
options: Options(
|
options: Options(
|
||||||
headers: {
|
headers: {
|
||||||
'Authorization': 'Bearer ${authData.token}',
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
@@ -247,11 +249,59 @@ class OrderRemoteDatasource {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
log("📥 HTTP Status Code: ${response.statusCode}");
|
if (response.statusCode == 200) {
|
||||||
log("📥 Response Body: ${response.data}");
|
return Right(PaymentSuccessResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal membuat pembayaran');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, OrderResponseModel>> getOrder({
|
||||||
|
int page = 1,
|
||||||
|
int limit = Variables.defaultLimit,
|
||||||
|
String status = 'completed',
|
||||||
|
required DateTime dateFrom,
|
||||||
|
required DateTime dateTo,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
Map<String, dynamic> params = {
|
||||||
|
'page': page,
|
||||||
|
'limit': limit,
|
||||||
|
'status': status,
|
||||||
|
'date_from': DateFormat('dd-MM-yyyy').format(dateFrom),
|
||||||
|
'date_to': DateFormat('dd-MM-yyyy').format(dateTo),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
params['search'] = search;
|
||||||
|
}
|
||||||
|
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/orders',
|
||||||
|
queryParameters: params,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
if (response.statusCode == 200) {
|
||||||
log("âś… getOrderByRangeDate API call successful");
|
|
||||||
return Right(OrderResponseModel.fromMap(response.data));
|
return Right(OrderResponseModel.fromMap(response.data));
|
||||||
} else {
|
} else {
|
||||||
log("❌ getOrderByRangeDate API call failed - Status: ${response.statusCode}");
|
log("❌ getOrderByRangeDate API call failed - Status: ${response.statusCode}");
|
||||||
@@ -267,4 +317,308 @@ class OrderRemoteDatasource {
|
|||||||
return Left("Unexpected Error: $e");
|
return Left("Unexpected Error: $e");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<Either<String, OrderDetailResponseModel>> getOrderById(
|
||||||
|
{required String orderId}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final response = await dio.get(
|
||||||
|
'${Variables.baseUrl}/api/v1/orders/$orderId',
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(OrderDetailResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
log("❌ OrderDetailResponseModel API call failed - Status: ${response.statusCode}");
|
||||||
|
return const Left("Failed Load Data");
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage = 'Something went wrong';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return Left("Unexpected Error: $e");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, OrderDetailResponseModel>> createOrderWithPayment(
|
||||||
|
OrderRequestModel orderModel,
|
||||||
|
PaymentMethod payment,
|
||||||
|
) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: orderModel.toMap(),
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final data = OrderDetailResponseModel.fromMap(response.data);
|
||||||
|
final orderData = data.data;
|
||||||
|
final paymentRequest = PaymentRequestModel(
|
||||||
|
orderId: orderData?.id,
|
||||||
|
amount: orderData?.totalAmount,
|
||||||
|
paymentMethodId: payment.id,
|
||||||
|
splitDescription: '',
|
||||||
|
splitNumber: 1,
|
||||||
|
splitTotal: 1,
|
||||||
|
paymentOrderItems: orderData?.orderItems
|
||||||
|
?.map((item) => PaymentOrderItemModel(
|
||||||
|
amount: item.totalPrice,
|
||||||
|
orderItemId: item.id,
|
||||||
|
))
|
||||||
|
.toList(),
|
||||||
|
);
|
||||||
|
|
||||||
|
createPayment(paymentRequest);
|
||||||
|
return Right(data);
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal membuat pesanan');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> addToOrder({
|
||||||
|
required String orderId,
|
||||||
|
required List<OrderItemRequest> orderItems,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders/$orderId/add-items';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
"order_items": orderItems.map((item) => item.toMap()).toList(),
|
||||||
|
'notes': '',
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal menambahkan pesanan pesanan');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan, coba lagi nanti.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> refund({
|
||||||
|
required String orderId,
|
||||||
|
required String reason,
|
||||||
|
required List<OrderItem> orderItems,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders/$orderId/refund';
|
||||||
|
|
||||||
|
final int refundAmount = orderItems.fold(
|
||||||
|
0,
|
||||||
|
(sum, item) => sum + ((item.unitPrice ?? 0) * (item.quantity ?? 0)),
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
'refund_amount': refundAmount,
|
||||||
|
"order_items": orderItems
|
||||||
|
.map((item) => {
|
||||||
|
'order_item_id': item.id,
|
||||||
|
"refund_quantity": item.quantity,
|
||||||
|
"refund_amount": item.totalPrice,
|
||||||
|
"reason": ""
|
||||||
|
})
|
||||||
|
.toList(),
|
||||||
|
'reason': reason,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal refund');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> voidOrder({
|
||||||
|
required String orderId,
|
||||||
|
required String reason,
|
||||||
|
String type = "ITEM", // TYPE: ALL, ITEM
|
||||||
|
required List<OrderItem> orderItems,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders/void';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
'order_id': orderId,
|
||||||
|
'type': orderItems.isEmpty ? "ALL" : type,
|
||||||
|
'reason': reason,
|
||||||
|
"items": orderItems
|
||||||
|
.map((item) => {
|
||||||
|
'order_item_id': item.id,
|
||||||
|
"quantity": item.quantity,
|
||||||
|
})
|
||||||
|
.toList(),
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal refund');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> refundPayment({
|
||||||
|
required String orderId,
|
||||||
|
required String reason,
|
||||||
|
required int refundAmount,
|
||||||
|
}) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders/$orderId/refund';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
'refund_amount': refundAmount,
|
||||||
|
'reason': reason,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal refund');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage = 'Terjadi kesalahan coba lagi nanti';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, PaymentSuccessResponseModel>> createPaymentSplitBill(
|
||||||
|
PaymentSplitBillRequest request) async {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/orders/split-bill';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: request.toMap(),
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(PaymentSuccessResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return const Left('Gagal membuat pembayaran');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
final errorMessage =
|
||||||
|
e.response?.data['message'] ?? 'Terjadi kesalahan, coba lagi nanti.';
|
||||||
|
log("đź’Ą Dio error: ${e.message}");
|
||||||
|
log("đź’Ą Dio response: ${e.response?.data}");
|
||||||
|
return Left(errorMessage);
|
||||||
|
} catch (e) {
|
||||||
|
log("đź’Ą Unexpected error: $e");
|
||||||
|
return const Left('Terjadi kesalahan tak terduga');
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
class OutletLocalDatasource {
|
||||||
|
Future<void> save(Outlet outlet) async {
|
||||||
|
try {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString('outlet', outlet.toJson());
|
||||||
|
log('Outlet Local Data: ${outlet.toJson()}');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error saving outlet: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> remove() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.remove('outlet');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Outlet> get() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final outlet = prefs.getString('outlet');
|
||||||
|
|
||||||
|
log('Outlet Local Data: $outlet');
|
||||||
|
|
||||||
|
return Outlet.fromJson(outlet!);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/outlet/outlet_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/settings_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/setting/models/tax_model.dart';
|
||||||
|
import '../../../core/constants/variables.dart';
|
||||||
|
import '../auth_local_datasource.dart';
|
||||||
|
|
||||||
|
class OutletRemoteDataSource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, OutletResponse>> getOutlets() async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/outlets/list';
|
||||||
|
|
||||||
|
final response = await dio.get(
|
||||||
|
url,
|
||||||
|
queryParameters: {
|
||||||
|
'organization_id': authData.user?.organizationId,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final data = OutletResponse.fromMap(response.data);
|
||||||
|
return Right(data);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to get outlets');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal mengambil outlet');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, OutletDetailResponse>> currentOutlet() async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
|
||||||
|
if (authData.user?.outletId == null) {
|
||||||
|
return const Left('Kamu belum memiliki bergabung dengan outlet');
|
||||||
|
}
|
||||||
|
|
||||||
|
final url =
|
||||||
|
'${Variables.baseUrl}/api/v1/outlets/detail/${authData.user?.outletId}';
|
||||||
|
|
||||||
|
final response = await dio.get(
|
||||||
|
url,
|
||||||
|
queryParameters: {
|
||||||
|
'organization_id': authData.user?.organizationId,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
final data = OutletDetailResponse.fromMap(response.data);
|
||||||
|
await SettingsLocalDatasource().saveTax(
|
||||||
|
TaxModel(
|
||||||
|
name: 'PB1',
|
||||||
|
type: TaxType.pajak,
|
||||||
|
value: data.data?.taxRate ?? 0,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await OutletLocalDatasource().save(data.data!);
|
||||||
|
return Right(data);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to get outlets');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal mengambil outlet');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
import 'dart:developer';
|
|
||||||
import 'package:dartz/dartz.dart';
|
|
||||||
import 'package:dio/dio.dart';
|
|
||||||
import 'package:enaklo_pos/core/network/dio_client.dart';
|
|
||||||
import 'package:enaklo_pos/presentation/home/models/outlet_model.dart';
|
|
||||||
import '../../core/constants/variables.dart';
|
|
||||||
import 'auth_local_datasource.dart';
|
|
||||||
|
|
||||||
class OutletRemoteDataSource {
|
|
||||||
final Dio dio = DioClient.instance;
|
|
||||||
|
|
||||||
Future<Either<String, OutletResponse>> getOutlets() async {
|
|
||||||
try {
|
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
|
||||||
final url = '${Variables.baseUrl}/api/v1/outlets/list';
|
|
||||||
|
|
||||||
final response = await dio.get(
|
|
||||||
url,
|
|
||||||
queryParameters: {
|
|
||||||
'organization_id': authData.user?.organizationId,
|
|
||||||
},
|
|
||||||
options: Options(
|
|
||||||
headers: {
|
|
||||||
'Authorization': 'Bearer ${authData.token}',
|
|
||||||
'Accept': 'application/json',
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (response.statusCode == 200) {
|
|
||||||
return Right(OutletResponse.fromMap(response.data));
|
|
||||||
} else {
|
|
||||||
return const Left('Failed to get outlets');
|
|
||||||
}
|
|
||||||
} on DioException catch (e) {
|
|
||||||
log("Dio error: ${e.message}");
|
|
||||||
return Left(e.response?.data['message'] ?? 'Gagal mengambil outlet');
|
|
||||||
} catch (e) {
|
|
||||||
log("Unexpected error: $e");
|
|
||||||
return const Left('Unexpected error occurred');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'package:enaklo_pos/core/database/database_handler.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/print_model.dart';
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
|
||||||
|
class PrinterLocalDatasource {
|
||||||
|
static PrinterLocalDatasource? _instance;
|
||||||
|
|
||||||
|
PrinterLocalDatasource._internal();
|
||||||
|
|
||||||
|
static PrinterLocalDatasource get instance {
|
||||||
|
_instance ??= PrinterLocalDatasource._internal();
|
||||||
|
return _instance!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Database> get _db async => await DatabaseHelper.instance.database;
|
||||||
|
|
||||||
|
// Create new printer
|
||||||
|
Future<int> createPrinter(PrintModel printer) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Creating printer: ${printer.toString()}');
|
||||||
|
|
||||||
|
final id = await db.insert(
|
||||||
|
'printers',
|
||||||
|
printer.toMapForInsert(),
|
||||||
|
conflictAlgorithm:
|
||||||
|
ConflictAlgorithm.abort, // Fail if code already exists
|
||||||
|
);
|
||||||
|
|
||||||
|
log('Successfully created printer with ID: $id');
|
||||||
|
return id;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error creating printer: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update existing printer
|
||||||
|
Future<void> updatePrinter(PrintModel printer, int id) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Updating printer ID $id: ${printer.toString()}');
|
||||||
|
|
||||||
|
final updatedRows = await db.update(
|
||||||
|
'printers',
|
||||||
|
printer.toMapForUpdate(),
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (updatedRows == 0) {
|
||||||
|
throw Exception('Printer with ID $id not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
log('Successfully updated printer ID: $id');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error updating printer: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete printer by ID
|
||||||
|
Future<void> deletePrinter(int id) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Deleting printer ID: $id');
|
||||||
|
|
||||||
|
final deletedRows = await db.delete(
|
||||||
|
'printers',
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (deletedRows == 0) {
|
||||||
|
throw Exception('Printer with ID $id not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
log('Successfully deleted printer ID: $id');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error deleting printer: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get printer by code
|
||||||
|
Future<PrintModel?> getPrinterByCode(String code) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Getting printer by code: $code');
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
where: 'code = ?',
|
||||||
|
whereArgs: [code],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.isEmpty) {
|
||||||
|
log('Printer with code $code not found');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final printer = PrintModel.fromMap(result.first);
|
||||||
|
log('Found printer: ${printer.toString()}');
|
||||||
|
return printer;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting printer by code: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get printer by ID
|
||||||
|
Future<PrintModel?> getPrinterById(int id) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Getting printer by ID: $id');
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.isEmpty) {
|
||||||
|
log('Printer with ID $id not found');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final printer = PrintModel.fromMap(result.first);
|
||||||
|
log('Found printer: ${printer.toString()}');
|
||||||
|
return printer;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting printer by ID: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all printers
|
||||||
|
Future<List<PrintModel>> getAllPrinters() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Getting all printers');
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
orderBy: 'name ASC',
|
||||||
|
);
|
||||||
|
|
||||||
|
final printers = result.map((map) => PrintModel.fromMap(map)).toList();
|
||||||
|
log('Found ${printers.length} printers');
|
||||||
|
|
||||||
|
return printers;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting all printers: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get printers by type
|
||||||
|
Future<List<PrintModel>> getPrintersByType(String type) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Getting printers by type: $type');
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
where: 'type = ?',
|
||||||
|
whereArgs: [type],
|
||||||
|
orderBy: 'name ASC',
|
||||||
|
);
|
||||||
|
|
||||||
|
final printers = result.map((map) => PrintModel.fromMap(map)).toList();
|
||||||
|
log('Found ${printers.length} printers with type $type');
|
||||||
|
|
||||||
|
return printers;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting printers by type: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search printers by name
|
||||||
|
Future<List<PrintModel>> searchPrintersByName(String query) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Searching printers by name: $query');
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
where: 'name LIKE ?',
|
||||||
|
whereArgs: ['%$query%'],
|
||||||
|
orderBy: 'name ASC',
|
||||||
|
);
|
||||||
|
|
||||||
|
final printers = result.map((map) => PrintModel.fromMap(map)).toList();
|
||||||
|
log('Found ${printers.length} printers matching "$query"');
|
||||||
|
|
||||||
|
return printers;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error searching printers: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if printer code exists
|
||||||
|
Future<bool> isPrinterCodeExists(String code, {int? excludeId}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String whereClause = 'code = ?';
|
||||||
|
List<dynamic> whereArgs = [code];
|
||||||
|
|
||||||
|
if (excludeId != null) {
|
||||||
|
whereClause += ' AND id != ?';
|
||||||
|
whereArgs.add(excludeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
final result = await db.query(
|
||||||
|
'printers',
|
||||||
|
where: whereClause,
|
||||||
|
whereArgs: whereArgs,
|
||||||
|
);
|
||||||
|
|
||||||
|
final exists = result.isNotEmpty;
|
||||||
|
log('Printer code "$code" exists: $exists');
|
||||||
|
return exists;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error checking printer code existence: $e');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get printer statistics
|
||||||
|
Future<Map<String, dynamic>> getPrinterStats() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Total count
|
||||||
|
final totalResult =
|
||||||
|
await db.rawQuery('SELECT COUNT(*) as total FROM printers');
|
||||||
|
final totalCount = totalResult.first['total'] as int;
|
||||||
|
|
||||||
|
// Count by type
|
||||||
|
final typeResult = await db.rawQuery('''
|
||||||
|
SELECT type, COUNT(*) as count
|
||||||
|
FROM printers
|
||||||
|
WHERE type IS NOT NULL
|
||||||
|
GROUP BY type
|
||||||
|
''');
|
||||||
|
|
||||||
|
final typeStats = <String, int>{};
|
||||||
|
for (final row in typeResult) {
|
||||||
|
typeStats[row['type'] as String] = row['count'] as int;
|
||||||
|
}
|
||||||
|
|
||||||
|
final stats = {
|
||||||
|
'total_printers': totalCount,
|
||||||
|
'by_type': typeStats,
|
||||||
|
};
|
||||||
|
|
||||||
|
log('Printer stats: $stats');
|
||||||
|
return stats;
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting printer stats: $e');
|
||||||
|
return {
|
||||||
|
'total_printers': 0,
|
||||||
|
'by_type': <String, int>{},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear all printers (for testing/reset purposes)
|
||||||
|
Future<void> clearAllPrinters() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Clearing all printers');
|
||||||
|
await db.delete('printers');
|
||||||
|
log('All printers cleared');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error clearing printers: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batch insert printers
|
||||||
|
Future<void> insertPrinters(List<PrintModel> printers) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('Batch inserting ${printers.length} printers');
|
||||||
|
|
||||||
|
await db.transaction((txn) async {
|
||||||
|
for (final printer in printers) {
|
||||||
|
await txn.insert(
|
||||||
|
'printers',
|
||||||
|
printer.toMapForInsert(),
|
||||||
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
log('Successfully batch inserted ${printers.length} printers');
|
||||||
|
} catch (e) {
|
||||||
|
log('Error batch inserting printers: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,496 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:developer';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:enaklo_pos/core/database/database_handler.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/product_response_model.dart';
|
||||||
|
import 'package:sqflite/sqflite.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
|
||||||
|
class ProductLocalDatasource {
|
||||||
|
static ProductLocalDatasource? _instance;
|
||||||
|
|
||||||
|
ProductLocalDatasource._internal();
|
||||||
|
|
||||||
|
static ProductLocalDatasource get instance {
|
||||||
|
_instance ??= ProductLocalDatasource._internal();
|
||||||
|
return _instance!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Database> get _db async => await DatabaseHelper.instance.database;
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHING SYSTEM
|
||||||
|
// ========================================
|
||||||
|
final Map<String, List<Product>> _queryCache = {};
|
||||||
|
final Duration _cacheExpiry = Duration(minutes: 5);
|
||||||
|
final Map<String, DateTime> _cacheTimestamps = {};
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// ENHANCED BATCH SAVE
|
||||||
|
// ========================================
|
||||||
|
Future<void> saveProductsBatch(List<Product> products,
|
||||||
|
{bool clearFirst = false}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.transaction((txn) async {
|
||||||
|
if (clearFirst) {
|
||||||
|
log('🗑️ Clearing existing products...');
|
||||||
|
await txn.delete('product_variants');
|
||||||
|
await txn.delete('products');
|
||||||
|
}
|
||||||
|
|
||||||
|
log('đź’ľ Batch saving ${products.length} products...');
|
||||||
|
|
||||||
|
// âś… BATCH INSERT PRODUCTS - Much faster than individual inserts
|
||||||
|
final batch = txn.batch();
|
||||||
|
for (final product in products) {
|
||||||
|
batch.insert(
|
||||||
|
'products',
|
||||||
|
_productToMap(product),
|
||||||
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
await batch.commit(noResult: true);
|
||||||
|
|
||||||
|
// âś… BATCH INSERT VARIANTS
|
||||||
|
final variantBatch = txn.batch();
|
||||||
|
for (final product in products) {
|
||||||
|
if (product.variants?.isNotEmpty == true) {
|
||||||
|
// Delete existing variants in batch
|
||||||
|
variantBatch.delete(
|
||||||
|
'product_variants',
|
||||||
|
where: 'product_id = ?',
|
||||||
|
whereArgs: [product.id],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Insert new variants
|
||||||
|
for (final variant in product.variants!) {
|
||||||
|
variantBatch.insert(
|
||||||
|
'product_variants',
|
||||||
|
_variantToMap(variant),
|
||||||
|
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await variantBatch.commit(noResult: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Clear cache after update
|
||||||
|
clearCache();
|
||||||
|
log('âś… Successfully batch saved ${products.length} products');
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error batch saving products: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHED QUERY - HIGH PERFORMANCE
|
||||||
|
// ========================================
|
||||||
|
Future<List<Product>> getCachedProducts({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 10,
|
||||||
|
String? categoryId,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
|
final cacheKey = _generateCacheKey(page, limit, categoryId, search);
|
||||||
|
final now = DateTime.now();
|
||||||
|
|
||||||
|
// âś… CHECK CACHE FIRST
|
||||||
|
if (_queryCache.containsKey(cacheKey) &&
|
||||||
|
_cacheTimestamps.containsKey(cacheKey)) {
|
||||||
|
final cacheTime = _cacheTimestamps[cacheKey]!;
|
||||||
|
if (now.difference(cacheTime) < _cacheExpiry) {
|
||||||
|
log('🚀 Cache HIT: $cacheKey (${_queryCache[cacheKey]!.length} products)');
|
||||||
|
return _queryCache[cacheKey]!; // Return from cache - SUPER FAST
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log('đź“€ Cache MISS: $cacheKey, querying database...');
|
||||||
|
|
||||||
|
// Cache miss, query database
|
||||||
|
final products = await getProducts(
|
||||||
|
page: page,
|
||||||
|
limit: limit,
|
||||||
|
categoryId: categoryId,
|
||||||
|
search: search,
|
||||||
|
);
|
||||||
|
|
||||||
|
// âś… STORE IN CACHE for next time
|
||||||
|
_queryCache[cacheKey] = products;
|
||||||
|
_cacheTimestamps[cacheKey] = now;
|
||||||
|
|
||||||
|
log('đź’ľ Cached ${products.length} products for key: $cacheKey');
|
||||||
|
return products;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// REGULAR GET PRODUCTS (No Cache)
|
||||||
|
// ========================================
|
||||||
|
Future<List<Product>> getProducts({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 10,
|
||||||
|
String? categoryId,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String query = 'SELECT * FROM products WHERE 1=1';
|
||||||
|
List<dynamic> whereArgs = [];
|
||||||
|
|
||||||
|
if (categoryId != null && categoryId.isNotEmpty) {
|
||||||
|
query += ' AND category_id = ?';
|
||||||
|
whereArgs.add(categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
query += ' AND (name LIKE ? OR sku LIKE ? OR description LIKE ?)';
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
}
|
||||||
|
|
||||||
|
query += ' ORDER BY created_at DESC';
|
||||||
|
|
||||||
|
if (limit > 0) {
|
||||||
|
query += ' LIMIT ?';
|
||||||
|
whereArgs.add(limit);
|
||||||
|
|
||||||
|
if (page > 1) {
|
||||||
|
query += ' OFFSET ?';
|
||||||
|
whereArgs.add((page - 1) * limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final List<Map<String, dynamic>> maps =
|
||||||
|
await db.rawQuery(query, whereArgs);
|
||||||
|
|
||||||
|
List<Product> products = [];
|
||||||
|
for (final map in maps) {
|
||||||
|
final variants = await _getProductVariants(db, map['id']);
|
||||||
|
final product = _mapToProduct(map, variants);
|
||||||
|
products.add(product);
|
||||||
|
}
|
||||||
|
|
||||||
|
log('📊 Retrieved ${products.length} products from database');
|
||||||
|
return products;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting products: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// OPTIMIZED SEARCH with RANKING
|
||||||
|
// ========================================
|
||||||
|
Future<List<Product>> searchProductsOptimized(String query) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
log('🔍 Optimized search for: "$query"');
|
||||||
|
|
||||||
|
// âś… Smart query with prioritization
|
||||||
|
final List<Map<String, dynamic>> maps = await db.rawQuery('''
|
||||||
|
SELECT * FROM products
|
||||||
|
WHERE name LIKE ? OR sku LIKE ? OR description LIKE ?
|
||||||
|
ORDER BY
|
||||||
|
CASE
|
||||||
|
WHEN name LIKE ? THEN 1 -- Highest priority: name match
|
||||||
|
WHEN sku LIKE ? THEN 2 -- Second priority: SKU match
|
||||||
|
ELSE 3 -- Lowest priority: description
|
||||||
|
END,
|
||||||
|
name ASC
|
||||||
|
LIMIT 50
|
||||||
|
''', [
|
||||||
|
'%$query%', '%$query%', '%$query%',
|
||||||
|
'$query%', '$query%' // Prioritize results that start with query
|
||||||
|
]);
|
||||||
|
|
||||||
|
List<Product> products = [];
|
||||||
|
for (final map in maps) {
|
||||||
|
final variants = await _getProductVariants(db, map['id']);
|
||||||
|
products.add(_mapToProduct(map, variants));
|
||||||
|
}
|
||||||
|
|
||||||
|
log('🎯 Optimized search found ${products.length} results');
|
||||||
|
return products;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error in optimized search: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// DATABASE ANALYTICS & MONITORING
|
||||||
|
// ========================================
|
||||||
|
Future<Map<String, dynamic>> getDatabaseStats() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final productCount = Sqflite.firstIntValue(
|
||||||
|
await db.rawQuery('SELECT COUNT(*) FROM products')) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
final variantCount = Sqflite.firstIntValue(
|
||||||
|
await db.rawQuery('SELECT COUNT(*) FROM product_variants')) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
final categoryCount = Sqflite.firstIntValue(await db.rawQuery(
|
||||||
|
'SELECT COUNT(DISTINCT category_id) FROM products WHERE category_id IS NOT NULL')) ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
final dbSize = await _getDatabaseSize();
|
||||||
|
|
||||||
|
final stats = {
|
||||||
|
'total_products': productCount,
|
||||||
|
'total_variants': variantCount,
|
||||||
|
'total_categories': categoryCount,
|
||||||
|
'database_size_mb': dbSize,
|
||||||
|
'cache_entries': _queryCache.length,
|
||||||
|
'cache_size_mb': _getCacheSize(),
|
||||||
|
};
|
||||||
|
|
||||||
|
log('📊 Database Stats: $stats');
|
||||||
|
return stats;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting database stats: $e');
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<double> _getDatabaseSize() async {
|
||||||
|
try {
|
||||||
|
final dbPath = p.join(await getDatabasesPath(), 'pos_database.db');
|
||||||
|
final file = File(dbPath);
|
||||||
|
if (await file.exists()) {
|
||||||
|
final size = await file.length();
|
||||||
|
return size / (1024 * 1024); // Convert to MB
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
log('Error getting database size: $e');
|
||||||
|
}
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
double _getCacheSize() {
|
||||||
|
double totalSize = 0;
|
||||||
|
_queryCache.forEach((key, products) {
|
||||||
|
totalSize += products.length * 0.001; // Rough estimate in MB
|
||||||
|
});
|
||||||
|
return totalSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// CACHE MANAGEMENT
|
||||||
|
// ========================================
|
||||||
|
String _generateCacheKey(
|
||||||
|
int page, int limit, String? categoryId, String? search) {
|
||||||
|
return 'products_${page}_${limit}_${categoryId ?? 'null'}_${search ?? 'null'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearCache() {
|
||||||
|
final count = _queryCache.length;
|
||||||
|
_queryCache.clear();
|
||||||
|
_cacheTimestamps.clear();
|
||||||
|
log('đź§ą Cache cleared: $count entries removed');
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearExpiredCache() {
|
||||||
|
final now = DateTime.now();
|
||||||
|
final expiredKeys = <String>[];
|
||||||
|
|
||||||
|
_cacheTimestamps.forEach((key, timestamp) {
|
||||||
|
if (now.difference(timestamp) > _cacheExpiry) {
|
||||||
|
expiredKeys.add(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (final key in expiredKeys) {
|
||||||
|
_queryCache.remove(key);
|
||||||
|
_cacheTimestamps.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (expiredKeys.isNotEmpty) {
|
||||||
|
log('⏰ Expired cache cleared: ${expiredKeys.length} entries');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// OTHER METHODS (Same as basic but with enhanced logging)
|
||||||
|
// ========================================
|
||||||
|
|
||||||
|
Future<Product?> getProductById(String id) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
final List<Map<String, dynamic>> maps = await db.query(
|
||||||
|
'products',
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (maps.isEmpty) {
|
||||||
|
log('❌ Product not found: $id');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final variants = await _getProductVariants(db, id);
|
||||||
|
final product = _mapToProduct(maps.first, variants);
|
||||||
|
log('âś… Product found: ${product.name}');
|
||||||
|
return product;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting product by ID: $e');
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> getTotalCount({String? categoryId, String? search}) async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String query = 'SELECT COUNT(*) FROM products WHERE 1=1';
|
||||||
|
List<dynamic> whereArgs = [];
|
||||||
|
|
||||||
|
if (categoryId != null && categoryId.isNotEmpty) {
|
||||||
|
query += ' AND category_id = ?';
|
||||||
|
whereArgs.add(categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
query += ' AND (name LIKE ? OR sku LIKE ? OR description LIKE ?)';
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
whereArgs.add('%$search%');
|
||||||
|
}
|
||||||
|
|
||||||
|
final result = await db.rawQuery(query, whereArgs);
|
||||||
|
final count = Sqflite.firstIntValue(result) ?? 0;
|
||||||
|
log('📊 Total count: $count (categoryId: $categoryId, search: $search)');
|
||||||
|
return count;
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting total count: $e');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<bool> hasProducts() async {
|
||||||
|
final count = await getTotalCount();
|
||||||
|
final hasData = count > 0;
|
||||||
|
log('🔍 Has products: $hasData ($count products)');
|
||||||
|
return hasData;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> clearAllProducts() async {
|
||||||
|
final db = await _db;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await db.transaction((txn) async {
|
||||||
|
await txn.delete('product_variants');
|
||||||
|
await txn.delete('products');
|
||||||
|
});
|
||||||
|
clearCache();
|
||||||
|
log('🗑️ All products cleared from local DB');
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error clearing products: $e');
|
||||||
|
rethrow;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========================================
|
||||||
|
// HELPER METHODS
|
||||||
|
// ========================================
|
||||||
|
|
||||||
|
Future<List<ProductVariant>> _getProductVariants(
|
||||||
|
Database db, String productId) async {
|
||||||
|
try {
|
||||||
|
final List<Map<String, dynamic>> maps = await db.query(
|
||||||
|
'product_variants',
|
||||||
|
where: 'product_id = ?',
|
||||||
|
whereArgs: [productId],
|
||||||
|
orderBy: 'name ASC',
|
||||||
|
);
|
||||||
|
|
||||||
|
return maps.map((map) => _mapToVariant(map)).toList();
|
||||||
|
} catch (e) {
|
||||||
|
log('❌ Error getting variants for product $productId: $e');
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _productToMap(Product product) {
|
||||||
|
return {
|
||||||
|
'id': product.id,
|
||||||
|
'organization_id': product.organizationId,
|
||||||
|
'category_id': product.categoryId,
|
||||||
|
'sku': product.sku,
|
||||||
|
'name': product.name,
|
||||||
|
'description': product.description,
|
||||||
|
'price': product.price,
|
||||||
|
'cost': product.cost,
|
||||||
|
'business_type': product.businessType,
|
||||||
|
'image_url': product.imageUrl,
|
||||||
|
'printer_type': product.printerType,
|
||||||
|
'metadata':
|
||||||
|
product.metadata != null ? json.encode(product.metadata) : null,
|
||||||
|
'is_active': product.isActive == true ? 1 : 0,
|
||||||
|
'created_at': product.createdAt?.toIso8601String(),
|
||||||
|
'updated_at': product.updatedAt?.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> _variantToMap(ProductVariant variant) {
|
||||||
|
return {
|
||||||
|
'id': variant.id,
|
||||||
|
'product_id': variant.productId,
|
||||||
|
'name': variant.name,
|
||||||
|
'price_modifier': variant.priceModifier,
|
||||||
|
'cost': variant.cost,
|
||||||
|
'metadata':
|
||||||
|
variant.metadata != null ? json.encode(variant.metadata) : null,
|
||||||
|
'created_at': variant.createdAt?.toIso8601String(),
|
||||||
|
'updated_at': variant.updatedAt?.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Product _mapToProduct(
|
||||||
|
Map<String, dynamic> map, List<ProductVariant> variants) {
|
||||||
|
return Product(
|
||||||
|
id: map['id'],
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
categoryId: map['category_id'],
|
||||||
|
sku: map['sku'],
|
||||||
|
name: map['name'],
|
||||||
|
description: map['description'],
|
||||||
|
price: map['price'],
|
||||||
|
cost: map['cost'],
|
||||||
|
businessType: map['business_type'],
|
||||||
|
imageUrl: map['image_url'],
|
||||||
|
printerType: map['printer_type'],
|
||||||
|
metadata: map['metadata'] != null ? json.decode(map['metadata']) : null,
|
||||||
|
isActive: map['is_active'] == 1,
|
||||||
|
createdAt:
|
||||||
|
map['created_at'] != null ? DateTime.parse(map['created_at']) : null,
|
||||||
|
updatedAt:
|
||||||
|
map['updated_at'] != null ? DateTime.parse(map['updated_at']) : null,
|
||||||
|
variants: variants,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
ProductVariant _mapToVariant(Map<String, dynamic> map) {
|
||||||
|
return ProductVariant(
|
||||||
|
id: map['id'],
|
||||||
|
productId: map['product_id'],
|
||||||
|
name: map['name'],
|
||||||
|
priceModifier: map['price_modifier'],
|
||||||
|
cost: map['cost'],
|
||||||
|
metadata: map['metadata'] != null ? json.decode(map['metadata']) : null,
|
||||||
|
createdAt:
|
||||||
|
map['created_at'] != null ? DateTime.parse(map['created_at']) : null,
|
||||||
|
updatedAt:
|
||||||
|
map['updated_at'] != null ? DateTime.parse(map['updated_at']) : null,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,639 +0,0 @@
|
|||||||
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: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<void> _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<Database> _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<void> _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<Database> get database async {
|
|
||||||
if (_database != null) return _database!;
|
|
||||||
_database = await _initDB('dbresto36.db');
|
|
||||||
return _database!;
|
|
||||||
}
|
|
||||||
|
|
||||||
//save order
|
|
||||||
Future<int> 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<List<OrderModel>> getOrderByIsNotSync() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> maps =
|
|
||||||
await db.query(tableOrder, where: 'is_sync = ?', whereArgs: [0]);
|
|
||||||
return List.generate(maps.length, (i) {
|
|
||||||
return OrderModel.fromMap(maps[i]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<List<OrderModel>> 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<Map<String, dynamic>> 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]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<List<OrderModel>> getAllOrderByRange(
|
|
||||||
DateTime start, DateTime end) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
|
|
||||||
// Format ke ISO 8601 untuk range, hasil: yyyy-MM-ddTHH:mm:ss
|
|
||||||
final startIso = start.toIso8601String();
|
|
||||||
final endIso = end.toIso8601String();
|
|
||||||
|
|
||||||
final startDateYYYYMMDD = startIso.substring(0, 10);
|
|
||||||
final endDateYYYYMMDD = endIso.substring(0, 10);
|
|
||||||
|
|
||||||
final List<Map<String, dynamic>> maps = await db.query(
|
|
||||||
tableOrder,
|
|
||||||
where: 'substr(transaction_time, 1, 10) BETWEEN ? AND ?',
|
|
||||||
whereArgs: [startDateYYYYMMDD, endDateYYYYMMDD],
|
|
||||||
orderBy: 'transaction_time DESC',
|
|
||||||
);
|
|
||||||
log("Get All Order By Range: $startDateYYYYMMDD $endDateYYYYMMDD");
|
|
||||||
|
|
||||||
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<List<ProductQuantity>> getOrderItemByOrderId(int orderId) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> 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<void> 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<void> updateOrderIsSync(int orderId) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
await db.update(tableOrder, {'is_sync': 1},
|
|
||||||
where: 'id = ?', whereArgs: [orderId]);
|
|
||||||
}
|
|
||||||
|
|
||||||
//insert data product
|
|
||||||
|
|
||||||
Future<void> 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<void> 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.id],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
//insert list of product
|
|
||||||
Future<void> insertProducts(List<Product> 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.id} | name: ${product.name} | price: ${product.price} ');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//get all products
|
|
||||||
Future<List<Product>> getProducts() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> maps = await db.query(tableProduct);
|
|
||||||
return List.generate(maps.length, (i) {
|
|
||||||
return Product.fromLocalMap(maps[i]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Product?> 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<TableModel?> getLastTableManagement() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> 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<void> 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<void> 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<void> updateTable(TableModel table) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
await db.update(
|
|
||||||
tableManagement,
|
|
||||||
table.toMap(),
|
|
||||||
where: 'id = ?',
|
|
||||||
whereArgs: [table.id],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// get all table
|
|
||||||
Future<List<TableModel>> getAllTable() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> 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<OrderModel?> getLastOrderTable(int tableNumber) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final List<Map<String, dynamic>> 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<List<TableModel>> getTableByStatus(String status) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
List<Map<String, dynamic>> 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<void> _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<void> 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<void> 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<void> deleteAllProducts() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
await db.delete(tableProduct);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> 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<List<DraftOrderModel>> getAllDraftOrder() async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final result = await db.query('draft_orders', orderBy: 'id ASC');
|
|
||||||
|
|
||||||
List<DraftOrderModel> 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<DraftOrderModel?> 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<List<DraftOrderItem>> getDraftOrderItemByOrderId(int idOrder) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
final result =
|
|
||||||
await db.query('draft_order_items', where: 'id_draft_order = $idOrder');
|
|
||||||
|
|
||||||
List<DraftOrderItem> 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<void> 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<void> 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<void> createPrinter(PrintModel print) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
await db.insert(tablePrint, print.toMap());
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> 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<void> deletePrinter(int id) async {
|
|
||||||
final db = await instance.database;
|
|
||||||
await db.delete(tablePrint, where: 'id = ?', whereArgs: [id]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// get printer by code
|
|
||||||
Future<PrintModel?> 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,6 @@ import 'package:enaklo_pos/core/network/dio_client.dart';
|
|||||||
import 'package:enaklo_pos/data/models/request/product_request_model.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/add_product_response_model.dart';
|
||||||
import 'package:enaklo_pos/data/models/response/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 '../../core/constants/variables.dart';
|
||||||
import 'auth_local_datasource.dart';
|
import 'auth_local_datasource.dart';
|
||||||
@@ -14,13 +13,32 @@ import 'auth_local_datasource.dart';
|
|||||||
class ProductRemoteDatasource {
|
class ProductRemoteDatasource {
|
||||||
final Dio dio = DioClient.instance;
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
Future<Either<String, ProductResponseModel>> getProducts() async {
|
Future<Either<String, ProductResponseModel>> getProducts({
|
||||||
|
int page = 1,
|
||||||
|
int limit = Variables.defaultLimit,
|
||||||
|
String? categoryId,
|
||||||
|
String? search,
|
||||||
|
}) async {
|
||||||
try {
|
try {
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
final url = '${Variables.baseUrl}/api/v1/products';
|
final url = '${Variables.baseUrl}/api/v1/products';
|
||||||
|
|
||||||
|
Map<String, dynamic> queryParameters = {
|
||||||
|
'page': page,
|
||||||
|
'limit': limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (categoryId != null) {
|
||||||
|
queryParameters['category_id'] = categoryId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (search != null && search.isNotEmpty) {
|
||||||
|
queryParameters['search'] = search;
|
||||||
|
}
|
||||||
|
|
||||||
final response = await dio.get(
|
final response = await dio.get(
|
||||||
url,
|
url,
|
||||||
|
queryParameters: queryParameters,
|
||||||
options: Options(
|
options: Options(
|
||||||
headers: {
|
headers: {
|
||||||
'Authorization': 'Bearer ${authData.token}',
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
@@ -38,74 +56,71 @@ class ProductRemoteDatasource {
|
|||||||
log("Dio error: ${e.message}");
|
log("Dio error: ${e.message}");
|
||||||
return Left(e.response?.data['message'] ?? 'Gagal mengambil produk');
|
return Left(e.response?.data['message'] ?? 'Gagal mengambil produk');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("Unexpected error: $e");
|
log("Unexpected error: $e", name: "productRemoteDatasource");
|
||||||
return const Left('Unexpected error occurred');
|
return const Left('Unexpected error occurred');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Either<String, AddProductResponseModel>> addProduct(
|
Future<Either<String, AddProductResponseModel>> addProduct(
|
||||||
ProductRequestModel productRequestModel) async {
|
ProductRequestModel productRequestModel) async {
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
try {
|
||||||
final Map<String, String> headers = {
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
'Authorization': 'Bearer ${authData.token}',
|
final url = '${Variables.baseUrl}/api/v1/products';
|
||||||
};
|
|
||||||
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 response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: productRequestModel.toMap(),
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
final String body = await response.stream.bytesToString();
|
if (response.statusCode == 200) {
|
||||||
log(response.stream.toString());
|
return Right(AddProductResponseModel.fromMap(response.data));
|
||||||
log(response.statusCode.toString());
|
} else {
|
||||||
if (response.statusCode == 201) {
|
return const Left('Failed to create products');
|
||||||
return right(AddProductResponseModel.fromJson(body));
|
}
|
||||||
} else {
|
} on DioException catch (e) {
|
||||||
return left(body);
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal menambah produk');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Either<String, AddProductResponseModel>> updateProduct(
|
Future<Either<String, AddProductResponseModel>> updateProduct(
|
||||||
ProductRequestModel productRequestModel) async {
|
ProductRequestModel productRequestModel) async {
|
||||||
final authData = await AuthLocalDataSource().getAuthData();
|
try {
|
||||||
final Map<String, String> headers = {
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
'Authorization': 'Bearer ${authData.token}',
|
final url =
|
||||||
};
|
'${Variables.baseUrl}/api/v1/products/${productRequestModel.id}';
|
||||||
|
|
||||||
log("Update Product Request Data: ${productRequestModel.toMap()}");
|
final response = await dio.put(
|
||||||
log("Update Product ID: ${productRequestModel.id}");
|
url,
|
||||||
log("Update Product Name: ${productRequestModel.name}");
|
data: productRequestModel.toMap(),
|
||||||
log("Update Product Price: ${productRequestModel.price}");
|
options: Options(
|
||||||
log("Update Product Stock: ${productRequestModel.stock}");
|
headers: {
|
||||||
log("Update Product Category ID: ${productRequestModel.categoryId}");
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
log("Update Product Is Best Seller: ${productRequestModel.isBestSeller}");
|
'Accept': 'application/json',
|
||||||
log("Update Product Printer Type: ${productRequestModel.printerType}");
|
},
|
||||||
log("Update Product Has Image: ${productRequestModel.image != null}");
|
),
|
||||||
|
);
|
||||||
|
|
||||||
var request = http.MultipartRequest(
|
if (response.statusCode == 200) {
|
||||||
'POST', Uri.parse('${Variables.baseUrl}/api/products/edit'));
|
return Right(AddProductResponseModel.fromMap(response.data));
|
||||||
request.fields.addAll(productRequestModel.toMap());
|
} else {
|
||||||
if (productRequestModel.image != null) {
|
return const Left('Failed to update products');
|
||||||
request.files.add(await http.MultipartFile.fromPath(
|
}
|
||||||
'image', productRequestModel.image!.path));
|
} on DioException catch (e) {
|
||||||
}
|
log("Dio error: ${e.message}");
|
||||||
request.headers.addAll(headers);
|
return Left(e.response?.data['message'] ?? 'Gagal update produk');
|
||||||
|
} catch (e) {
|
||||||
log("Update Product Request Fields: ${request.fields}");
|
log("Unexpected error: $e");
|
||||||
log("Update Product Request Files: ${request.files.length}");
|
return const Left('Unexpected error occurred');
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class SettingsLocalDatasource {
|
|||||||
return TaxModel(
|
return TaxModel(
|
||||||
name: 'Tax',
|
name: 'Tax',
|
||||||
type: TaxType.pajak,
|
type: TaxType.pajak,
|
||||||
value: 11,
|
value: 0,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
import 'dart:ui';
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/table_model.dart';
|
||||||
|
import '../../core/constants/variables.dart';
|
||||||
|
import 'auth_local_datasource.dart';
|
||||||
|
|
||||||
|
class TableRemoteDataSource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, bool>> createTable({
|
||||||
|
required String tableName,
|
||||||
|
required int capacity,
|
||||||
|
required String location,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/tables';
|
||||||
|
|
||||||
|
final response = await dio.post(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
"outlet_id": authData.user?.outletId,
|
||||||
|
"table_name": tableName,
|
||||||
|
"capacity": capacity,
|
||||||
|
"location": location,
|
||||||
|
"status": "available",
|
||||||
|
"is_active": true,
|
||||||
|
"position_x": 200,
|
||||||
|
"position_y": 200,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to create table');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal membuat table');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, TableResponseModel>> getTable({
|
||||||
|
int page = 1,
|
||||||
|
int limit = 50,
|
||||||
|
String? status,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/tables';
|
||||||
|
|
||||||
|
Map<String, dynamic> queryParameters = {
|
||||||
|
'page': page,
|
||||||
|
'limit': limit,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (status != null) {
|
||||||
|
queryParameters['status'] = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
final response = await dio.get(
|
||||||
|
url,
|
||||||
|
queryParameters: queryParameters,
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
return Right(TableResponseModel.fromMap(response.data));
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to get tables');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal mengambil data meja');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> updatePosition({
|
||||||
|
required String tableId,
|
||||||
|
required Offset position,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/tables/$tableId';
|
||||||
|
|
||||||
|
final response = await dio.put(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
"position_x": position.dx.round(),
|
||||||
|
"position_y": position.dy.round(),
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to create table');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal membuat table');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Either<String, bool>> transferTable({
|
||||||
|
required String fromTableId,
|
||||||
|
required String toTableId,
|
||||||
|
}) async {
|
||||||
|
try {
|
||||||
|
final authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/tables/transfer';
|
||||||
|
|
||||||
|
final response = await dio.put(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
"from_table": fromTableId,
|
||||||
|
"to_table": toTableId,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to create table');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Gagal membuat table');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import 'dart:developer';
|
||||||
|
|
||||||
|
import 'package:dartz/dartz.dart';
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:enaklo_pos/core/constants/variables.dart';
|
||||||
|
import 'package:enaklo_pos/core/network/dio_client.dart';
|
||||||
|
import 'package:enaklo_pos/data/datasources/auth_local_datasource.dart';
|
||||||
|
import 'package:enaklo_pos/data/models/response/auth_response_model.dart';
|
||||||
|
|
||||||
|
class UserRemoteDatasource {
|
||||||
|
final Dio dio = DioClient.instance;
|
||||||
|
|
||||||
|
Future<Either<String, bool>> updateOutlet(String outletId) async {
|
||||||
|
AuthResponseModel authData = await AuthLocalDataSource().getAuthData();
|
||||||
|
final url = '${Variables.baseUrl}/api/v1/users/${authData.user?.id}';
|
||||||
|
|
||||||
|
try {
|
||||||
|
final response = await dio.put(
|
||||||
|
url,
|
||||||
|
data: {
|
||||||
|
'outlet_id': outletId,
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Authorization': 'Bearer ${authData.token}',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.statusCode == 200) {
|
||||||
|
authData.user?.outletId = response.data['outlet_id'];
|
||||||
|
await AuthLocalDataSource().saveAuthData(authData);
|
||||||
|
return Right(true);
|
||||||
|
} else {
|
||||||
|
return const Left('Failed to login');
|
||||||
|
}
|
||||||
|
} on DioException catch (e) {
|
||||||
|
log("Dio error: ${e.message}");
|
||||||
|
return Left(e.response?.data['message'] ?? 'Login gagal');
|
||||||
|
} catch (e) {
|
||||||
|
log("Unexpected error: $e");
|
||||||
|
return const Left('Unexpected error occurred');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
class PaymentRequestModel {
|
||||||
|
final String? orderId;
|
||||||
|
final String? paymentMethodId;
|
||||||
|
final int? amount;
|
||||||
|
final String? transactionId;
|
||||||
|
final int? splitNumber;
|
||||||
|
final int? splitTotal;
|
||||||
|
final String? splitDescription;
|
||||||
|
final List<PaymentOrderItemModel>? paymentOrderItems;
|
||||||
|
|
||||||
|
PaymentRequestModel({
|
||||||
|
this.orderId,
|
||||||
|
this.paymentMethodId,
|
||||||
|
this.amount,
|
||||||
|
this.transactionId,
|
||||||
|
this.splitNumber,
|
||||||
|
this.splitTotal,
|
||||||
|
this.splitDescription,
|
||||||
|
this.paymentOrderItems,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentRequestModel.fromJson(String str) =>
|
||||||
|
PaymentRequestModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
|
String toJson() => json.encode(toMap());
|
||||||
|
|
||||||
|
factory PaymentRequestModel.fromMap(Map<String, dynamic> json) =>
|
||||||
|
PaymentRequestModel(
|
||||||
|
orderId: json["order_id"],
|
||||||
|
paymentMethodId: json["payment_method_id"],
|
||||||
|
amount: json["amount"]?.toDouble(),
|
||||||
|
transactionId: json["transaction_id"],
|
||||||
|
splitNumber: json["split_number"],
|
||||||
|
splitTotal: json["split_total"],
|
||||||
|
splitDescription: json["split_description"],
|
||||||
|
paymentOrderItems: json["payment_order_items"] == null
|
||||||
|
? []
|
||||||
|
: List<PaymentOrderItemModel>.from(json["payment_order_items"]
|
||||||
|
.map((x) => PaymentOrderItemModel.fromMap(x))),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"order_id": orderId,
|
||||||
|
"payment_method_id": paymentMethodId,
|
||||||
|
"amount": amount,
|
||||||
|
"transaction_id": transactionId,
|
||||||
|
"split_number": splitNumber,
|
||||||
|
"split_total": splitTotal,
|
||||||
|
"split_description": splitDescription,
|
||||||
|
"payment_order_items": paymentOrderItems == null
|
||||||
|
? []
|
||||||
|
: List<dynamic>.from(paymentOrderItems!.map((x) => x.toMap())),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentOrderItemModel {
|
||||||
|
final String? orderItemId;
|
||||||
|
final int? amount;
|
||||||
|
|
||||||
|
PaymentOrderItemModel({
|
||||||
|
this.orderItemId,
|
||||||
|
this.amount,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentOrderItemModel.fromJson(String str) =>
|
||||||
|
PaymentOrderItemModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
|
factory PaymentOrderItemModel.fromMap(Map<String, dynamic> json) =>
|
||||||
|
PaymentOrderItemModel(
|
||||||
|
orderItemId: json["order_item_id"],
|
||||||
|
amount: json["amount"]?.toDouble(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"order_item_id": orderItemId,
|
||||||
|
"amount": amount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentSplitBillRequest {
|
||||||
|
final String orderId;
|
||||||
|
final String paymentMethodId;
|
||||||
|
final String customerId;
|
||||||
|
final String type; // e.g., "AMOUNT" or "ITEM"
|
||||||
|
final int amount;
|
||||||
|
final List<SplitItem> items;
|
||||||
|
|
||||||
|
PaymentSplitBillRequest({
|
||||||
|
required this.orderId,
|
||||||
|
required this.paymentMethodId,
|
||||||
|
required this.customerId,
|
||||||
|
required this.type,
|
||||||
|
required this.amount,
|
||||||
|
required this.items,
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
Map<String, dynamic> data = {
|
||||||
|
'order_id': orderId,
|
||||||
|
'payment_method_id': paymentMethodId,
|
||||||
|
'type': type,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (customerId.isNotEmpty) {
|
||||||
|
data['customer_id'] = customerId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == "AMOUNT") {
|
||||||
|
data['amount'] = amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == "ITEM") {
|
||||||
|
data['items'] = items.map((e) => e.toJson()).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SplitItem {
|
||||||
|
final String orderItemId;
|
||||||
|
final int quantity;
|
||||||
|
|
||||||
|
SplitItem({
|
||||||
|
required this.orderItemId,
|
||||||
|
required this.quantity,
|
||||||
|
});
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() {
|
||||||
|
return {
|
||||||
|
'order_item_id': orderItemId,
|
||||||
|
'quantity': quantity,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,40 +1,49 @@
|
|||||||
import 'dart:developer';
|
|
||||||
|
|
||||||
import 'package:image_picker/image_picker.dart';
|
|
||||||
|
|
||||||
class ProductRequestModel {
|
class ProductRequestModel {
|
||||||
final String? id;
|
final String? id;
|
||||||
final String name;
|
final String name;
|
||||||
|
final String? description;
|
||||||
|
final String categoryId;
|
||||||
|
final String? sku;
|
||||||
|
final String? barcode;
|
||||||
final int price;
|
final int price;
|
||||||
final int stock;
|
final int cost;
|
||||||
final int categoryId;
|
final bool isActive;
|
||||||
final int isBestSeller;
|
final bool hasVariants;
|
||||||
final XFile? image;
|
final String imageUrl;
|
||||||
final String? printerType;
|
final String? printerType;
|
||||||
|
|
||||||
ProductRequestModel({
|
ProductRequestModel({
|
||||||
this.id,
|
this.id,
|
||||||
required this.name,
|
required this.name,
|
||||||
required this.price,
|
this.description,
|
||||||
required this.stock,
|
|
||||||
required this.categoryId,
|
required this.categoryId,
|
||||||
required this.isBestSeller,
|
this.sku,
|
||||||
this.image,
|
this.barcode,
|
||||||
|
required this.price,
|
||||||
|
required this.cost,
|
||||||
|
this.isActive = true,
|
||||||
|
this.hasVariants = false,
|
||||||
|
required this.imageUrl,
|
||||||
this.printerType,
|
this.printerType,
|
||||||
});
|
});
|
||||||
|
|
||||||
Map<String, String> toMap() {
|
Map<String, dynamic> toMap() {
|
||||||
log("toMap: $isBestSeller");
|
final map = <String, dynamic>{
|
||||||
final map = {
|
|
||||||
'name': name,
|
'name': name,
|
||||||
'price': price.toString(),
|
'description': description ?? '',
|
||||||
'stock': stock.toString(),
|
'category_id': categoryId,
|
||||||
'category_id': categoryId.toString(),
|
'sku': sku ?? '',
|
||||||
'is_best_seller': isBestSeller.toString(),
|
'barcode': barcode ?? '',
|
||||||
|
'price': price,
|
||||||
|
'cost': cost,
|
||||||
|
'is_active': isActive,
|
||||||
|
'has_variants': hasVariants,
|
||||||
|
'image_url': imageUrl,
|
||||||
'printer_type': printerType ?? '',
|
'printer_type': printerType ?? '',
|
||||||
};
|
};
|
||||||
|
|
||||||
if (id != null) {
|
if (id != null) {
|
||||||
map['id'] = id.toString();
|
map['id'] = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
return map;
|
return map;
|
||||||
|
|||||||
@@ -4,12 +4,10 @@ import 'package:enaklo_pos/data/models/response/product_response_model.dart';
|
|||||||
|
|
||||||
class AddProductResponseModel {
|
class AddProductResponseModel {
|
||||||
final bool success;
|
final bool success;
|
||||||
final String message;
|
|
||||||
final Product data;
|
final Product data;
|
||||||
|
|
||||||
AddProductResponseModel({
|
AddProductResponseModel({
|
||||||
required this.success,
|
required this.success,
|
||||||
required this.message,
|
|
||||||
required this.data,
|
required this.data,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -21,13 +19,11 @@ class AddProductResponseModel {
|
|||||||
factory AddProductResponseModel.fromMap(Map<String, dynamic> json) =>
|
factory AddProductResponseModel.fromMap(Map<String, dynamic> json) =>
|
||||||
AddProductResponseModel(
|
AddProductResponseModel(
|
||||||
success: json["success"],
|
success: json["success"],
|
||||||
message: json["message"],
|
|
||||||
data: Product.fromMap(json["data"]),
|
data: Product.fromMap(json["data"]),
|
||||||
);
|
);
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() => {
|
||||||
"success": success,
|
"success": success,
|
||||||
"message": message,
|
|
||||||
"data": data.toMap(),
|
"data": data.toMap(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,9 +2,11 @@ import 'dart:convert';
|
|||||||
|
|
||||||
class AuthResponseModel {
|
class AuthResponseModel {
|
||||||
final String? token;
|
final String? token;
|
||||||
|
final String? refreshToken;
|
||||||
final User? user;
|
final User? user;
|
||||||
|
|
||||||
AuthResponseModel({
|
AuthResponseModel({
|
||||||
|
this.refreshToken,
|
||||||
this.token,
|
this.token,
|
||||||
this.user,
|
this.user,
|
||||||
});
|
});
|
||||||
@@ -17,11 +19,13 @@ class AuthResponseModel {
|
|||||||
factory AuthResponseModel.fromMap(Map<String, dynamic> json) =>
|
factory AuthResponseModel.fromMap(Map<String, dynamic> json) =>
|
||||||
AuthResponseModel(
|
AuthResponseModel(
|
||||||
token: json["token"],
|
token: json["token"],
|
||||||
|
refreshToken: json["refresh_token"],
|
||||||
user: json["user"] == null ? null : User.fromMap(json["user"]),
|
user: json["user"] == null ? null : User.fromMap(json["user"]),
|
||||||
);
|
);
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() => {
|
||||||
"token": token,
|
"token": token,
|
||||||
|
"refresh_token": refreshToken,
|
||||||
"user": user?.toMap(),
|
"user": user?.toMap(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -29,7 +33,7 @@ class AuthResponseModel {
|
|||||||
class User {
|
class User {
|
||||||
final String? id;
|
final String? id;
|
||||||
final String? organizationId;
|
final String? organizationId;
|
||||||
final String? outletId;
|
String? outletId;
|
||||||
final String? name;
|
final String? name;
|
||||||
final String? email;
|
final String? email;
|
||||||
final String? role;
|
final String? role;
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
class CategoryAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final CategoryAnalyticData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
CategoryAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dari JSON String ke Model
|
||||||
|
factory CategoryAnalyticResponseModel.fromJson(Map<String, dynamic> json) {
|
||||||
|
return CategoryAnalyticResponseModel(
|
||||||
|
success: json['success'],
|
||||||
|
data: json['data'] == null
|
||||||
|
? null
|
||||||
|
: CategoryAnalyticData.fromMap(json['data']),
|
||||||
|
errors: json['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dari Model ke JSON String
|
||||||
|
Map<String, dynamic> toJson() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dari Map ke Model
|
||||||
|
factory CategoryAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return CategoryAnalyticResponseModel(
|
||||||
|
success: map['success'],
|
||||||
|
data: CategoryAnalyticData.fromMap(map['data']),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dari Model ke Map
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CategoryAnalyticData {
|
||||||
|
final String organizationId;
|
||||||
|
final String outletId;
|
||||||
|
final DateTime dateFrom;
|
||||||
|
final DateTime dateTo;
|
||||||
|
final List<CategoryAnalyticItem> data;
|
||||||
|
|
||||||
|
CategoryAnalyticData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.outletId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CategoryAnalyticData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return CategoryAnalyticData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
dateFrom: DateTime.parse(map['date_from']),
|
||||||
|
dateTo: DateTime.parse(map['date_to']),
|
||||||
|
data: map['data'] == null
|
||||||
|
? []
|
||||||
|
: List<CategoryAnalyticItem>.from(
|
||||||
|
map['data']?.map((x) => CategoryAnalyticItem.fromMap(x)) ?? [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'date_from': dateFrom.toIso8601String(),
|
||||||
|
'date_to': dateTo.toIso8601String(),
|
||||||
|
'data': data.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CategoryAnalyticItem {
|
||||||
|
final String categoryId;
|
||||||
|
final String categoryName;
|
||||||
|
final int totalRevenue;
|
||||||
|
final int totalQuantity;
|
||||||
|
final int productCount;
|
||||||
|
final int orderCount;
|
||||||
|
|
||||||
|
CategoryAnalyticItem({
|
||||||
|
required this.categoryId,
|
||||||
|
required this.categoryName,
|
||||||
|
required this.totalRevenue,
|
||||||
|
required this.totalQuantity,
|
||||||
|
required this.productCount,
|
||||||
|
required this.orderCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CategoryAnalyticItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return CategoryAnalyticItem(
|
||||||
|
categoryId: map['category_id'],
|
||||||
|
categoryName: map['category_name'],
|
||||||
|
totalRevenue: map['total_revenue'] ?? 0,
|
||||||
|
totalQuantity: map['total_quantity'] ?? 0,
|
||||||
|
productCount: map['product_count'] ?? 0,
|
||||||
|
orderCount: map['order_count'] ?? 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'category_id': categoryId,
|
||||||
|
'category_name': categoryName,
|
||||||
|
'total_revenue': totalRevenue,
|
||||||
|
'total_quantity': totalQuantity,
|
||||||
|
'product_count': productCount,
|
||||||
|
'order_count': orderCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,91 +1,130 @@
|
|||||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
class CategroyResponseModel {
|
class CategoryResponseModel {
|
||||||
final String status;
|
final bool success;
|
||||||
final List<CategoryModel> data;
|
final CategoryData data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
CategroyResponseModel({
|
CategoryResponseModel({
|
||||||
required this.status,
|
required this.success,
|
||||||
required this.data,
|
required this.data,
|
||||||
|
this.errors,
|
||||||
});
|
});
|
||||||
|
|
||||||
Map<String, dynamic> toMap() {
|
factory CategoryResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
return <String, dynamic>{
|
return CategoryResponseModel(
|
||||||
'status': status,
|
success: map['success'] as bool,
|
||||||
'data': data.map((x) => x.toMap()).toList(),
|
data: CategoryData.fromMap(map['data'] as Map<String, dynamic>),
|
||||||
};
|
errors: map['errors'],
|
||||||
}
|
|
||||||
|
|
||||||
factory CategroyResponseModel.fromMap(Map<String, dynamic> map) {
|
|
||||||
return CategroyResponseModel(
|
|
||||||
status: map['status'] as String,
|
|
||||||
data: List<CategoryModel>.from(
|
|
||||||
(map['data']).map<CategoryModel>(
|
|
||||||
(x) => CategoryModel.fromMap(x as Map<String, dynamic>),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
factory CategroyResponseModel.fromJson(String str) =>
|
factory CategoryResponseModel.fromJson(String str) =>
|
||||||
CategroyResponseModel.fromMap(json.decode(str));
|
CategoryResponseModel.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<String, dynamic> toMap() {
|
Map<String, dynamic> toMap() {
|
||||||
return <String, dynamic>{
|
return {
|
||||||
// 'id': id,
|
'success': success,
|
||||||
'name': name,
|
'data': data.toMap(),
|
||||||
'is_sync': isSync ?? 1,
|
'errors': errors,
|
||||||
'category_id': id,
|
|
||||||
'image': image
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
factory CategoryModel.fromMap(Map<String, dynamic> 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());
|
String toJson() => json.encode(toMap());
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
class CategoryData {
|
||||||
bool operator ==(covariant CategoryModel other) {
|
final List<CategoryModel> categories;
|
||||||
if (identical(this, other)) return true;
|
final int totalCount;
|
||||||
|
final int page;
|
||||||
|
final int limit;
|
||||||
|
final int totalPages;
|
||||||
|
|
||||||
return other.id == id &&
|
CategoryData({
|
||||||
other.name == name &&
|
required this.categories,
|
||||||
other.categoryId == categoryId &&
|
required this.totalCount,
|
||||||
other.isSync == isSync &&
|
required this.page,
|
||||||
other.image == image;
|
required this.limit,
|
||||||
|
required this.totalPages,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CategoryData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return CategoryData(
|
||||||
|
categories: List<CategoryModel>.from(
|
||||||
|
(map['categories'] as List).map((x) => CategoryModel.fromMap(x)),
|
||||||
|
),
|
||||||
|
totalCount: map['total_count'] as int,
|
||||||
|
page: map['page'] as int,
|
||||||
|
limit: map['limit'] as int,
|
||||||
|
totalPages: map['total_pages'] as int,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
Map<String, dynamic> toMap() {
|
||||||
int get hashCode {
|
return {
|
||||||
return id.hashCode ^
|
'categories': categories.map((x) => x.toMap()).toList(),
|
||||||
name.hashCode ^
|
'total_count': totalCount,
|
||||||
categoryId.hashCode ^
|
'page': page,
|
||||||
isSync.hashCode ^
|
'limit': limit,
|
||||||
image.hashCode;
|
'total_pages': totalPages,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class CategoryModel {
|
||||||
|
String id;
|
||||||
|
final String organizationId;
|
||||||
|
final String name;
|
||||||
|
final String? description;
|
||||||
|
final String businessType;
|
||||||
|
final Map<String, dynamic> metadata;
|
||||||
|
final DateTime createdAt;
|
||||||
|
final DateTime updatedAt;
|
||||||
|
|
||||||
|
CategoryModel({
|
||||||
|
required this.id,
|
||||||
|
required this.organizationId,
|
||||||
|
required this.name,
|
||||||
|
this.description,
|
||||||
|
required this.businessType,
|
||||||
|
required this.metadata,
|
||||||
|
required this.createdAt,
|
||||||
|
required this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CategoryModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return CategoryModel(
|
||||||
|
id: map['id'] as String,
|
||||||
|
organizationId: map['organization_id'] as String,
|
||||||
|
name: map['name'] as String,
|
||||||
|
description: map['description'] as String?,
|
||||||
|
businessType: map['business_type'] as String,
|
||||||
|
metadata: Map<String, dynamic>.from(map['metadata'] ?? {}),
|
||||||
|
createdAt: DateTime.parse(map['created_at'] as String),
|
||||||
|
updatedAt: DateTime.parse(map['updated_at'] as String),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'name': name,
|
||||||
|
'description': description,
|
||||||
|
'business_type': businessType,
|
||||||
|
'metadata': metadata,
|
||||||
|
'created_at': createdAt.toIso8601String(),
|
||||||
|
'updated_at': updatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
factory CategoryModel.all() => CategoryModel(
|
||||||
|
id: 'all',
|
||||||
|
organizationId: '',
|
||||||
|
name: 'Semua',
|
||||||
|
businessType: 'restaurant',
|
||||||
|
metadata: {},
|
||||||
|
createdAt: DateTime.now(),
|
||||||
|
updatedAt: DateTime.now(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
class CustomerResponseModel {
|
||||||
|
final bool? success;
|
||||||
|
final CustomerData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
CustomerResponseModel({
|
||||||
|
this.success,
|
||||||
|
this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CustomerResponseModel.fromJson(String str) =>
|
||||||
|
CustomerResponseModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
|
String toJson() => json.encode(toMap());
|
||||||
|
|
||||||
|
factory CustomerResponseModel.fromMap(Map<String, dynamic> json) =>
|
||||||
|
CustomerResponseModel(
|
||||||
|
success: json["success"],
|
||||||
|
data: json["data"] == null ? null : CustomerData.fromMap(json["data"]),
|
||||||
|
errors: json["errors"],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"success": success,
|
||||||
|
"data": data?.toMap(),
|
||||||
|
"errors": errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class CustomerData {
|
||||||
|
final List<Customer>? customers;
|
||||||
|
final int? totalCount;
|
||||||
|
final int? page;
|
||||||
|
final int? limit;
|
||||||
|
final int? totalPages;
|
||||||
|
|
||||||
|
CustomerData({
|
||||||
|
this.customers,
|
||||||
|
this.totalCount,
|
||||||
|
this.page,
|
||||||
|
this.limit,
|
||||||
|
this.totalPages,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory CustomerData.fromMap(Map<String, dynamic> json) => CustomerData(
|
||||||
|
customers: json["data"] == null
|
||||||
|
? []
|
||||||
|
: List<Customer>.from(json["data"].map((x) => Customer.fromMap(x))),
|
||||||
|
totalCount: json["total_count"],
|
||||||
|
page: json["page"],
|
||||||
|
limit: json["limit"],
|
||||||
|
totalPages: json["total_pages"],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"data": customers == null
|
||||||
|
? []
|
||||||
|
: List<dynamic>.from(customers!.map((x) => x.toMap())),
|
||||||
|
"total_count": totalCount,
|
||||||
|
"page": page,
|
||||||
|
"limit": limit,
|
||||||
|
"total_pages": totalPages,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class Customer {
|
||||||
|
final String? id;
|
||||||
|
final String? organizationId;
|
||||||
|
final String? name;
|
||||||
|
final String? email;
|
||||||
|
final String? phone;
|
||||||
|
final String? address;
|
||||||
|
final bool? isDefault;
|
||||||
|
final bool? isActive;
|
||||||
|
final Map<String, dynamic>? metadata;
|
||||||
|
final DateTime? createdAt;
|
||||||
|
final DateTime? updatedAt;
|
||||||
|
|
||||||
|
Customer({
|
||||||
|
this.id,
|
||||||
|
this.organizationId,
|
||||||
|
this.name,
|
||||||
|
this.email,
|
||||||
|
this.phone,
|
||||||
|
this.address,
|
||||||
|
this.isDefault,
|
||||||
|
this.isActive,
|
||||||
|
this.metadata,
|
||||||
|
this.createdAt,
|
||||||
|
this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory Customer.fromMap(Map<String, dynamic> json) => Customer(
|
||||||
|
id: json["id"],
|
||||||
|
organizationId: json["organization_id"],
|
||||||
|
name: json["name"],
|
||||||
|
email: json["email"],
|
||||||
|
phone: json["phone"],
|
||||||
|
address: json["address"],
|
||||||
|
isDefault: json["is_default"],
|
||||||
|
isActive: json["is_active"],
|
||||||
|
metadata: json["metadata"] ?? {},
|
||||||
|
createdAt: json["created_at"] == null
|
||||||
|
? null
|
||||||
|
: DateTime.parse(json["created_at"]),
|
||||||
|
updatedAt: json["updated_at"] == null
|
||||||
|
? null
|
||||||
|
: DateTime.parse(json["updated_at"]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"id": id,
|
||||||
|
"organization_id": organizationId,
|
||||||
|
"name": name,
|
||||||
|
"email": email,
|
||||||
|
"phone": phone,
|
||||||
|
"address": address,
|
||||||
|
"is_default": isDefault,
|
||||||
|
"is_active": isActive,
|
||||||
|
"metadata": metadata,
|
||||||
|
"created_at": createdAt?.toIso8601String(),
|
||||||
|
"updated_at": updatedAt?.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
class DashboardAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final DashboardAnalyticData data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
DashboardAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Khusus untuk JSON string
|
||||||
|
factory DashboardAnalyticResponseModel.fromJson(Map<String, dynamic> json) =>
|
||||||
|
DashboardAnalyticResponseModel.fromMap(json);
|
||||||
|
|
||||||
|
/// Untuk menerima Map biasa (bukan dari JSON string)
|
||||||
|
factory DashboardAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return DashboardAnalyticResponseModel(
|
||||||
|
success: map['success'] ?? false,
|
||||||
|
data: DashboardAnalyticData.fromMap(map['data'] ?? {}),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'success': success,
|
||||||
|
'data': data.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class DashboardAnalyticData {
|
||||||
|
final String organizationId;
|
||||||
|
final String outletId;
|
||||||
|
final String dateFrom;
|
||||||
|
final String dateTo;
|
||||||
|
final DashboardOverview overview;
|
||||||
|
final List<TopProduct> topProducts;
|
||||||
|
final List<PaymentMethodAnalytic> paymentMethods;
|
||||||
|
final List<RecentSale> recentSales;
|
||||||
|
|
||||||
|
DashboardAnalyticData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.outletId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.overview,
|
||||||
|
required this.topProducts,
|
||||||
|
required this.paymentMethods,
|
||||||
|
required this.recentSales,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory DashboardAnalyticData.fromMap(Map<String, dynamic> map) =>
|
||||||
|
DashboardAnalyticData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
dateFrom: map['date_from'],
|
||||||
|
dateTo: map['date_to'],
|
||||||
|
overview: DashboardOverview.fromMap(map['overview']),
|
||||||
|
topProducts: map['top_products'] == null
|
||||||
|
? []
|
||||||
|
: List<TopProduct>.from(
|
||||||
|
map['top_products']?.map((x) => TopProduct.fromMap(x))),
|
||||||
|
paymentMethods: map['payment_methods'] == null
|
||||||
|
? []
|
||||||
|
: List<PaymentMethodAnalytic>.from(map['payment_methods']
|
||||||
|
?.map((x) => PaymentMethodAnalytic.fromMap(x))),
|
||||||
|
recentSales: map['recent_sales'] == null
|
||||||
|
? []
|
||||||
|
: List<RecentSale>.from(
|
||||||
|
map['recent_sales']?.map((x) => RecentSale.fromMap(x))),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'date_from': dateFrom,
|
||||||
|
'date_to': dateTo,
|
||||||
|
'overview': overview.toMap(),
|
||||||
|
'top_products': topProducts.map((x) => x.toMap()).toList(),
|
||||||
|
'payment_methods': paymentMethods.map((x) => x.toMap()).toList(),
|
||||||
|
'recent_sales': recentSales.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class DashboardOverview {
|
||||||
|
final int totalSales;
|
||||||
|
final int totalOrders;
|
||||||
|
final double averageOrderValue;
|
||||||
|
final int totalCustomers;
|
||||||
|
final int voidedOrders;
|
||||||
|
final int refundedOrders;
|
||||||
|
|
||||||
|
DashboardOverview({
|
||||||
|
required this.totalSales,
|
||||||
|
required this.totalOrders,
|
||||||
|
required this.averageOrderValue,
|
||||||
|
required this.totalCustomers,
|
||||||
|
required this.voidedOrders,
|
||||||
|
required this.refundedOrders,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory DashboardOverview.fromMap(Map<String, dynamic> map) =>
|
||||||
|
DashboardOverview(
|
||||||
|
totalSales: map['total_sales'],
|
||||||
|
totalOrders: map['total_orders'],
|
||||||
|
averageOrderValue: map['average_order_value']?.toDouble() ?? 0.0,
|
||||||
|
totalCustomers: map['total_customers'],
|
||||||
|
voidedOrders: map['voided_orders'],
|
||||||
|
refundedOrders: map['refunded_orders'],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'total_sales': totalSales,
|
||||||
|
'total_orders': totalOrders,
|
||||||
|
'average_order_value': averageOrderValue,
|
||||||
|
'total_customers': totalCustomers,
|
||||||
|
'voided_orders': voidedOrders,
|
||||||
|
'refunded_orders': refundedOrders,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class TopProduct {
|
||||||
|
final String productId;
|
||||||
|
final String productName;
|
||||||
|
final String categoryId;
|
||||||
|
final String categoryName;
|
||||||
|
final int quantitySold;
|
||||||
|
final int revenue;
|
||||||
|
final double averagePrice;
|
||||||
|
final int orderCount;
|
||||||
|
|
||||||
|
TopProduct({
|
||||||
|
required this.productId,
|
||||||
|
required this.productName,
|
||||||
|
required this.categoryId,
|
||||||
|
required this.categoryName,
|
||||||
|
required this.quantitySold,
|
||||||
|
required this.revenue,
|
||||||
|
required this.averagePrice,
|
||||||
|
required this.orderCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory TopProduct.fromMap(Map<String, dynamic> map) => TopProduct(
|
||||||
|
productId: map['product_id'],
|
||||||
|
productName: map['product_name'],
|
||||||
|
categoryId: map['category_id'],
|
||||||
|
categoryName: map['category_name'],
|
||||||
|
quantitySold: map['quantity_sold'],
|
||||||
|
revenue: map['revenue'],
|
||||||
|
averagePrice: map['average_price']?.toDouble() ?? 0.0,
|
||||||
|
orderCount: map['order_count'],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'product_id': productId,
|
||||||
|
'product_name': productName,
|
||||||
|
'category_id': categoryId,
|
||||||
|
'category_name': categoryName,
|
||||||
|
'quantity_sold': quantitySold,
|
||||||
|
'revenue': revenue,
|
||||||
|
'average_price': averagePrice,
|
||||||
|
'order_count': orderCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentMethodAnalytic {
|
||||||
|
final String paymentMethodId;
|
||||||
|
final String paymentMethodName;
|
||||||
|
final String paymentMethodType;
|
||||||
|
final int totalAmount;
|
||||||
|
final int orderCount;
|
||||||
|
final int paymentCount;
|
||||||
|
final double percentage;
|
||||||
|
|
||||||
|
PaymentMethodAnalytic({
|
||||||
|
required this.paymentMethodId,
|
||||||
|
required this.paymentMethodName,
|
||||||
|
required this.paymentMethodType,
|
||||||
|
required this.totalAmount,
|
||||||
|
required this.orderCount,
|
||||||
|
required this.paymentCount,
|
||||||
|
required this.percentage,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentMethodAnalytic.fromMap(Map<String, dynamic> map) =>
|
||||||
|
PaymentMethodAnalytic(
|
||||||
|
paymentMethodId: map['payment_method_id'],
|
||||||
|
paymentMethodName: map['payment_method_name'],
|
||||||
|
paymentMethodType: map['payment_method_type'],
|
||||||
|
totalAmount: map['total_amount'],
|
||||||
|
orderCount: map['order_count'],
|
||||||
|
paymentCount: map['payment_count'],
|
||||||
|
percentage: map['percentage']?.toDouble() ?? 0.0,
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'payment_method_id': paymentMethodId,
|
||||||
|
'payment_method_name': paymentMethodName,
|
||||||
|
'payment_method_type': paymentMethodType,
|
||||||
|
'total_amount': totalAmount,
|
||||||
|
'order_count': orderCount,
|
||||||
|
'payment_count': paymentCount,
|
||||||
|
'percentage': percentage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class RecentSale {
|
||||||
|
final String date;
|
||||||
|
final int sales;
|
||||||
|
final int orders;
|
||||||
|
final int items;
|
||||||
|
final int tax;
|
||||||
|
final int discount;
|
||||||
|
final int netSales;
|
||||||
|
|
||||||
|
RecentSale({
|
||||||
|
required this.date,
|
||||||
|
required this.sales,
|
||||||
|
required this.orders,
|
||||||
|
required this.items,
|
||||||
|
required this.tax,
|
||||||
|
required this.discount,
|
||||||
|
required this.netSales,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory RecentSale.fromMap(Map<String, dynamic> map) => RecentSale(
|
||||||
|
date: map['date'],
|
||||||
|
sales: map['sales'],
|
||||||
|
orders: map['orders'],
|
||||||
|
items: map['items'],
|
||||||
|
tax: map['tax'],
|
||||||
|
discount: map['discount'],
|
||||||
|
netSales: map['net_sales'],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'date': date,
|
||||||
|
'sales': sales,
|
||||||
|
'orders': orders,
|
||||||
|
'items': items,
|
||||||
|
'tax': tax,
|
||||||
|
'discount': discount,
|
||||||
|
'net_sales': netSales,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
class DeliveryModel {
|
||||||
|
String id;
|
||||||
|
String name;
|
||||||
|
String imageUrl;
|
||||||
|
|
||||||
|
DeliveryModel({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
required this.imageUrl,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
class FileResponseModel {
|
||||||
|
final FileModel data;
|
||||||
|
final String message;
|
||||||
|
final bool success;
|
||||||
|
|
||||||
|
FileResponseModel({
|
||||||
|
required this.data,
|
||||||
|
required this.message,
|
||||||
|
required this.success,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory FileResponseModel.fromJson(Map<String, dynamic> json) {
|
||||||
|
return FileResponseModel(
|
||||||
|
data: FileModel.fromJson(json['data']),
|
||||||
|
message: json['message'] as String,
|
||||||
|
success: json['success'] as bool,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'data': data.toJson(),
|
||||||
|
'message': message,
|
||||||
|
'success': success,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory FileResponseModel.fromMap(Map<String, dynamic> map) =>
|
||||||
|
FileResponseModel.fromJson(map);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => toJson();
|
||||||
|
|
||||||
|
FileResponseModel copyWith({
|
||||||
|
FileModel? data,
|
||||||
|
String? message,
|
||||||
|
bool? success,
|
||||||
|
}) {
|
||||||
|
return FileResponseModel(
|
||||||
|
data: data ?? this.data,
|
||||||
|
message: message ?? this.message,
|
||||||
|
success: success ?? this.success,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() =>
|
||||||
|
'FileResponseModel(data: $data, message: $message, success: $success)';
|
||||||
|
}
|
||||||
|
|
||||||
|
class FileModel {
|
||||||
|
final String id;
|
||||||
|
final String organizationId;
|
||||||
|
final String userId;
|
||||||
|
final String fileName;
|
||||||
|
final String originalName;
|
||||||
|
final String fileUrl;
|
||||||
|
final int fileSize;
|
||||||
|
final String mimeType;
|
||||||
|
final String fileType;
|
||||||
|
final String uploadPath;
|
||||||
|
final bool isPublic;
|
||||||
|
final DateTime createdAt;
|
||||||
|
final DateTime updatedAt;
|
||||||
|
|
||||||
|
FileModel({
|
||||||
|
required this.id,
|
||||||
|
required this.organizationId,
|
||||||
|
required this.userId,
|
||||||
|
required this.fileName,
|
||||||
|
required this.originalName,
|
||||||
|
required this.fileUrl,
|
||||||
|
required this.fileSize,
|
||||||
|
required this.mimeType,
|
||||||
|
required this.fileType,
|
||||||
|
required this.uploadPath,
|
||||||
|
required this.isPublic,
|
||||||
|
required this.createdAt,
|
||||||
|
required this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory FileModel.fromJson(Map<String, dynamic> json) {
|
||||||
|
return FileModel(
|
||||||
|
id: json['id'] as String,
|
||||||
|
organizationId: json['organization_id'] as String,
|
||||||
|
userId: json['user_id'] as String,
|
||||||
|
fileName: json['file_name'] as String,
|
||||||
|
originalName: json['original_name'] as String,
|
||||||
|
fileUrl: json['file_url'] as String,
|
||||||
|
fileSize: json['file_size'] as int,
|
||||||
|
mimeType: json['mime_type'] as String,
|
||||||
|
fileType: json['file_type'] as String,
|
||||||
|
uploadPath: json['upload_path'] as String,
|
||||||
|
isPublic: json['is_public'] as bool,
|
||||||
|
createdAt: DateTime.parse(json['created_at'] as String),
|
||||||
|
updatedAt: DateTime.parse(json['updated_at'] as String),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'user_id': userId,
|
||||||
|
'file_name': fileName,
|
||||||
|
'original_name': originalName,
|
||||||
|
'file_url': fileUrl,
|
||||||
|
'file_size': fileSize,
|
||||||
|
'mime_type': mimeType,
|
||||||
|
'file_type': fileType,
|
||||||
|
'upload_path': uploadPath,
|
||||||
|
'is_public': isPublic,
|
||||||
|
'created_at': createdAt.toIso8601String(),
|
||||||
|
'updated_at': updatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
|
||||||
|
factory FileModel.fromMap(Map<String, dynamic> map) =>
|
||||||
|
FileModel.fromJson(map);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => toJson();
|
||||||
|
|
||||||
|
FileModel copyWith({
|
||||||
|
String? id,
|
||||||
|
String? organizationId,
|
||||||
|
String? userId,
|
||||||
|
String? fileName,
|
||||||
|
String? originalName,
|
||||||
|
String? fileUrl,
|
||||||
|
int? fileSize,
|
||||||
|
String? mimeType,
|
||||||
|
String? fileType,
|
||||||
|
String? uploadPath,
|
||||||
|
bool? isPublic,
|
||||||
|
DateTime? createdAt,
|
||||||
|
DateTime? updatedAt,
|
||||||
|
}) {
|
||||||
|
return FileModel(
|
||||||
|
id: id ?? this.id,
|
||||||
|
organizationId: organizationId ?? this.organizationId,
|
||||||
|
userId: userId ?? this.userId,
|
||||||
|
fileName: fileName ?? this.fileName,
|
||||||
|
originalName: originalName ?? this.originalName,
|
||||||
|
fileUrl: fileUrl ?? this.fileUrl,
|
||||||
|
fileSize: fileSize ?? this.fileSize,
|
||||||
|
mimeType: mimeType ?? this.mimeType,
|
||||||
|
fileType: fileType ?? this.fileType,
|
||||||
|
uploadPath: uploadPath ?? this.uploadPath,
|
||||||
|
isPublic: isPublic ?? this.isPublic,
|
||||||
|
createdAt: createdAt ?? this.createdAt,
|
||||||
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'FileModel(id: $id, organizationId: $organizationId, userId: $userId, fileName: $fileName, originalName: $originalName, fileUrl: $fileUrl, fileSize: $fileSize, mimeType: $mimeType, fileType: $fileType, uploadPath: $uploadPath, isPublic: $isPublic, createdAt: $createdAt, updatedAt: $updatedAt)';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
class InventoryAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final InventoryAnalyticData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
InventoryAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
// From JSON
|
||||||
|
factory InventoryAnalyticResponseModel.fromJson(Map<String, dynamic> json) {
|
||||||
|
return InventoryAnalyticResponseModel(
|
||||||
|
success: json['success'],
|
||||||
|
data: json['data'] != null
|
||||||
|
? InventoryAnalyticData.fromMap(json['data'])
|
||||||
|
: null,
|
||||||
|
errors: json['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// To JSON
|
||||||
|
Map<String, dynamic> toJson() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// From Map
|
||||||
|
factory InventoryAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return InventoryAnalyticResponseModel(
|
||||||
|
success: map['success'],
|
||||||
|
data: map['data'] != null
|
||||||
|
? InventoryAnalyticData.fromMap(map['data'])
|
||||||
|
: null,
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// To Map
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InventoryAnalyticData {
|
||||||
|
final InventorySummary summary;
|
||||||
|
final List<InventoryProductItem> products;
|
||||||
|
final List<InventoryIngredientItem> ingredients;
|
||||||
|
|
||||||
|
InventoryAnalyticData({
|
||||||
|
required this.summary,
|
||||||
|
required this.products,
|
||||||
|
required this.ingredients,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory InventoryAnalyticData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return InventoryAnalyticData(
|
||||||
|
summary: InventorySummary.fromMap(map['summary']),
|
||||||
|
products: map['products'] == null
|
||||||
|
? []
|
||||||
|
: List<InventoryProductItem>.from(
|
||||||
|
map['products']?.map((x) => InventoryProductItem.fromMap(x)) ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
ingredients: map['ingredients'] == null
|
||||||
|
? []
|
||||||
|
: List<InventoryIngredientItem>.from(
|
||||||
|
map['ingredients']
|
||||||
|
?.map((x) => InventoryIngredientItem.fromMap(x)) ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'summary': summary.toMap(),
|
||||||
|
'products': products.map((x) => x.toMap()).toList(),
|
||||||
|
'ingredients': ingredients.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InventorySummary {
|
||||||
|
final int totalProducts;
|
||||||
|
final int totalIngredients;
|
||||||
|
final int totalValue;
|
||||||
|
final int lowStockProducts;
|
||||||
|
final int lowStockIngredients;
|
||||||
|
final int zeroStockProducts;
|
||||||
|
final int zeroStockIngredients;
|
||||||
|
final int totalSoldProducts;
|
||||||
|
final int totalSoldIngredients;
|
||||||
|
final String outletId;
|
||||||
|
final String outletName;
|
||||||
|
final DateTime generatedAt;
|
||||||
|
|
||||||
|
InventorySummary({
|
||||||
|
required this.totalProducts,
|
||||||
|
required this.totalIngredients,
|
||||||
|
required this.totalValue,
|
||||||
|
required this.lowStockProducts,
|
||||||
|
required this.lowStockIngredients,
|
||||||
|
required this.zeroStockProducts,
|
||||||
|
required this.zeroStockIngredients,
|
||||||
|
required this.totalSoldProducts,
|
||||||
|
required this.totalSoldIngredients,
|
||||||
|
required this.outletId,
|
||||||
|
required this.outletName,
|
||||||
|
required this.generatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory InventorySummary.fromMap(Map<String, dynamic> map) {
|
||||||
|
return InventorySummary(
|
||||||
|
totalProducts: map['total_products'] ?? 0,
|
||||||
|
totalIngredients: map['total_ingredients'] ?? 0,
|
||||||
|
totalValue: map['total_value'] ?? 0,
|
||||||
|
lowStockProducts: map['low_stock_products'] ?? 0,
|
||||||
|
lowStockIngredients: map['low_stock_ingredients'] ?? 0,
|
||||||
|
zeroStockProducts: map['zero_stock_products'] ?? 0,
|
||||||
|
zeroStockIngredients: map['zero_stock_ingredients'] ?? 0,
|
||||||
|
totalSoldProducts: map['total_sold_products'] ?? 0,
|
||||||
|
totalSoldIngredients: map['total_sold_ingredients'] ?? 0,
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
outletName: map['outlet_name'],
|
||||||
|
generatedAt: DateTime.parse(map['generated_at']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'total_products': totalProducts,
|
||||||
|
'total_ingredients': totalIngredients,
|
||||||
|
'total_value': totalValue,
|
||||||
|
'low_stock_products': lowStockProducts,
|
||||||
|
'low_stock_ingredients': lowStockIngredients,
|
||||||
|
'zero_stock_products': zeroStockProducts,
|
||||||
|
'zero_stock_ingredients': zeroStockIngredients,
|
||||||
|
'total_sold_products': totalSoldProducts,
|
||||||
|
'total_sold_ingredients': totalSoldIngredients,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'outlet_name': outletName,
|
||||||
|
'generated_at': generatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InventoryProductItem {
|
||||||
|
final String id;
|
||||||
|
final String productId;
|
||||||
|
final String productName;
|
||||||
|
final String categoryName;
|
||||||
|
final int quantity;
|
||||||
|
final int reorderLevel;
|
||||||
|
final num unitCost;
|
||||||
|
final int totalValue;
|
||||||
|
final int totalIn;
|
||||||
|
final int totalOut;
|
||||||
|
final bool isLowStock;
|
||||||
|
final bool isZeroStock;
|
||||||
|
final DateTime updatedAt;
|
||||||
|
|
||||||
|
InventoryProductItem({
|
||||||
|
required this.id,
|
||||||
|
required this.productId,
|
||||||
|
required this.productName,
|
||||||
|
required this.categoryName,
|
||||||
|
required this.quantity,
|
||||||
|
required this.reorderLevel,
|
||||||
|
required this.unitCost,
|
||||||
|
required this.totalValue,
|
||||||
|
required this.totalIn,
|
||||||
|
required this.totalOut,
|
||||||
|
required this.isLowStock,
|
||||||
|
required this.isZeroStock,
|
||||||
|
required this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory InventoryProductItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return InventoryProductItem(
|
||||||
|
id: map['id'],
|
||||||
|
productId: map['product_id'],
|
||||||
|
productName: map['product_name'],
|
||||||
|
categoryName: map['category_name'],
|
||||||
|
quantity: map['quantity'] ?? 0,
|
||||||
|
reorderLevel: map['reorder_level'] ?? 0,
|
||||||
|
unitCost: map['unit_cost'] ?? 0,
|
||||||
|
totalValue: map['total_value'] ?? 0,
|
||||||
|
totalIn: map['total_in'] ?? 0,
|
||||||
|
totalOut: map['total_out'] ?? 0,
|
||||||
|
isLowStock: map['is_low_stock'] ?? false,
|
||||||
|
isZeroStock: map['is_zero_stock'] ?? false,
|
||||||
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'product_id': productId,
|
||||||
|
'product_name': productName,
|
||||||
|
'category_name': categoryName,
|
||||||
|
'quantity': quantity,
|
||||||
|
'reorder_level': reorderLevel,
|
||||||
|
'unit_cost': unitCost,
|
||||||
|
'total_value': totalValue,
|
||||||
|
'total_in': totalIn,
|
||||||
|
'total_out': totalOut,
|
||||||
|
'is_low_stock': isLowStock,
|
||||||
|
'is_zero_stock': isZeroStock,
|
||||||
|
'updated_at': updatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class InventoryIngredientItem {
|
||||||
|
final String id;
|
||||||
|
final String ingredientId;
|
||||||
|
final String ingredientName;
|
||||||
|
final String unitName;
|
||||||
|
final int quantity;
|
||||||
|
final int reorderLevel;
|
||||||
|
final num unitCost;
|
||||||
|
final int totalValue;
|
||||||
|
final int totalIn;
|
||||||
|
final int totalOut;
|
||||||
|
final bool isLowStock;
|
||||||
|
final bool isZeroStock;
|
||||||
|
final DateTime updatedAt;
|
||||||
|
|
||||||
|
InventoryIngredientItem({
|
||||||
|
required this.id,
|
||||||
|
required this.ingredientId,
|
||||||
|
required this.ingredientName,
|
||||||
|
required this.unitName,
|
||||||
|
required this.quantity,
|
||||||
|
required this.reorderLevel,
|
||||||
|
required this.unitCost,
|
||||||
|
required this.totalValue,
|
||||||
|
required this.totalIn,
|
||||||
|
required this.totalOut,
|
||||||
|
required this.isLowStock,
|
||||||
|
required this.isZeroStock,
|
||||||
|
required this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory InventoryIngredientItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return InventoryIngredientItem(
|
||||||
|
id: map['id'],
|
||||||
|
ingredientId: map['ingredient_id'],
|
||||||
|
ingredientName: map['ingredient_name'],
|
||||||
|
unitName: map['unit_name'],
|
||||||
|
quantity: map['quantity'] ?? 0,
|
||||||
|
reorderLevel: map['reorder_level'] ?? 0,
|
||||||
|
unitCost: map['unit_cost'] ?? 0,
|
||||||
|
totalValue: map['total_value'] ?? 0,
|
||||||
|
totalIn: map['total_in'] ?? 0,
|
||||||
|
totalOut: map['total_out'] ?? 0,
|
||||||
|
isLowStock: map['is_low_stock'] ?? false,
|
||||||
|
isZeroStock: map['is_zero_stock'] ?? false,
|
||||||
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'ingredient_id': ingredientId,
|
||||||
|
'ingredient_name': ingredientName,
|
||||||
|
'unit_name': unitName,
|
||||||
|
'quantity': quantity,
|
||||||
|
'reorder_level': reorderLevel,
|
||||||
|
'unit_cost': unitCost,
|
||||||
|
'total_value': totalValue,
|
||||||
|
'total_in': totalIn,
|
||||||
|
'total_out': totalOut,
|
||||||
|
'is_low_stock': isLowStock,
|
||||||
|
'is_zero_stock': isZeroStock,
|
||||||
|
'updated_at': updatedAt.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +1,28 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
class OrderResponseModel {
|
import 'package:enaklo_pos/data/models/response/product_response_model.dart';
|
||||||
|
import 'package:enaklo_pos/presentation/home/models/product_quantity.dart';
|
||||||
|
|
||||||
|
class OrderDetailResponseModel {
|
||||||
final bool? success;
|
final bool? success;
|
||||||
final OrderData? data;
|
final Order? data;
|
||||||
final dynamic errors;
|
final dynamic errors;
|
||||||
|
|
||||||
OrderResponseModel({
|
OrderDetailResponseModel({
|
||||||
this.success,
|
this.success,
|
||||||
this.data,
|
this.data,
|
||||||
this.errors,
|
this.errors,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory OrderResponseModel.fromJson(String str) =>
|
factory OrderDetailResponseModel.fromJson(String str) =>
|
||||||
OrderResponseModel.fromMap(json.decode(str));
|
OrderDetailResponseModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
String toJson() => json.encode(toMap());
|
String toJson() => json.encode(toMap());
|
||||||
|
|
||||||
factory OrderResponseModel.fromMap(Map<String, dynamic> json) =>
|
factory OrderDetailResponseModel.fromMap(Map<String, dynamic> json) =>
|
||||||
OrderResponseModel(
|
OrderDetailResponseModel(
|
||||||
success: json["success"],
|
success: json["success"],
|
||||||
data: json["data"] == null ? null : OrderData.fromMap(json["data"]),
|
data: json["data"] == null ? null : Order.fromMap(json["data"]),
|
||||||
errors: json["errors"],
|
errors: json["errors"],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -30,40 +33,77 @@ class OrderResponseModel {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class OrderResponseModel {
|
||||||
|
final bool? success;
|
||||||
|
final OrderData? data;
|
||||||
|
|
||||||
|
OrderResponseModel({
|
||||||
|
this.success,
|
||||||
|
this.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory OrderResponseModel.fromJson(String str) =>
|
||||||
|
OrderResponseModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
|
String toJson() => json.encode(toMap());
|
||||||
|
|
||||||
|
factory OrderResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return OrderResponseModel(
|
||||||
|
success: map['success'] ?? false,
|
||||||
|
data: OrderData.fromMap(map['data']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class OrderData {
|
class OrderData {
|
||||||
final List<Order>? orders;
|
final List<Order>? orders;
|
||||||
|
final List<Payment>? payments;
|
||||||
final int? totalCount;
|
final int? totalCount;
|
||||||
final int? page;
|
final int? page;
|
||||||
final int? limit;
|
final int? limit;
|
||||||
final int? totalPages;
|
final int? totalPages;
|
||||||
|
|
||||||
OrderData({
|
OrderData({
|
||||||
this.orders,
|
required this.orders,
|
||||||
this.totalCount,
|
required this.payments,
|
||||||
this.page,
|
required this.totalCount,
|
||||||
this.limit,
|
required this.page,
|
||||||
this.totalPages,
|
required this.limit,
|
||||||
|
required this.totalPages,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory OrderData.fromMap(Map<String, dynamic> json) => OrderData(
|
factory OrderData.fromMap(Map<String, dynamic> map) {
|
||||||
orders: json["orders"] == null
|
return OrderData(
|
||||||
? []
|
orders: map["orders"] == null
|
||||||
: List<Order>.from(json["orders"].map((x) => Order.fromMap(x))),
|
? []
|
||||||
totalCount: json["total_count"],
|
: List<Order>.from(map['orders']?.map((x) => Order.fromMap(x))),
|
||||||
page: json["page"],
|
payments: map["payments"] == null
|
||||||
limit: json["limit"],
|
? []
|
||||||
totalPages: json["total_pages"],
|
: List<Payment>.from(map['payments']?.map((x) => Payment.fromMap(x))),
|
||||||
);
|
totalCount: map['total_count'],
|
||||||
|
page: map['page'],
|
||||||
|
limit: map['limit'],
|
||||||
|
totalPages: map['total_pages'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() {
|
||||||
"orders": orders == null
|
return {
|
||||||
? []
|
'orders': orders?.map((x) => x.toMap()).toList(),
|
||||||
: List<dynamic>.from(orders!.map((x) => x.toMap())),
|
'payments': payments?.map((x) => x.toMap()).toList(),
|
||||||
"total_count": totalCount,
|
'total_count': totalCount,
|
||||||
"page": page,
|
'page': page,
|
||||||
"limit": limit,
|
'limit': limit,
|
||||||
"total_pages": totalPages,
|
'total_pages': totalPages,
|
||||||
};
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Order {
|
class Order {
|
||||||
@@ -78,11 +118,21 @@ class Order {
|
|||||||
final int? taxAmount;
|
final int? taxAmount;
|
||||||
final int? discountAmount;
|
final int? discountAmount;
|
||||||
final int? totalAmount;
|
final int? totalAmount;
|
||||||
|
final num? totalCost;
|
||||||
|
final int? remainingAmount;
|
||||||
|
final String? paymentStatus;
|
||||||
|
final int? refundAmount;
|
||||||
|
final bool? isVoid;
|
||||||
|
final bool? isRefund;
|
||||||
final String? notes;
|
final String? notes;
|
||||||
final Map<String, dynamic>? metadata;
|
final Map<String, dynamic>? metadata;
|
||||||
final DateTime? createdAt;
|
final DateTime? createdAt;
|
||||||
final DateTime? updatedAt;
|
final DateTime? updatedAt;
|
||||||
final List<OrderItem>? orderItems;
|
final List<OrderItem>? orderItems;
|
||||||
|
final List<Payment>? payments;
|
||||||
|
final int? totalPaid;
|
||||||
|
final int? paymentCount;
|
||||||
|
final String? splitType;
|
||||||
|
|
||||||
Order({
|
Order({
|
||||||
this.id,
|
this.id,
|
||||||
@@ -96,75 +146,108 @@ class Order {
|
|||||||
this.taxAmount,
|
this.taxAmount,
|
||||||
this.discountAmount,
|
this.discountAmount,
|
||||||
this.totalAmount,
|
this.totalAmount,
|
||||||
|
this.totalCost,
|
||||||
|
this.remainingAmount,
|
||||||
|
this.paymentStatus,
|
||||||
|
this.refundAmount,
|
||||||
|
this.isVoid,
|
||||||
|
this.isRefund,
|
||||||
this.notes,
|
this.notes,
|
||||||
this.metadata,
|
this.metadata,
|
||||||
this.createdAt,
|
this.createdAt,
|
||||||
this.updatedAt,
|
this.updatedAt,
|
||||||
this.orderItems,
|
this.orderItems,
|
||||||
|
this.payments,
|
||||||
|
this.totalPaid,
|
||||||
|
this.paymentCount,
|
||||||
|
this.splitType,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory Order.fromMap(Map<String, dynamic> json) => Order(
|
factory Order.fromMap(Map<String, dynamic> map) {
|
||||||
id: json["id"],
|
return Order(
|
||||||
orderNumber: json["order_number"],
|
id: map['id'],
|
||||||
outletId: json["outlet_id"],
|
orderNumber: map['order_number'],
|
||||||
userId: json["user_id"],
|
outletId: map['outlet_id'],
|
||||||
tableNumber: json["table_number"],
|
userId: map['user_id'],
|
||||||
orderType: json["order_type"],
|
tableNumber: map['table_number'],
|
||||||
status: json["status"],
|
orderType: map['order_type'],
|
||||||
subtotal: json["subtotal"],
|
status: map['status'],
|
||||||
taxAmount: json["tax_amount"],
|
subtotal: map['subtotal'],
|
||||||
discountAmount: json["discount_amount"],
|
taxAmount: map['tax_amount'],
|
||||||
totalAmount: json["total_amount"],
|
discountAmount: map['discount_amount'],
|
||||||
notes: json["notes"],
|
totalAmount: map['total_amount'],
|
||||||
metadata: json["metadata"] ?? {},
|
totalCost: map['total_cost'],
|
||||||
createdAt: json["created_at"] == null
|
remainingAmount: map['remaining_amount'],
|
||||||
? null
|
paymentStatus: map['payment_status'],
|
||||||
: DateTime.parse(json["created_at"]),
|
refundAmount: map['refund_amount'],
|
||||||
updatedAt: json["updated_at"] == null
|
isVoid: map['is_void'],
|
||||||
? null
|
isRefund: map['is_refund'],
|
||||||
: DateTime.parse(json["updated_at"]),
|
notes: map['notes'],
|
||||||
orderItems: json["order_items"] == null
|
metadata: map['metadata'] ?? {},
|
||||||
? []
|
createdAt: DateTime.parse(map['created_at']),
|
||||||
: List<OrderItem>.from(
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
json["order_items"].map((x) => OrderItem.fromMap(x))),
|
orderItems: map["order_items"] == null
|
||||||
);
|
? []
|
||||||
|
: List<OrderItem>.from(
|
||||||
|
map['order_items'].map((x) => OrderItem.fromMap(x))),
|
||||||
|
payments: map["payments"] == null
|
||||||
|
? []
|
||||||
|
: List<Payment>.from(map['payments'].map((x) => Payment.fromMap(x))),
|
||||||
|
totalPaid: map['total_paid'],
|
||||||
|
paymentCount: map['payment_count'],
|
||||||
|
splitType: map['split_type'] ?? "",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() {
|
||||||
"id": id,
|
return {
|
||||||
"order_number": orderNumber,
|
'id': id,
|
||||||
"outlet_id": outletId,
|
'order_number': orderNumber,
|
||||||
"user_id": userId,
|
'outlet_id': outletId,
|
||||||
"table_number": tableNumber,
|
'user_id': userId,
|
||||||
"order_type": orderType,
|
'table_number': tableNumber,
|
||||||
"status": status,
|
'order_type': orderType,
|
||||||
"subtotal": subtotal,
|
'status': status,
|
||||||
"tax_amount": taxAmount,
|
'subtotal': subtotal,
|
||||||
"discount_amount": discountAmount,
|
'tax_amount': taxAmount,
|
||||||
"total_amount": totalAmount,
|
'discount_amount': discountAmount,
|
||||||
"notes": notes,
|
'total_amount': totalAmount,
|
||||||
"metadata": metadata,
|
'total_cost': totalCost,
|
||||||
"created_at": createdAt?.toIso8601String(),
|
'remaining_amount': remainingAmount,
|
||||||
"updated_at": updatedAt?.toIso8601String(),
|
'payment_status': paymentStatus,
|
||||||
"order_items": orderItems == null
|
'refund_amount': refundAmount,
|
||||||
? []
|
'is_void': isVoid,
|
||||||
: List<dynamic>.from(orderItems!.map((x) => x.toMap())),
|
'is_refund': isRefund,
|
||||||
};
|
'notes': notes,
|
||||||
|
'metadata': metadata,
|
||||||
|
'created_at': createdAt?.toIso8601String(),
|
||||||
|
'updated_at': updatedAt?.toIso8601String(),
|
||||||
|
'order_items': orderItems?.map((x) => x.toMap()).toList(),
|
||||||
|
'payments': payments?.map((x) => x.toMap()).toList(),
|
||||||
|
'total_paid': totalPaid,
|
||||||
|
'payment_count': paymentCount,
|
||||||
|
'split_type': splitType,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class OrderItem {
|
class OrderItem {
|
||||||
final String? id;
|
String? id;
|
||||||
final String? orderId;
|
String? orderId;
|
||||||
final String? productId;
|
String? productId;
|
||||||
final String? productName;
|
String? productName;
|
||||||
final String? productVariantId;
|
String? productVariantId;
|
||||||
final int? quantity;
|
String? productVariantName;
|
||||||
final int? unitPrice;
|
int? quantity;
|
||||||
final int? totalPrice;
|
int? unitPrice;
|
||||||
final List<dynamic>? modifiers;
|
int? totalPrice;
|
||||||
final String? notes;
|
List<dynamic>? modifiers;
|
||||||
final String? status;
|
String? notes;
|
||||||
final DateTime? createdAt;
|
String? status;
|
||||||
final DateTime? updatedAt;
|
DateTime? createdAt;
|
||||||
|
DateTime? updatedAt;
|
||||||
|
String? printerType;
|
||||||
|
int? paidQuantity;
|
||||||
|
|
||||||
OrderItem({
|
OrderItem({
|
||||||
this.id,
|
this.id,
|
||||||
@@ -172,6 +255,7 @@ class OrderItem {
|
|||||||
this.productId,
|
this.productId,
|
||||||
this.productName,
|
this.productName,
|
||||||
this.productVariantId,
|
this.productVariantId,
|
||||||
|
this.productVariantName,
|
||||||
this.quantity,
|
this.quantity,
|
||||||
this.unitPrice,
|
this.unitPrice,
|
||||||
this.totalPrice,
|
this.totalPrice,
|
||||||
@@ -180,41 +264,240 @@ class OrderItem {
|
|||||||
this.status,
|
this.status,
|
||||||
this.createdAt,
|
this.createdAt,
|
||||||
this.updatedAt,
|
this.updatedAt,
|
||||||
|
this.printerType,
|
||||||
|
this.paidQuantity,
|
||||||
});
|
});
|
||||||
|
|
||||||
factory OrderItem.fromMap(Map<String, dynamic> json) => OrderItem(
|
factory OrderItem.fromMap(Map<String, dynamic> map) {
|
||||||
id: json["id"],
|
return OrderItem(
|
||||||
orderId: json["order_id"],
|
id: map['id'],
|
||||||
productId: json["product_id"],
|
orderId: map['order_id'],
|
||||||
productName: json["product_name"],
|
productId: map['product_id'],
|
||||||
productVariantId: json["product_variant_id"],
|
productName: map['product_name'],
|
||||||
quantity: json["quantity"],
|
productVariantId: map['product_variant_id'],
|
||||||
unitPrice: json["unit_price"],
|
productVariantName: map['product_variant_name'],
|
||||||
totalPrice: json["total_price"],
|
quantity: map['quantity'],
|
||||||
modifiers: json["modifiers"] ?? [],
|
unitPrice: map['unit_price'],
|
||||||
notes: json["notes"],
|
totalPrice: map['total_price'],
|
||||||
status: json["status"],
|
modifiers:
|
||||||
createdAt: json["created_at"] == null
|
map['modifiers'] == null ? [] : List<dynamic>.from(map['modifiers']),
|
||||||
? null
|
notes: map['notes'],
|
||||||
: DateTime.parse(json["created_at"]),
|
status: map['status'],
|
||||||
updatedAt: json["updated_at"] == null
|
createdAt: DateTime.parse(map['created_at']),
|
||||||
? null
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
: DateTime.parse(json["updated_at"]),
|
printerType: map['printer_type'],
|
||||||
);
|
paidQuantity: map['paid_quantity'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() {
|
||||||
"id": id,
|
return {
|
||||||
"order_id": orderId,
|
'id': id,
|
||||||
"product_id": productId,
|
'order_id': orderId,
|
||||||
"product_name": productName,
|
'product_id': productId,
|
||||||
"product_variant_id": productVariantId,
|
'product_name': productName,
|
||||||
"quantity": quantity,
|
'product_variant_id': productVariantId,
|
||||||
"unit_price": unitPrice,
|
'product_variant_name': productVariantName,
|
||||||
"total_price": totalPrice,
|
'quantity': quantity,
|
||||||
"modifiers": modifiers,
|
'unit_price': unitPrice,
|
||||||
"notes": notes,
|
'total_price': totalPrice,
|
||||||
"status": status,
|
'modifiers': modifiers,
|
||||||
"created_at": createdAt?.toIso8601String(),
|
'notes': notes,
|
||||||
"updated_at": updatedAt?.toIso8601String(),
|
'status': status,
|
||||||
};
|
'created_at': createdAt?.toIso8601String(),
|
||||||
|
'updated_at': updatedAt?.toIso8601String(),
|
||||||
|
'printer_type': printerType,
|
||||||
|
'paid_quantity': paidQuantity,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Payment {
|
||||||
|
final String? id;
|
||||||
|
final String? orderId;
|
||||||
|
final String? paymentMethodId;
|
||||||
|
final String? paymentMethodName;
|
||||||
|
final String? paymentMethodType;
|
||||||
|
final int? amount;
|
||||||
|
final String? status;
|
||||||
|
final int? splitNumber;
|
||||||
|
final int? splitTotal;
|
||||||
|
final String? splitDescription;
|
||||||
|
final int? refundAmount;
|
||||||
|
final Map<String, dynamic>? metadata;
|
||||||
|
final DateTime? createdAt;
|
||||||
|
final DateTime? updatedAt;
|
||||||
|
|
||||||
|
Payment({
|
||||||
|
this.id,
|
||||||
|
this.orderId,
|
||||||
|
this.paymentMethodId,
|
||||||
|
this.paymentMethodName,
|
||||||
|
this.paymentMethodType,
|
||||||
|
this.amount,
|
||||||
|
this.status,
|
||||||
|
this.splitNumber,
|
||||||
|
this.splitTotal,
|
||||||
|
this.splitDescription,
|
||||||
|
this.refundAmount,
|
||||||
|
this.metadata,
|
||||||
|
this.createdAt,
|
||||||
|
this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory Payment.fromMap(Map<String, dynamic> map) {
|
||||||
|
return Payment(
|
||||||
|
id: map['id'],
|
||||||
|
orderId: map['order_id'],
|
||||||
|
paymentMethodId: map['payment_method_id'],
|
||||||
|
paymentMethodName: map['payment_method_name'],
|
||||||
|
paymentMethodType: map['payment_method_type'],
|
||||||
|
amount: map['amount'],
|
||||||
|
status: map['status'],
|
||||||
|
splitNumber: map['split_number'],
|
||||||
|
splitTotal: map['split_total'],
|
||||||
|
splitDescription: map['split_description'],
|
||||||
|
refundAmount: map['refund_amount'],
|
||||||
|
metadata: map['metadata'] ?? {},
|
||||||
|
createdAt: DateTime.parse(map['created_at']),
|
||||||
|
updatedAt: DateTime.parse(map['updated_at']),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'order_id': orderId,
|
||||||
|
'payment_method_id': paymentMethodId,
|
||||||
|
'payment_method_name': paymentMethodName,
|
||||||
|
'payment_method_type': paymentMethodType,
|
||||||
|
'amount': amount,
|
||||||
|
'status': status,
|
||||||
|
'split_number': splitNumber,
|
||||||
|
'split_total': splitTotal,
|
||||||
|
'split_description': splitDescription,
|
||||||
|
'refund_amount': refundAmount,
|
||||||
|
'metadata': metadata,
|
||||||
|
'created_at': createdAt?.toIso8601String(),
|
||||||
|
'updated_at': updatedAt?.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OrderItemListExtension on List<OrderItem> {
|
||||||
|
List<ProductQuantity> toProductQuantities() => map((e) => ProductQuantity(
|
||||||
|
product: Product(
|
||||||
|
id: e.productId,
|
||||||
|
name: e.productName,
|
||||||
|
price: e.unitPrice,
|
||||||
|
printerType: e.printerType,
|
||||||
|
),
|
||||||
|
variant: ProductVariant(
|
||||||
|
id: e.productVariantId,
|
||||||
|
name: e.productVariantName,
|
||||||
|
productId: e.productId,
|
||||||
|
),
|
||||||
|
notes: e.notes ?? '',
|
||||||
|
quantity: e.quantity ?? 0,
|
||||||
|
)).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OrderCopyWith on Order {
|
||||||
|
Order copyWith({
|
||||||
|
String? id,
|
||||||
|
String? orderNumber,
|
||||||
|
String? outletId,
|
||||||
|
String? userId,
|
||||||
|
String? tableNumber,
|
||||||
|
String? orderType,
|
||||||
|
String? status,
|
||||||
|
int? subtotal,
|
||||||
|
int? taxAmount,
|
||||||
|
int? discountAmount,
|
||||||
|
int? totalAmount,
|
||||||
|
num? totalCost,
|
||||||
|
int? remainingAmount,
|
||||||
|
String? paymentStatus,
|
||||||
|
int? refundAmount,
|
||||||
|
bool? isVoid,
|
||||||
|
bool? isRefund,
|
||||||
|
String? notes,
|
||||||
|
Map<String, dynamic>? metadata,
|
||||||
|
DateTime? createdAt,
|
||||||
|
DateTime? updatedAt,
|
||||||
|
List<OrderItem>? orderItems,
|
||||||
|
List<Payment>? payments,
|
||||||
|
int? totalPaid,
|
||||||
|
int? paymentCount,
|
||||||
|
String? splitType,
|
||||||
|
}) {
|
||||||
|
return Order(
|
||||||
|
id: id ?? this.id,
|
||||||
|
orderNumber: orderNumber ?? this.orderNumber,
|
||||||
|
outletId: outletId ?? this.outletId,
|
||||||
|
userId: userId ?? this.userId,
|
||||||
|
tableNumber: tableNumber ?? this.tableNumber,
|
||||||
|
orderType: orderType ?? this.orderType,
|
||||||
|
status: status ?? this.status,
|
||||||
|
subtotal: subtotal ?? this.subtotal,
|
||||||
|
taxAmount: taxAmount ?? this.taxAmount,
|
||||||
|
discountAmount: discountAmount ?? this.discountAmount,
|
||||||
|
totalAmount: totalAmount ?? this.totalAmount,
|
||||||
|
totalCost: totalCost ?? this.totalCost,
|
||||||
|
remainingAmount: remainingAmount ?? this.remainingAmount,
|
||||||
|
paymentStatus: paymentStatus ?? this.paymentStatus,
|
||||||
|
refundAmount: refundAmount ?? this.refundAmount,
|
||||||
|
isVoid: isVoid ?? this.isVoid,
|
||||||
|
isRefund: isRefund ?? this.isRefund,
|
||||||
|
notes: notes ?? this.notes,
|
||||||
|
metadata: metadata ?? this.metadata,
|
||||||
|
createdAt: createdAt ?? this.createdAt,
|
||||||
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
|
orderItems: orderItems ?? this.orderItems,
|
||||||
|
payments: payments ?? this.payments,
|
||||||
|
totalPaid: totalPaid ?? this.totalPaid,
|
||||||
|
paymentCount: paymentCount ?? this.paymentCount,
|
||||||
|
splitType: splitType ?? this.splitType,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension OrderItemCopyWith on OrderItem {
|
||||||
|
OrderItem copyWith({
|
||||||
|
String? id,
|
||||||
|
String? orderId,
|
||||||
|
String? productId,
|
||||||
|
String? productName,
|
||||||
|
String? productVariantId,
|
||||||
|
String? productVariantName,
|
||||||
|
int? quantity,
|
||||||
|
int? unitPrice,
|
||||||
|
int? totalPrice,
|
||||||
|
List<dynamic>? modifiers,
|
||||||
|
String? notes,
|
||||||
|
String? status,
|
||||||
|
DateTime? createdAt,
|
||||||
|
DateTime? updatedAt,
|
||||||
|
String? printerType,
|
||||||
|
int? paidQuantity,
|
||||||
|
}) {
|
||||||
|
return OrderItem(
|
||||||
|
id: id ?? this.id,
|
||||||
|
orderId: orderId ?? this.orderId,
|
||||||
|
productId: productId ?? this.productId,
|
||||||
|
productName: productName ?? this.productName,
|
||||||
|
productVariantId: productVariantId ?? this.productVariantId,
|
||||||
|
productVariantName: productVariantName ?? this.productVariantName,
|
||||||
|
quantity: quantity ?? this.quantity,
|
||||||
|
unitPrice: unitPrice ?? this.unitPrice,
|
||||||
|
totalPrice: totalPrice ?? this.totalPrice,
|
||||||
|
modifiers: modifiers ?? this.modifiers,
|
||||||
|
notes: notes ?? this.notes,
|
||||||
|
status: status ?? this.status,
|
||||||
|
createdAt: createdAt ?? this.createdAt,
|
||||||
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
|
printerType: printerType ?? this.printerType,
|
||||||
|
paidQuantity: paidQuantity ?? this.paidQuantity,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
class PaymentMethodAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final PaymentMethodAnalyticData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
PaymentMethodAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticResponseModel.fromJson(
|
||||||
|
Map<String, dynamic> json) =>
|
||||||
|
PaymentMethodAnalyticResponseModel.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return PaymentMethodAnalyticResponseModel(
|
||||||
|
success: map['success'],
|
||||||
|
data: map['data'] == null
|
||||||
|
? null
|
||||||
|
: PaymentMethodAnalyticData.fromMap(map['data']),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentMethodAnalyticData {
|
||||||
|
final String organizationId;
|
||||||
|
final String outletId;
|
||||||
|
final DateTime dateFrom;
|
||||||
|
final DateTime dateTo;
|
||||||
|
final String groupBy;
|
||||||
|
final PaymentSummary summary;
|
||||||
|
final List<PaymentMethodAnalyticItem> data;
|
||||||
|
|
||||||
|
PaymentMethodAnalyticData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.outletId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.groupBy,
|
||||||
|
required this.summary,
|
||||||
|
required this.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticData.fromJson(Map<String, dynamic> json) =>
|
||||||
|
PaymentMethodAnalyticData.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return PaymentMethodAnalyticData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
dateFrom: DateTime.parse(map['date_from']),
|
||||||
|
dateTo: DateTime.parse(map['date_to']),
|
||||||
|
groupBy: map['group_by'],
|
||||||
|
summary: PaymentSummary.fromMap(map['summary']),
|
||||||
|
data: map['data'] == null
|
||||||
|
? []
|
||||||
|
: List<PaymentMethodAnalyticItem>.from(
|
||||||
|
map['data']?.map((x) => PaymentMethodAnalyticItem.fromMap(x)) ??
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'date_from': dateFrom.toIso8601String(),
|
||||||
|
'date_to': dateTo.toIso8601String(),
|
||||||
|
'group_by': groupBy,
|
||||||
|
'summary': summary.toMap(),
|
||||||
|
'data': data.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentSummary {
|
||||||
|
final int totalAmount;
|
||||||
|
final int totalOrders;
|
||||||
|
final int totalPayments;
|
||||||
|
final double averageOrderValue;
|
||||||
|
|
||||||
|
PaymentSummary({
|
||||||
|
required this.totalAmount,
|
||||||
|
required this.totalOrders,
|
||||||
|
required this.totalPayments,
|
||||||
|
required this.averageOrderValue,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentSummary.fromJson(Map<String, dynamic> json) =>
|
||||||
|
PaymentSummary.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory PaymentSummary.fromMap(Map<String, dynamic> map) {
|
||||||
|
return PaymentSummary(
|
||||||
|
totalAmount: map['total_amount'],
|
||||||
|
totalOrders: map['total_orders'],
|
||||||
|
totalPayments: map['total_payments'],
|
||||||
|
averageOrderValue: (map['average_order_value'] as num).toDouble(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'total_amount': totalAmount,
|
||||||
|
'total_orders': totalOrders,
|
||||||
|
'total_payments': totalPayments,
|
||||||
|
'average_order_value': averageOrderValue,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentMethodAnalyticItem {
|
||||||
|
final String paymentMethodId;
|
||||||
|
final String paymentMethodName;
|
||||||
|
final String paymentMethodType;
|
||||||
|
final int totalAmount;
|
||||||
|
final int orderCount;
|
||||||
|
final int paymentCount;
|
||||||
|
final num percentage;
|
||||||
|
|
||||||
|
PaymentMethodAnalyticItem({
|
||||||
|
required this.paymentMethodId,
|
||||||
|
required this.paymentMethodName,
|
||||||
|
required this.paymentMethodType,
|
||||||
|
required this.totalAmount,
|
||||||
|
required this.orderCount,
|
||||||
|
required this.paymentCount,
|
||||||
|
required this.percentage,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticItem.fromJson(Map<String, dynamic> json) =>
|
||||||
|
PaymentMethodAnalyticItem.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory PaymentMethodAnalyticItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return PaymentMethodAnalyticItem(
|
||||||
|
paymentMethodId: map['payment_method_id'],
|
||||||
|
paymentMethodName: map['payment_method_name'],
|
||||||
|
paymentMethodType: map['payment_method_type'],
|
||||||
|
totalAmount: map['total_amount'],
|
||||||
|
orderCount: map['order_count'],
|
||||||
|
paymentCount: map['payment_count'],
|
||||||
|
percentage: map['percentage'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'payment_method_id': paymentMethodId,
|
||||||
|
'payment_method_name': paymentMethodName,
|
||||||
|
'payment_method_type': paymentMethodType,
|
||||||
|
'total_amount': totalAmount,
|
||||||
|
'order_count': orderCount,
|
||||||
|
'payment_count': paymentCount,
|
||||||
|
'percentage': percentage,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
class PaymentSuccessResponseModel {
|
||||||
|
final bool? success;
|
||||||
|
final PaymentData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
PaymentSuccessResponseModel({
|
||||||
|
this.success,
|
||||||
|
this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentSuccessResponseModel.fromJson(String str) =>
|
||||||
|
PaymentSuccessResponseModel.fromMap(json.decode(str));
|
||||||
|
|
||||||
|
String toJson() => json.encode(toMap());
|
||||||
|
|
||||||
|
factory PaymentSuccessResponseModel.fromMap(Map<String, dynamic> json) =>
|
||||||
|
PaymentSuccessResponseModel(
|
||||||
|
success: json["success"],
|
||||||
|
data: json["data"] == null ? null : PaymentData.fromMap(json["data"]),
|
||||||
|
errors: json["errors"],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"success": success,
|
||||||
|
"data": data?.toMap(),
|
||||||
|
"errors": errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class PaymentData {
|
||||||
|
final String? id;
|
||||||
|
final String? orderId;
|
||||||
|
final String? paymentMethodId;
|
||||||
|
final int? amount;
|
||||||
|
final String? status;
|
||||||
|
final String? transactionId;
|
||||||
|
final int? splitNumber;
|
||||||
|
final int? splitTotal;
|
||||||
|
final String? splitDescription;
|
||||||
|
final int? refundAmount;
|
||||||
|
final DateTime? createdAt;
|
||||||
|
final DateTime? updatedAt;
|
||||||
|
|
||||||
|
PaymentData({
|
||||||
|
this.id,
|
||||||
|
this.orderId,
|
||||||
|
this.paymentMethodId,
|
||||||
|
this.amount,
|
||||||
|
this.status,
|
||||||
|
this.transactionId,
|
||||||
|
this.splitNumber,
|
||||||
|
this.splitTotal,
|
||||||
|
this.splitDescription,
|
||||||
|
this.refundAmount,
|
||||||
|
this.createdAt,
|
||||||
|
this.updatedAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PaymentData.fromMap(Map<String, dynamic> json) => PaymentData(
|
||||||
|
id: json["id"],
|
||||||
|
orderId: json["order_id"],
|
||||||
|
paymentMethodId: json["payment_method_id"],
|
||||||
|
amount: json["amount"],
|
||||||
|
status: json["status"],
|
||||||
|
transactionId: json["transaction_id"],
|
||||||
|
splitNumber: json["split_number"],
|
||||||
|
splitTotal: json["split_total"],
|
||||||
|
splitDescription: json["split_description"],
|
||||||
|
refundAmount: json["refund_amount"],
|
||||||
|
createdAt: json["created_at"] == null
|
||||||
|
? null
|
||||||
|
: DateTime.parse(json["created_at"]),
|
||||||
|
updatedAt: json["updated_at"] == null
|
||||||
|
? null
|
||||||
|
: DateTime.parse(json["updated_at"]),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
"id": id,
|
||||||
|
"order_id": orderId,
|
||||||
|
"payment_method_id": paymentMethodId,
|
||||||
|
"amount": amount,
|
||||||
|
"status": status,
|
||||||
|
"transaction_id": transactionId,
|
||||||
|
"split_number": splitNumber,
|
||||||
|
"split_total": splitTotal,
|
||||||
|
"split_description": splitDescription,
|
||||||
|
"refund_amount": refundAmount,
|
||||||
|
"created_at": createdAt?.toIso8601String(),
|
||||||
|
"updated_at": updatedAt?.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -5,6 +5,8 @@ class PrintModel {
|
|||||||
final String address;
|
final String address;
|
||||||
final String paper;
|
final String paper;
|
||||||
final String type;
|
final String type;
|
||||||
|
final DateTime? createdAt;
|
||||||
|
final DateTime? updatedAt;
|
||||||
|
|
||||||
PrintModel({
|
PrintModel({
|
||||||
this.id,
|
this.id,
|
||||||
@@ -13,26 +15,130 @@ class PrintModel {
|
|||||||
required this.address,
|
required this.address,
|
||||||
required this.paper,
|
required this.paper,
|
||||||
required this.type,
|
required this.type,
|
||||||
|
this.createdAt,
|
||||||
|
this.updatedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
// from map
|
// Factory constructor from map (updated)
|
||||||
factory PrintModel.fromMap(Map<String, dynamic> map) {
|
factory PrintModel.fromMap(Map<String, dynamic> map) {
|
||||||
return PrintModel(
|
return PrintModel(
|
||||||
id: map['id'],
|
id: map['id'] as int?,
|
||||||
code: map['code'],
|
code: map['code'] as String,
|
||||||
name: map['name'],
|
name: map['name'] as String,
|
||||||
address: map['address'],
|
address: map['address'] as String,
|
||||||
paper: map['paper'],
|
paper: map['paper'] as String,
|
||||||
type: map['type'],
|
type: map['type'] as String,
|
||||||
|
createdAt: map['created_at'] != null
|
||||||
|
? DateTime.tryParse(map['created_at'] as String)
|
||||||
|
: null,
|
||||||
|
updatedAt: map['updated_at'] != null
|
||||||
|
? DateTime.tryParse(map['updated_at'] as String)
|
||||||
|
: null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// to map
|
// Convert to map for database insertion (without id, with timestamps)
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMapForInsert() {
|
||||||
"code": code,
|
final now = DateTime.now().toIso8601String();
|
||||||
"name": name,
|
return {
|
||||||
"address": address,
|
'code': code,
|
||||||
"paper": paper,
|
'name': name,
|
||||||
"type": type,
|
'address': address,
|
||||||
};
|
'paper': paper,
|
||||||
|
'type': type,
|
||||||
|
'created_at': now,
|
||||||
|
'updated_at': now,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to map for database update (without id and created_at)
|
||||||
|
Map<String, dynamic> toMapForUpdate() {
|
||||||
|
return {
|
||||||
|
'code': code,
|
||||||
|
'name': name,
|
||||||
|
'address': address,
|
||||||
|
'paper': paper,
|
||||||
|
'type': type,
|
||||||
|
'updated_at': DateTime.now().toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to complete map (original method, enhanced)
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
if (id != null) 'id': id,
|
||||||
|
'code': code,
|
||||||
|
'name': name,
|
||||||
|
'address': address,
|
||||||
|
'paper': paper,
|
||||||
|
'type': type,
|
||||||
|
if (createdAt != null) 'created_at': createdAt!.toIso8601String(),
|
||||||
|
if (updatedAt != null) 'updated_at': updatedAt!.toIso8601String(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy with method for creating modified instances
|
||||||
|
PrintModel copyWith({
|
||||||
|
int? id,
|
||||||
|
String? code,
|
||||||
|
String? name,
|
||||||
|
String? address,
|
||||||
|
String? paper,
|
||||||
|
String? type,
|
||||||
|
DateTime? createdAt,
|
||||||
|
DateTime? updatedAt,
|
||||||
|
}) {
|
||||||
|
return PrintModel(
|
||||||
|
id: id ?? this.id,
|
||||||
|
code: code ?? this.code,
|
||||||
|
name: name ?? this.name,
|
||||||
|
address: address ?? this.address,
|
||||||
|
paper: paper ?? this.paper,
|
||||||
|
type: type ?? this.type,
|
||||||
|
createdAt: createdAt ?? this.createdAt,
|
||||||
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equality and hashCode
|
||||||
|
@override
|
||||||
|
bool operator ==(Object other) {
|
||||||
|
if (identical(this, other)) return true;
|
||||||
|
return other is PrintModel &&
|
||||||
|
other.id == id &&
|
||||||
|
other.code == code &&
|
||||||
|
other.name == name &&
|
||||||
|
other.address == address &&
|
||||||
|
other.paper == paper &&
|
||||||
|
other.type == type;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
int get hashCode {
|
||||||
|
return Object.hash(id, code, name, address, paper, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// String representation for debugging (matches datasource logging)
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'PrintModel(id: $id, code: $code, name: $name, address: $address, paper: $paper, type: $type, createdAt: $createdAt, updatedAt: $updatedAt)';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation methods
|
||||||
|
bool get isValid {
|
||||||
|
return code.isNotEmpty &&
|
||||||
|
name.isNotEmpty &&
|
||||||
|
address.isNotEmpty &&
|
||||||
|
paper.isNotEmpty &&
|
||||||
|
type.isNotEmpty;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? get validationError {
|
||||||
|
if (code.isEmpty) return 'Printer code cannot be empty';
|
||||||
|
if (name.isEmpty) return 'Printer name cannot be empty';
|
||||||
|
if (address.isEmpty) return 'Printer address cannot be empty';
|
||||||
|
if (paper.isEmpty) return 'Paper size cannot be empty';
|
||||||
|
if (type.isEmpty) return 'Printer type cannot be empty';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
class ProductAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final ProductAnalyticData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
ProductAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProductAnalyticResponseModel.fromJson(Map<String, dynamic> json) =>
|
||||||
|
ProductAnalyticResponseModel.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory ProductAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProductAnalyticResponseModel(
|
||||||
|
success: map['success'] ?? false,
|
||||||
|
data:
|
||||||
|
map['data'] == null ? null : ProductAnalyticData.fromMap(map['data']),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProductAnalyticData {
|
||||||
|
final String organizationId;
|
||||||
|
final String outletId;
|
||||||
|
final DateTime dateFrom;
|
||||||
|
final DateTime dateTo;
|
||||||
|
final List<ProductAnalyticItem> data;
|
||||||
|
|
||||||
|
ProductAnalyticData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.outletId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProductAnalyticData.fromMap(Map<String, dynamic> map) =>
|
||||||
|
ProductAnalyticData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
dateFrom: DateTime.parse(map['date_from']),
|
||||||
|
dateTo: DateTime.parse(map['date_to']),
|
||||||
|
data: map['data'] == null
|
||||||
|
? []
|
||||||
|
: List<ProductAnalyticItem>.from(
|
||||||
|
map['data'].map((x) => ProductAnalyticItem.fromMap(x)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'date_from': dateFrom.toIso8601String(),
|
||||||
|
'date_to': dateTo.toIso8601String(),
|
||||||
|
'data': data.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProductAnalyticItem {
|
||||||
|
final String productId;
|
||||||
|
final String productName;
|
||||||
|
final String categoryId;
|
||||||
|
final String categoryName;
|
||||||
|
final int quantitySold;
|
||||||
|
final int revenue;
|
||||||
|
final double averagePrice;
|
||||||
|
final int orderCount;
|
||||||
|
|
||||||
|
ProductAnalyticItem({
|
||||||
|
required this.productId,
|
||||||
|
required this.productName,
|
||||||
|
required this.categoryId,
|
||||||
|
required this.categoryName,
|
||||||
|
required this.quantitySold,
|
||||||
|
required this.revenue,
|
||||||
|
required this.averagePrice,
|
||||||
|
required this.orderCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProductAnalyticItem.fromMap(Map<String, dynamic> map) =>
|
||||||
|
ProductAnalyticItem(
|
||||||
|
productId: map['product_id'],
|
||||||
|
productName: map['product_name'],
|
||||||
|
categoryId: map['category_id'],
|
||||||
|
categoryName: map['category_name'],
|
||||||
|
quantitySold: map['quantity_sold'],
|
||||||
|
revenue: map['revenue'],
|
||||||
|
averagePrice: (map['average_price'] as num).toDouble(),
|
||||||
|
orderCount: map['order_count'],
|
||||||
|
);
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() => {
|
||||||
|
'product_id': productId,
|
||||||
|
'product_name': productName,
|
||||||
|
'category_id': categoryId,
|
||||||
|
'category_name': categoryName,
|
||||||
|
'quantity_sold': quantitySold,
|
||||||
|
'revenue': revenue,
|
||||||
|
'average_price': averagePrice,
|
||||||
|
'order_count': orderCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProductInsights {
|
||||||
|
final List<ProductAnalyticItem> topProducts;
|
||||||
|
final ProductAnalyticItem? bestProduct;
|
||||||
|
final List<CategorySummary> categorySummary;
|
||||||
|
final int totalProducts;
|
||||||
|
final int totalRevenue;
|
||||||
|
final int totalQuantitySold;
|
||||||
|
|
||||||
|
ProductInsights({
|
||||||
|
required this.topProducts,
|
||||||
|
required this.bestProduct,
|
||||||
|
required this.categorySummary,
|
||||||
|
required this.totalProducts,
|
||||||
|
required this.totalRevenue,
|
||||||
|
required this.totalQuantitySold,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Category summary class
|
||||||
|
class CategorySummary {
|
||||||
|
final String categoryName;
|
||||||
|
int productCount;
|
||||||
|
int totalRevenue;
|
||||||
|
|
||||||
|
CategorySummary({
|
||||||
|
required this.categoryName,
|
||||||
|
required this.productCount,
|
||||||
|
required this.totalRevenue,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
|
int? parseInt(dynamic value) {
|
||||||
|
if (value == null) return null;
|
||||||
|
if (value is int) return value;
|
||||||
|
if (value is double) return value.toInt();
|
||||||
|
if (value is String) return int.tryParse(value);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
class ProductResponseModel {
|
class ProductResponseModel {
|
||||||
final bool? success;
|
final bool? success;
|
||||||
final ProductData? data;
|
final ProductData? data;
|
||||||
@@ -51,10 +59,10 @@ class ProductData {
|
|||||||
? []
|
? []
|
||||||
: List<Product>.from(
|
: List<Product>.from(
|
||||||
json["products"].map((x) => Product.fromMap(x))),
|
json["products"].map((x) => Product.fromMap(x))),
|
||||||
totalCount: json["total_count"],
|
totalCount: parseInt(json["total_count"]),
|
||||||
page: json["page"],
|
page: parseInt(json["page"]),
|
||||||
limit: json["limit"],
|
limit: parseInt(json["limit"]),
|
||||||
totalPages: json["total_pages"],
|
totalPages: parseInt(json["total_pages"]),
|
||||||
);
|
);
|
||||||
|
|
||||||
Map<String, dynamic> toMap() => {
|
Map<String, dynamic> toMap() => {
|
||||||
@@ -116,8 +124,8 @@ class Product {
|
|||||||
sku: json["sku"],
|
sku: json["sku"],
|
||||||
name: json["name"],
|
name: json["name"],
|
||||||
description: json["description"],
|
description: json["description"],
|
||||||
price: json["price"],
|
price: parseInt(json["price"]),
|
||||||
cost: json["cost"],
|
cost: parseInt(json["cost"]),
|
||||||
businessType: json["business_type"],
|
businessType: json["business_type"],
|
||||||
imageUrl: json["image_url"],
|
imageUrl: json["image_url"],
|
||||||
printerType: json["printer_type"],
|
printerType: json["printer_type"],
|
||||||
@@ -137,7 +145,7 @@ class Product {
|
|||||||
|
|
||||||
factory Product.fromOrderMap(Map<String, dynamic> json) => Product(
|
factory Product.fromOrderMap(Map<String, dynamic> json) => Product(
|
||||||
id: json["id_product"],
|
id: json["id_product"],
|
||||||
price: json["price"],
|
price: parseInt(json["price"]),
|
||||||
);
|
);
|
||||||
|
|
||||||
factory Product.fromLocalMap(Map<String, dynamic> json) => Product(
|
factory Product.fromLocalMap(Map<String, dynamic> json) => Product(
|
||||||
@@ -147,8 +155,8 @@ class Product {
|
|||||||
sku: json["sku"],
|
sku: json["sku"],
|
||||||
name: json["name"],
|
name: json["name"],
|
||||||
description: json["description"],
|
description: json["description"],
|
||||||
price: json["price"],
|
price: parseInt(json["price"]),
|
||||||
cost: json["cost"],
|
cost: parseInt(json["cost"]),
|
||||||
businessType: json["business_type"],
|
businessType: json["business_type"],
|
||||||
imageUrl: json["image_url"],
|
imageUrl: json["image_url"],
|
||||||
printerType: json["printer_type"],
|
printerType: json["printer_type"],
|
||||||
@@ -207,96 +215,6 @@ class Product {
|
|||||||
? []
|
? []
|
||||||
: List<dynamic>.from(variants!.map((x) => x.toMap())),
|
: List<dynamic>.from(variants!.map((x) => x.toMap())),
|
||||||
};
|
};
|
||||||
|
|
||||||
@override
|
|
||||||
bool operator ==(covariant Product other) {
|
|
||||||
if (identical(this, other)) return true;
|
|
||||||
|
|
||||||
return other.id == id &&
|
|
||||||
other.organizationId == organizationId &&
|
|
||||||
other.categoryId == categoryId &&
|
|
||||||
other.sku == sku &&
|
|
||||||
other.name == name &&
|
|
||||||
other.description == description &&
|
|
||||||
other.price == price &&
|
|
||||||
other.cost == cost &&
|
|
||||||
other.businessType == businessType &&
|
|
||||||
other.imageUrl == imageUrl &&
|
|
||||||
other.printerType == printerType &&
|
|
||||||
other.metadata == metadata &&
|
|
||||||
other.isActive == isActive &&
|
|
||||||
other.createdAt == createdAt &&
|
|
||||||
other.updatedAt == updatedAt &&
|
|
||||||
_listEquals(other.variants, variants);
|
|
||||||
}
|
|
||||||
|
|
||||||
bool _listEquals(List<ProductVariant>? a, List<ProductVariant>? b) {
|
|
||||||
if (a == null && b == null) return true;
|
|
||||||
if (a == null || b == null) return false;
|
|
||||||
if (a.length != b.length) return false;
|
|
||||||
for (int i = 0; i < a.length; i++) {
|
|
||||||
if (a[i] != b[i]) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
int get hashCode {
|
|
||||||
return id.hashCode ^
|
|
||||||
organizationId.hashCode ^
|
|
||||||
categoryId.hashCode ^
|
|
||||||
sku.hashCode ^
|
|
||||||
name.hashCode ^
|
|
||||||
description.hashCode ^
|
|
||||||
price.hashCode ^
|
|
||||||
cost.hashCode ^
|
|
||||||
businessType.hashCode ^
|
|
||||||
imageUrl.hashCode ^
|
|
||||||
printerType.hashCode ^
|
|
||||||
metadata.hashCode ^
|
|
||||||
isActive.hashCode ^
|
|
||||||
createdAt.hashCode ^
|
|
||||||
updatedAt.hashCode ^
|
|
||||||
variants.hashCode;
|
|
||||||
}
|
|
||||||
|
|
||||||
Product copyWith({
|
|
||||||
String? id,
|
|
||||||
String? organizationId,
|
|
||||||
String? categoryId,
|
|
||||||
String? sku,
|
|
||||||
String? name,
|
|
||||||
String? description,
|
|
||||||
int? price,
|
|
||||||
int? cost,
|
|
||||||
String? businessType,
|
|
||||||
String? imageUrl,
|
|
||||||
String? printerType,
|
|
||||||
Map<String, dynamic>? metadata,
|
|
||||||
bool? isActive,
|
|
||||||
DateTime? createdAt,
|
|
||||||
DateTime? updatedAt,
|
|
||||||
List<ProductVariant>? variants,
|
|
||||||
}) {
|
|
||||||
return Product(
|
|
||||||
id: id ?? this.id,
|
|
||||||
organizationId: organizationId ?? this.organizationId,
|
|
||||||
categoryId: categoryId ?? this.categoryId,
|
|
||||||
sku: sku ?? this.sku,
|
|
||||||
name: name ?? this.name,
|
|
||||||
description: description ?? this.description,
|
|
||||||
price: price ?? this.price,
|
|
||||||
cost: cost ?? this.cost,
|
|
||||||
businessType: businessType ?? this.businessType,
|
|
||||||
imageUrl: imageUrl ?? this.imageUrl,
|
|
||||||
printerType: printerType ?? this.printerType,
|
|
||||||
metadata: metadata ?? this.metadata,
|
|
||||||
isActive: isActive ?? this.isActive,
|
|
||||||
createdAt: createdAt ?? this.createdAt,
|
|
||||||
updatedAt: updatedAt ?? this.updatedAt,
|
|
||||||
variants: variants ?? this.variants,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class Category {
|
class Category {
|
||||||
@@ -341,28 +259,6 @@ class Category {
|
|||||||
"created_at": createdAt?.toIso8601String(),
|
"created_at": createdAt?.toIso8601String(),
|
||||||
"updated_at": updatedAt?.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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ProductVariant {
|
class ProductVariant {
|
||||||
@@ -390,8 +286,8 @@ class ProductVariant {
|
|||||||
id: json["id"],
|
id: json["id"],
|
||||||
productId: json["product_id"],
|
productId: json["product_id"],
|
||||||
name: json["name"],
|
name: json["name"],
|
||||||
priceModifier: json["price_modifier"],
|
priceModifier: parseInt(json["price_modifier"]),
|
||||||
cost: json["cost"],
|
cost: parseInt(json["cost"]),
|
||||||
metadata: json["metadata"] ?? {},
|
metadata: json["metadata"] ?? {},
|
||||||
createdAt: json["created_at"] == null
|
createdAt: json["created_at"] == null
|
||||||
? null
|
? null
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
class ProfitLossResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final ProfitLossData? data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
ProfitLossResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Dari JSON ke model (misal response dari API)
|
||||||
|
factory ProfitLossResponseModel.fromJson(Map<String, dynamic> json) {
|
||||||
|
return ProfitLossResponseModel(
|
||||||
|
success: json['success'],
|
||||||
|
data: json['data'] == null ? null : ProfitLossData.fromMap(json['data']),
|
||||||
|
errors: json['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dari model ke JSON (misal saat kirim ke API)
|
||||||
|
Map<String, dynamic> toJson() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alias dari fromJson, kadang dibutuhkan untuk naming yang konsisten
|
||||||
|
factory ProfitLossResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProfitLossResponseModel(
|
||||||
|
success: map['success'],
|
||||||
|
data: ProfitLossData.fromMap(map['data']),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alias dari toJson
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data?.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProfitLossData {
|
||||||
|
final String organizationId;
|
||||||
|
final String dateFrom;
|
||||||
|
final String dateTo;
|
||||||
|
final String groupBy;
|
||||||
|
final ProfitLossSummary summary;
|
||||||
|
final List<ProfitLossItem> data;
|
||||||
|
final List<ProfitLossProduct> productData;
|
||||||
|
|
||||||
|
ProfitLossData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.groupBy,
|
||||||
|
required this.summary,
|
||||||
|
required this.data,
|
||||||
|
required this.productData,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProfitLossData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProfitLossData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
dateFrom: map['date_from'],
|
||||||
|
dateTo: map['date_to'],
|
||||||
|
groupBy: map['group_by'],
|
||||||
|
summary: ProfitLossSummary.fromMap(map['summary']),
|
||||||
|
data: map['data'] == null
|
||||||
|
? []
|
||||||
|
: List<ProfitLossItem>.from(
|
||||||
|
map['data'].map((x) => ProfitLossItem.fromMap(x))),
|
||||||
|
productData: map['product_data'] == null
|
||||||
|
? []
|
||||||
|
: List<ProfitLossProduct>.from(
|
||||||
|
map['product_data'].map((x) => ProfitLossProduct.fromMap(x))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'date_from': dateFrom,
|
||||||
|
'date_to': dateTo,
|
||||||
|
'group_by': groupBy,
|
||||||
|
'summary': summary.toMap(),
|
||||||
|
'data': data.map((x) => x.toMap()).toList(),
|
||||||
|
'product_data': productData.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProfitLossSummary {
|
||||||
|
final int totalRevenue;
|
||||||
|
final num totalCost;
|
||||||
|
final num grossProfit;
|
||||||
|
final double grossProfitMargin;
|
||||||
|
final int totalTax;
|
||||||
|
final int totalDiscount;
|
||||||
|
final num netProfit;
|
||||||
|
final double netProfitMargin;
|
||||||
|
final int totalOrders;
|
||||||
|
final double averageProfit;
|
||||||
|
final double profitabilityRatio;
|
||||||
|
|
||||||
|
ProfitLossSummary({
|
||||||
|
required this.totalRevenue,
|
||||||
|
required this.totalCost,
|
||||||
|
required this.grossProfit,
|
||||||
|
required this.grossProfitMargin,
|
||||||
|
required this.totalTax,
|
||||||
|
required this.totalDiscount,
|
||||||
|
required this.netProfit,
|
||||||
|
required this.netProfitMargin,
|
||||||
|
required this.totalOrders,
|
||||||
|
required this.averageProfit,
|
||||||
|
required this.profitabilityRatio,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProfitLossSummary.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProfitLossSummary(
|
||||||
|
totalRevenue: map['total_revenue'],
|
||||||
|
totalCost: map['total_cost'],
|
||||||
|
grossProfit: map['gross_profit'],
|
||||||
|
grossProfitMargin: (map['gross_profit_margin'] as num).toDouble(),
|
||||||
|
totalTax: map['total_tax'],
|
||||||
|
totalDiscount: map['total_discount'],
|
||||||
|
netProfit: map['net_profit'],
|
||||||
|
netProfitMargin: (map['net_profit_margin'] as num).toDouble(),
|
||||||
|
totalOrders: map['total_orders'],
|
||||||
|
averageProfit: (map['average_profit'] as num).toDouble(),
|
||||||
|
profitabilityRatio: (map['profitability_ratio'] as num).toDouble(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'total_revenue': totalRevenue,
|
||||||
|
'total_cost': totalCost,
|
||||||
|
'gross_profit': grossProfit,
|
||||||
|
'gross_profit_margin': grossProfitMargin,
|
||||||
|
'total_tax': totalTax,
|
||||||
|
'total_discount': totalDiscount,
|
||||||
|
'net_profit': netProfit,
|
||||||
|
'net_profit_margin': netProfitMargin,
|
||||||
|
'total_orders': totalOrders,
|
||||||
|
'average_profit': averageProfit,
|
||||||
|
'profitability_ratio': profitabilityRatio,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProfitLossItem {
|
||||||
|
final String date;
|
||||||
|
final int revenue;
|
||||||
|
final num cost;
|
||||||
|
final num grossProfit;
|
||||||
|
final double grossProfitMargin;
|
||||||
|
final int tax;
|
||||||
|
final int discount;
|
||||||
|
final num netProfit;
|
||||||
|
final double netProfitMargin;
|
||||||
|
final int orders;
|
||||||
|
|
||||||
|
ProfitLossItem({
|
||||||
|
required this.date,
|
||||||
|
required this.revenue,
|
||||||
|
required this.cost,
|
||||||
|
required this.grossProfit,
|
||||||
|
required this.grossProfitMargin,
|
||||||
|
required this.tax,
|
||||||
|
required this.discount,
|
||||||
|
required this.netProfit,
|
||||||
|
required this.netProfitMargin,
|
||||||
|
required this.orders,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProfitLossItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProfitLossItem(
|
||||||
|
date: map['date'],
|
||||||
|
revenue: map['revenue'],
|
||||||
|
cost: map['cost'],
|
||||||
|
grossProfit: map['gross_profit'],
|
||||||
|
grossProfitMargin: (map['gross_profit_margin'] as num).toDouble(),
|
||||||
|
tax: map['tax'],
|
||||||
|
discount: map['discount'],
|
||||||
|
netProfit: map['net_profit'],
|
||||||
|
netProfitMargin: (map['net_profit_margin'] as num).toDouble(),
|
||||||
|
orders: map['orders'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'date': date,
|
||||||
|
'revenue': revenue,
|
||||||
|
'cost': cost,
|
||||||
|
'gross_profit': grossProfit,
|
||||||
|
'gross_profit_margin': grossProfitMargin,
|
||||||
|
'tax': tax,
|
||||||
|
'discount': discount,
|
||||||
|
'net_profit': netProfit,
|
||||||
|
'net_profit_margin': netProfitMargin,
|
||||||
|
'orders': orders,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProfitLossProduct {
|
||||||
|
final String productId;
|
||||||
|
final String productName;
|
||||||
|
final String categoryId;
|
||||||
|
final String categoryName;
|
||||||
|
final int quantitySold;
|
||||||
|
final int revenue;
|
||||||
|
final num cost;
|
||||||
|
final num grossProfit;
|
||||||
|
final double grossProfitMargin;
|
||||||
|
final int averagePrice;
|
||||||
|
final num averageCost;
|
||||||
|
final num profitPerUnit;
|
||||||
|
|
||||||
|
ProfitLossProduct({
|
||||||
|
required this.productId,
|
||||||
|
required this.productName,
|
||||||
|
required this.categoryId,
|
||||||
|
required this.categoryName,
|
||||||
|
required this.quantitySold,
|
||||||
|
required this.revenue,
|
||||||
|
required this.cost,
|
||||||
|
required this.grossProfit,
|
||||||
|
required this.grossProfitMargin,
|
||||||
|
required this.averagePrice,
|
||||||
|
required this.averageCost,
|
||||||
|
required this.profitPerUnit,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory ProfitLossProduct.fromMap(Map<String, dynamic> map) {
|
||||||
|
return ProfitLossProduct(
|
||||||
|
productId: map['product_id'],
|
||||||
|
productName: map['product_name'],
|
||||||
|
categoryId: map['category_id'],
|
||||||
|
categoryName: map['category_name'],
|
||||||
|
quantitySold: map['quantity_sold'],
|
||||||
|
revenue: map['revenue'],
|
||||||
|
cost: map['cost'],
|
||||||
|
grossProfit: map['gross_profit'],
|
||||||
|
grossProfitMargin: (map['gross_profit_margin'] as num).toDouble(),
|
||||||
|
averagePrice: (map['average_price'] as num).toInt(),
|
||||||
|
averageCost: (map['average_cost'] as num).toInt(),
|
||||||
|
profitPerUnit: map['profit_per_unit'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'product_id': productId,
|
||||||
|
'product_name': productName,
|
||||||
|
'category_id': categoryId,
|
||||||
|
'category_name': categoryName,
|
||||||
|
'quantity_sold': quantitySold,
|
||||||
|
'revenue': revenue,
|
||||||
|
'cost': cost,
|
||||||
|
'gross_profit': grossProfit,
|
||||||
|
'gross_profit_margin': grossProfitMargin,
|
||||||
|
'average_price': averagePrice,
|
||||||
|
'average_cost': averageCost,
|
||||||
|
'profit_per_unit': profitPerUnit,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
class SalesAnalyticResponseModel {
|
||||||
|
final bool success;
|
||||||
|
final SalesAnalyticData data;
|
||||||
|
final dynamic errors;
|
||||||
|
|
||||||
|
SalesAnalyticResponseModel({
|
||||||
|
required this.success,
|
||||||
|
required this.data,
|
||||||
|
this.errors,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SalesAnalyticResponseModel.fromJson(Map<String, dynamic> json) =>
|
||||||
|
SalesAnalyticResponseModel.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory SalesAnalyticResponseModel.fromMap(Map<String, dynamic> map) {
|
||||||
|
return SalesAnalyticResponseModel(
|
||||||
|
success: map['success'],
|
||||||
|
data: SalesAnalyticData.fromMap(map['data']),
|
||||||
|
errors: map['errors'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'success': success,
|
||||||
|
'data': data.toMap(),
|
||||||
|
'errors': errors,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SalesAnalyticData {
|
||||||
|
final String organizationId;
|
||||||
|
final String outletId;
|
||||||
|
final DateTime dateFrom;
|
||||||
|
final DateTime dateTo;
|
||||||
|
final String groupBy;
|
||||||
|
final SalesSummary summary;
|
||||||
|
final List<SalesAnalyticItem> data;
|
||||||
|
|
||||||
|
SalesAnalyticData({
|
||||||
|
required this.organizationId,
|
||||||
|
required this.outletId,
|
||||||
|
required this.dateFrom,
|
||||||
|
required this.dateTo,
|
||||||
|
required this.groupBy,
|
||||||
|
required this.summary,
|
||||||
|
required this.data,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SalesAnalyticData.fromJson(Map<String, dynamic> json) =>
|
||||||
|
SalesAnalyticData.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory SalesAnalyticData.fromMap(Map<String, dynamic> map) {
|
||||||
|
return SalesAnalyticData(
|
||||||
|
organizationId: map['organization_id'],
|
||||||
|
outletId: map['outlet_id'],
|
||||||
|
dateFrom: DateTime.parse(map['date_from']),
|
||||||
|
dateTo: DateTime.parse(map['date_to']),
|
||||||
|
groupBy: map['group_by'],
|
||||||
|
summary: SalesSummary.fromMap(map['summary']),
|
||||||
|
data: List<SalesAnalyticItem>.from(
|
||||||
|
map['data']?.map((x) => SalesAnalyticItem.fromMap(x)) ?? [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'organization_id': organizationId,
|
||||||
|
'outlet_id': outletId,
|
||||||
|
'date_from': dateFrom.toIso8601String(),
|
||||||
|
'date_to': dateTo.toIso8601String(),
|
||||||
|
'group_by': groupBy,
|
||||||
|
'summary': summary.toMap(),
|
||||||
|
'data': data.map((x) => x.toMap()).toList(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SalesSummary {
|
||||||
|
final int totalSales;
|
||||||
|
final int totalOrders;
|
||||||
|
final int totalItems;
|
||||||
|
final double averageOrderValue;
|
||||||
|
final int totalTax;
|
||||||
|
final int totalDiscount;
|
||||||
|
final int netSales;
|
||||||
|
|
||||||
|
SalesSummary({
|
||||||
|
required this.totalSales,
|
||||||
|
required this.totalOrders,
|
||||||
|
required this.totalItems,
|
||||||
|
required this.averageOrderValue,
|
||||||
|
required this.totalTax,
|
||||||
|
required this.totalDiscount,
|
||||||
|
required this.netSales,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SalesSummary.fromJson(Map<String, dynamic> json) =>
|
||||||
|
SalesSummary.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory SalesSummary.fromMap(Map<String, dynamic> map) {
|
||||||
|
return SalesSummary(
|
||||||
|
totalSales: map['total_sales'],
|
||||||
|
totalOrders: map['total_orders'],
|
||||||
|
totalItems: map['total_items'],
|
||||||
|
averageOrderValue: (map['average_order_value'] as num).toDouble(),
|
||||||
|
totalTax: map['total_tax'],
|
||||||
|
totalDiscount: map['total_discount'],
|
||||||
|
netSales: map['net_sales'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'total_sales': totalSales,
|
||||||
|
'total_orders': totalOrders,
|
||||||
|
'total_items': totalItems,
|
||||||
|
'average_order_value': averageOrderValue,
|
||||||
|
'total_tax': totalTax,
|
||||||
|
'total_discount': totalDiscount,
|
||||||
|
'net_sales': netSales,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SalesAnalyticItem {
|
||||||
|
final DateTime date;
|
||||||
|
final int sales;
|
||||||
|
final int orders;
|
||||||
|
final int items;
|
||||||
|
final int tax;
|
||||||
|
final int discount;
|
||||||
|
final int netSales;
|
||||||
|
|
||||||
|
SalesAnalyticItem({
|
||||||
|
required this.date,
|
||||||
|
required this.sales,
|
||||||
|
required this.orders,
|
||||||
|
required this.items,
|
||||||
|
required this.tax,
|
||||||
|
required this.discount,
|
||||||
|
required this.netSales,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SalesAnalyticItem.fromJson(Map<String, dynamic> json) =>
|
||||||
|
SalesAnalyticItem.fromMap(json);
|
||||||
|
|
||||||
|
Map<String, dynamic> toJson() => toMap();
|
||||||
|
|
||||||
|
factory SalesAnalyticItem.fromMap(Map<String, dynamic> map) {
|
||||||
|
return SalesAnalyticItem(
|
||||||
|
date: DateTime.parse(map['date']),
|
||||||
|
sales: map['sales'],
|
||||||
|
orders: map['orders'],
|
||||||
|
items: map['items'],
|
||||||
|
tax: map['tax'],
|
||||||
|
discount: map['discount'],
|
||||||
|
netSales: map['net_sales'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> toMap() {
|
||||||
|
return {
|
||||||
|
'date': date.toIso8601String(),
|
||||||
|
'sales': sales,
|
||||||
|
'orders': orders,
|
||||||
|
'items': items,
|
||||||
|
'tax': tax,
|
||||||
|
'discount': discount,
|
||||||
|
'net_sales': netSales,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SalesInsights {
|
||||||
|
final List<SalesAnalyticItem> originalData;
|
||||||
|
final List<SalesAnalyticItem> sortedDailyData;
|
||||||
|
final SalesAnalyticItem? highestRevenueDay;
|
||||||
|
final SalesSummary summary;
|
||||||
|
|
||||||
|
SalesInsights({
|
||||||
|
required this.originalData,
|
||||||
|
required this.sortedDailyData,
|
||||||
|
required this.highestRevenueDay,
|
||||||
|
required this.summary,
|
||||||
|
});
|
||||||
|
}
|
||||||