Compare commits
609 Commits
Vaibhav_Ta
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ec7dee0f1 | |||
| 48a96a703b | |||
| 8686d696f0 | |||
| 5d73fd6f4f | |||
| 1717cd5e2b | |||
| 717f0c92af | |||
| 633a75fe92 | |||
| 8fb32c7c8e | |||
| 3dfa6e5877 | |||
| 03e3e7b5db | |||
| cf85c17d75 | |||
| 66445b1e54 | |||
| 7c86d0c5c2 | |||
| 012d40cd57 | |||
| d4d678d98a | |||
| 6ed069d924 | |||
| c9e73771b0 | |||
| ed2eb014d8 | |||
| 3ad48016f3 | |||
| 37ce612fca | |||
| 7bef2e9d89 | |||
| 341d779499 | |||
| 65fbef3441 | |||
| 259f2aa928 | |||
| 84156167ea | |||
| 260b762724 | |||
| 951dd22ecc | |||
| 33ae5c0333 | |||
| 60bc53afef | |||
| 90a3a85753 | |||
| 71a48750bd | |||
| e2bee52820 | |||
| bb723b91e5 | |||
| 55122b5b13 | |||
| 2700864adf | |||
| 18fbfaa42d | |||
| 3e8bd1c41d | |||
| 4d2b05cdc2 | |||
| ddb1440211 | |||
| e4f55d82f7 | |||
| 081849f964 | |||
| a3b95b4d07 | |||
| ed4a558894 | |||
| e2897e4dde | |||
| 08777176df | |||
| 81f74004b8 | |||
| 3fa578f1b4 | |||
| 28c1c36e07 | |||
| 24bfccfdf6 | |||
| 5bed5bd2f4 | |||
| 41112a3eea | |||
| 9eb72a60ac | |||
| b401e98658 | |||
| 56602328ca | |||
| aece165c38 | |||
| 38626ebef0 | |||
| 6b58085434 | |||
| 5e1379b74b | |||
| c69e4280ef | |||
| 761cd1f7e8 | |||
| 516d6b0489 | |||
| e9075dcdf5 | |||
| 5c53a3f4be | |||
| 603e7ee7e5 | |||
| 2c98ac359c | |||
| fc78806af2 | |||
| cf7021a982 | |||
| efefb1c34b | |||
| 846ca64402 | |||
| 765f537cf9 | |||
| 87a7d19672 | |||
| d0b40a9822 | |||
| c44d10d35a | |||
| 02ef996753 | |||
| ec6a45ed43 | |||
| 92c739045c | |||
| 5dd09869ad | |||
| 8edd189479 | |||
| bbadcc4139 | |||
| d05e26bc87 | |||
| 49326e9929 | |||
| 0e575c393d | |||
| 804f0eba7b | |||
| 253aa55a80 | |||
| 17fc04f3ee | |||
| 474ecac53c | |||
| dc4ea7979c | |||
| 618ac6f27a | |||
| 2260382990 | |||
| 919310644d | |||
| 605617695e | |||
| 4d47ee3002 | |||
| 9dd66bd297 | |||
| f506bd1bfc | |||
| 39abfa2260 | |||
| ed88e0dfc9 | |||
| a910d37f22 | |||
| 2df4afcea7 | |||
| ceee12df33 | |||
| 58ed2676e3 | |||
| e1b6794e15 | |||
| 01f3cd24da | |||
| a8b31b3a95 | |||
| b9195c7fdd | |||
| be835bd2bd | |||
| 2d35addeeb | |||
| e3fe3c0d86 | |||
| b8aefc544f | |||
| 58c6a3f9af | |||
| 1f694381a1 | |||
| ba6d58fd0a | |||
| e9a43af350 | |||
| fdd2d51ed0 | |||
| cddc2990fb | |||
| 3974ae8a4c | |||
| 68ed97b64a | |||
| 793eeec7fa | |||
| 29af4e53a9 | |||
| 0b894a5091 | |||
| 8153d315b7 | |||
| bcfa29c0ed | |||
| 7f7d73c790 | |||
| 7fdeb103cf | |||
| 3bae3429c6 | |||
| 79b727aeb1 | |||
| 52da540271 | |||
| b2619eabe9 | |||
| b21c00faac | |||
| 083eece75b | |||
| bc62bc903d | |||
| a39af6519a | |||
| d530077444 | |||
| a2aef3355f | |||
| de657a4bce | |||
| 4c9fecdfcf | |||
| 52782098f8 | |||
| fc09673cd0 | |||
| bd6fc9f81b | |||
| 3660291482 | |||
| 81692a1930 | |||
| 5c386cb8ff | |||
| 0334a6b7a8 | |||
| 38528f1ade | |||
| 8619a9e43e | |||
| 5a3e9c2977 | |||
| 9f72f689c5 | |||
| c8a8d45c66 | |||
| 10e9f4a315 | |||
| 5ce37379cb | |||
| d5868d213a | |||
| 14ed2a8417 | |||
| 55fffbbe78 | |||
| 6f8f1f1856 | |||
| 548ecb33a6 | |||
| 01d7a2fd3b | |||
| 8dabac2eff | |||
| b476986807 | |||
| 2149fd6bc5 | |||
| 30405f7de4 | |||
| ffb02027cc | |||
| d3b8ce17b8 | |||
| e024cf4576 | |||
| 8edf3e89a5 | |||
| a61b9c50af | |||
| 509813ca2d | |||
| 61ca8f4250 | |||
| 36a3d586a0 | |||
| 899252f215 | |||
| 411e9afcc9 | |||
| f3f1f02282 | |||
| 477667c06a | |||
| 575fcc200c | |||
| 1b883ac524 | |||
| c631f8b092 | |||
| bdfc492e65 | |||
| 674a9c691b | |||
| 02c10d8115 | |||
| 456df30c8e | |||
| d229facfba | |||
| 4900ce87f7 | |||
| 3ebc9ab602 | |||
| 7e3d2ac2b9 | |||
| 7ee65115be | |||
| e1952d505b | |||
| 2b42393741 | |||
| ffd18a9e40 | |||
| 9ef1f57ca4 | |||
| 6e37e0dd04 | |||
| ee1e5014b4 | |||
| 31a27da85d | |||
| 2e750ad19c | |||
| 5f99827b23 | |||
| 70c8160dce | |||
| 831aacc202 | |||
| fe4a64e4d2 | |||
| 2d4d71b847 | |||
| 03b16e0ad9 | |||
| c0b4a74f87 | |||
| b0472503d1 | |||
| 9666d39d5e | |||
| befeef3c02 | |||
| 1f47a55d9c | |||
| 3bc7b5092f | |||
| 2255ae29fa | |||
| 214816ac0f | |||
| c4bb8331c9 | |||
| 00aa53d496 | |||
| 818e0a144a | |||
| 0b60276e03 | |||
| 68f17214fd | |||
| cdba511d43 | |||
| 6c14fc1507 | |||
| feb12862fa | |||
| 1de5e7fae7 | |||
| 7b6520597e | |||
| 11393922e2 | |||
| cb00911983 | |||
| 0414a109be | |||
| 340d0b8a1e | |||
| 8fb65d31e2 | |||
| 7f756f3d4c | |||
| d2c7f92a02 | |||
| 6b56351a49 | |||
| 5db53c29df | |||
| be2f97cc0e | |||
| 44bbbf9bfb | |||
| f62b7d924b | |||
| ee9c94dc86 | |||
| 3e99fc67a3 | |||
| cffa4456b9 | |||
| af5bfcaa59 | |||
| 7f0c4d075d | |||
| fe950c5b07 | |||
| 034de5a601 | |||
| 77a6d50571 | |||
| 077dbf35ee | |||
| f232ab42b0 | |||
| 3543770654 | |||
| 1dc68033df | |||
| b1f5fb8d78 | |||
| 8d688f2575 | |||
| 502bb1e2d9 | |||
| a88d085001 | |||
| fd57686c8a | |||
| fd861b3adb | |||
| 1c253df5f9 | |||
| 92f7fec083 | |||
| 1070f04d1a | |||
| eb46194679 | |||
| 910bb5e6b4 | |||
| 80d7ef96cb | |||
| 99166801da | |||
| 87520d7664 | |||
| e8d4931016 | |||
| f0d42edcc1 | |||
| 82c2cc3c58 | |||
| ac7a75c92f | |||
| b1437db9e0 | |||
| 4d3a42e851 | |||
| c78c14e409 | |||
| ebc8996f71 | |||
| 3c95583a23 | |||
| 91174dd960 | |||
| 9e52e50cc9 | |||
| 177f8c32e2 | |||
| d15d9f22df | |||
| 3c89b4ddbb | |||
| d208648350 | |||
| 16a2e1e53a | |||
| 15b6dbd374 | |||
| 7007a86ac7 | |||
| 04da062f4f | |||
| 97b45ebd91 | |||
| a245670e0a | |||
| 038b33e3b8 | |||
| 83218166ba | |||
| 26611d3650 | |||
| 7fb5a5217a | |||
| 706881d08d | |||
| e8acfe10d9 | |||
| 16e2f5a4f3 | |||
| cd92d4d309 | |||
| 5dc2db0a8b | |||
| bb5fdb27b2 | |||
| acb203848e | |||
| e6238ca5b0 | |||
| d5a8d08e63 | |||
| 041b62ca2f | |||
| d1d48b1a74 | |||
| 7e75431feb | |||
| 45bc492683 | |||
| 26675388dd | |||
| d02211d389 | |||
| 5086b3be98 | |||
| 539e94fc99 | |||
| dbd4a42b7a | |||
| 38ae9e3571 | |||
| 7f924ee533 | |||
| d6587931fa | |||
| 8ad9690d89 | |||
| b286ab854a | |||
| 8576448a32 | |||
| 075167e285 | |||
| fd7c338c05 | |||
| b5d8d41e42 | |||
| 781a8dabaf | |||
| 98612db7b5 | |||
| 7c21324b42 | |||
| 1900e944e5 | |||
| 53fefbba50 | |||
| 9012218a44 | |||
| fb26ba0757 | |||
| aa5ae29284 | |||
| 83d9d0689a | |||
| 85d3dedbef | |||
| 1d9c416f68 | |||
| 7d211e24f8 | |||
| fc081c779e | |||
| 4cb60138c0 | |||
| 68cfdf54d6 | |||
| 83a8abbb87 | |||
| 17c7b9f10d | |||
| efb5564fcb | |||
| 637426aea4 | |||
| 8ed67dcdf1 | |||
| 6863769b8a | |||
| 8d3c900262 | |||
| 9362945d60 | |||
| b5e9c7b6a3 | |||
| 04cbdab277 | |||
| ae7ce851ee | |||
| 8c99ba287f | |||
| bbe7f4a215 | |||
| 85d776b60b | |||
| 4836dd994c | |||
| 544eb4dc79 | |||
| 957bae526f | |||
| a1cd212e74 | |||
| 47666c7897 | |||
| e6f028d129 | |||
| 1fafe77211 | |||
| 25b20fedda | |||
| 7d5d2b5bf4 | |||
| ef1403bec9 | |||
| 3b497fecaf | |||
| 8fb725a5cf | |||
| 2517f2360e | |||
| d2712b8288 | |||
| fd7f108a20 | |||
| 61acbb019b | |||
| be908a5251 | |||
| 5c923bb48b | |||
| bd6f175ca7 | |||
| 229531c5bf | |||
| 20365697a7 | |||
| 0cccdc6b05 | |||
| 6d70afc779 | |||
| a02887845b | |||
| 99bd26942c | |||
| bf84ef4786 | |||
| 4d11a2ccf0 | |||
| e12e5ab13b | |||
| 2133dedfae | |||
| 334023bf1b | |||
| 40a4a77af5 | |||
| c27b226b58 | |||
| a0f3475c5e | |||
| 3aab006bea | |||
| f5d4ab8415 | |||
| d62f8aa9ef | |||
| 80d5fc5f21 | |||
| a154872649 | |||
| 91184b48bb | |||
| c69e0d5221 | |||
| ac6b6e6173 | |||
| 35a0228cbe | |||
| 5977fef261 | |||
| 311002f3ba | |||
| 8783e7a503 | |||
| 8688e84779 | |||
| 911cddf97c | |||
| 1af3ae2aa6 | |||
| 3ba3129b18 | |||
| 98d2dd4c46 | |||
| cc0bb7aafc | |||
| 6187d63ccc | |||
| 83804cde3f | |||
| 1e48c686b2 | |||
| f24bff4fad | |||
| fa767ea201 | |||
| c9882879ff | |||
| a6da579f07 | |||
| 9feb9d1b4b | |||
| 2013447904 | |||
| 2fb3c36ba4 | |||
| 0e177e5a1f | |||
| 7175ade940 | |||
| 10e4a6e514 | |||
| 77dcd9af8e | |||
| 858fe7435d | |||
| 93f9a6e738 | |||
| 092fe21252 | |||
| 1d17a8e109 | |||
| 7ec8b1e7bc | |||
| d205cc2014 | |||
| a5058cd0bc | |||
| 754f919cdc | |||
| b0c9a2c45f | |||
| 3195fdd4a0 | |||
| 06fc8a4c61 | |||
| 63e5caae24 | |||
| aa76ec60cb | |||
| 0401b41b3c | |||
| 0acd619d78 | |||
| f1220cc018 | |||
| 84811635d0 | |||
| 7dbc9138c6 | |||
| f245f9accf | |||
| 0150400092 | |||
| bba44d4d39 | |||
| 7dd47ce460 | |||
| d799093537 | |||
| 9d9afe37b8 | |||
| fe66f35be7 | |||
| 70443d8e24 | |||
| 0f0eb51c15 | |||
| 2518b65cb7 | |||
| 5f66c4c647 | |||
| d0cbfa987d | |||
| 0f14fda83a | |||
| 7ce07c9b47 | |||
| f5eed0a0b9 | |||
| 6d29d444fa | |||
| 797df80890 | |||
| 3427c5bd26 | |||
| 31966f4bc5 | |||
| 29f759ca9d | |||
| adf5e1437e | |||
| 9d49f2a92d | |||
| cef3bd8a1e | |||
| 2b34635a75 | |||
| 154cfdb471 | |||
| d28332b55d | |||
| 98836f8157 | |||
| ddbc1ec1e5 | |||
| 5bc811f91f | |||
| f4b905cd42 | |||
| e5b3616245 | |||
| 9124b815ef | |||
| a83954c5c4 | |||
| 586d18565f | |||
| e0ed35a671 | |||
| debc12bc1b | |||
| d90673523a | |||
| d7b62323d6 | |||
| ff01c05a73 | |||
| a7bb24ee29 | |||
| af83d66390 | |||
| b40d371d43 | |||
| 982c81f849 | |||
| 9e4c0378c6 | |||
| 069fa29aa7 | |||
| 25a1331878 | |||
| 380bdf870e | |||
| 008d35d576 | |||
| 69e64ec789 | |||
| 943c7c7b50 | |||
| 0e1b6e2a8c | |||
| d0f42da30f | |||
| 93cdaab2c2 | |||
| 4a01371fad | |||
| f7352eb3c3 | |||
| ee469f694e | |||
| 6c0e73d870 | |||
| 30318cd294 | |||
| 8c5035d679 | |||
| 60060eaa5e | |||
| 02daa1e689 | |||
| 4908db35ad | |||
| 990bf737dc | |||
|
|
072bc34cde | ||
|
|
befbead7ff | ||
|
|
85966b5ebf | ||
|
|
b0c97a850c | ||
| e96aeeb14b | |||
|
|
9f7d6c92c5 | ||
|
|
0335b0d3ab | ||
|
|
e624fb00a0 | ||
|
|
219815dd27 | ||
|
|
9c28dc05dd | ||
|
|
f9ab336eb0 | ||
|
|
07bf9a93aa | ||
|
|
395444e8fc | ||
|
|
574e7df447 | ||
|
|
33d267f18e | ||
|
|
2926bb7216 | ||
| 059e7c6c8b | |||
|
|
8a729f23fe | ||
|
|
71f9e54d58 | ||
|
|
1e1bcc3aa4 | ||
|
|
5b5030ec36 | ||
|
|
ffba37b767 | ||
|
|
efd5021ab1 | ||
|
|
91e2bb7bc8 | ||
|
|
f4135a77d8 | ||
|
|
aac65104ab | ||
|
|
e059ee71f3 | ||
|
|
a9067bd407 | ||
|
|
b3b68b6258 | ||
|
|
6907d176da | ||
|
|
ae868bb0f6 | ||
|
|
df0dd5d560 | ||
|
|
1ad880a021 | ||
|
|
fb28439d69 | ||
|
|
2fef2e508e | ||
|
|
a8c890a60d | ||
|
|
77e27ff98e | ||
|
|
445cd75e03 | ||
|
|
5fb18a13d2 | ||
|
|
43aeec4c6f | ||
|
|
5e8158a410 | ||
|
|
45ce53539c | ||
|
|
7a2798401a | ||
|
|
56b493c909 | ||
|
|
087c77bbd2 | ||
|
|
606c5e5971 | ||
|
|
e7940941ed | ||
|
|
62c49b5429 | ||
|
|
b187f1843a | ||
|
|
eabd988b32 | ||
|
|
becdec1a79 | ||
|
|
549d8cce3c | ||
|
|
be71544ae4 | ||
|
|
83ad10ffb4 | ||
| a0f1602f4e | |||
| 8f87161d74 | |||
| 2c79d3eec8 | |||
| ec6c24464e | |||
| e6d05e247e | |||
| ef60677c98 | |||
| e71e4d633a | |||
| 99a9b47a19 | |||
| 67d78f02b7 | |||
| 95c625a55b | |||
| f7fcad2992 | |||
| 099edd3884 | |||
| f1764eed81 | |||
| 0317954b02 | |||
| 6e11fc8c52 | |||
| 6c3370437d | |||
| 6cdf35374d | |||
| ca8bc26ab5 | |||
| f7671bc5d3 | |||
| 405916bb48 | |||
| 97c873167f | |||
| ef6521faa2 | |||
| 660bd3cdf1 | |||
| 4ba30145ef | |||
| d1305e1dba | |||
| f834422c4e | |||
| 44d72b73ac | |||
| c215c4c943 | |||
| 3ede53713d | |||
| 5148b41579 | |||
| 58a66546e4 | |||
| 206c84b3a1 | |||
| 93a2350858 | |||
| 6f2e257f0d | |||
| 5275ad940b | |||
| d765b96df4 | |||
| 0ad8847b94 | |||
| 658f3f26e0 | |||
| 602d8a8dc9 | |||
| 59e6634023 | |||
| a97fb1f541 | |||
| c7600e8e26 | |||
| 8e47d28005 | |||
| 916cfa3af4 | |||
| 5cf0202cc1 | |||
| 4022197b7f | |||
| 11d9f107ad | |||
| daf132c3b5 | |||
| 1f784d96f4 | |||
| 3a449441fa | |||
| b38d987eac | |||
| 56efbe8869 | |||
| b81ac33b2d | |||
| 936faae07d | |||
| 313350e1a5 | |||
| 6a36064af7 | |||
| 52afa7735e | |||
| 8c2d258848 | |||
| 18987aa97a | |||
| 040a8f0a2e | |||
| a2a7eb84b0 | |||
| 2ccd237329 | |||
| c253c14481 | |||
| 25dfcf3e08 | |||
| a89346fc8a | |||
| 516a779626 | |||
| 0b8a5364ae | |||
| 905b3e32c5 | |||
| 3926e762e5 | |||
| deff7aea7d | |||
| a0761d255f | |||
| d7680df3a9 | |||
| 4862e53967 | |||
| d99221e800 | |||
| cd29a478a2 |
@ -3,42 +3,84 @@ plugins {
|
||||
id "kotlin-android"
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id "dev.flutter.flutter-gradle-plugin"
|
||||
id("com.google.gms.google-services")
|
||||
}
|
||||
|
||||
// Load keystore properties from key.properties file
|
||||
def keystoreProperties = new Properties()
|
||||
def keystorePropertiesFile = rootProject.file('key.properties')
|
||||
if (keystorePropertiesFile.exists()) {
|
||||
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.marco"
|
||||
// Define the namespace for your Android application
|
||||
namespace = "com.marcoonfieldwork.aiot"
|
||||
// Set the compile SDK version based on Flutter's configuration
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
// Set the NDK version based on Flutter's configuration
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
// Configure Java compatibility options
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||
targetCompatibility = JavaVersion.VERSION_1_8
|
||||
// ✅ Enable core library desugaring for Java 8+ APIs
|
||||
coreLibraryDesugaringEnabled true
|
||||
}
|
||||
|
||||
// Configure Kotlin options for JVM target
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_1_8
|
||||
}
|
||||
|
||||
// Default configuration for your application
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.example.marco"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = flutter.minSdkVersion
|
||||
// Specify your unique Application ID. This identifies your app on Google Play.
|
||||
applicationId = "com.marcoonfieldwork.aiot"
|
||||
// Set minimum and target SDK versions based on Flutter's configuration
|
||||
minSdk = 23
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
// Set version code and name based on Flutter's configuration (from pubspec.yaml)
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
// Define signing configurations for different build types
|
||||
signingConfigs {
|
||||
release {
|
||||
// Reference the key alias from key.properties
|
||||
keyAlias keystoreProperties['keyAlias']
|
||||
// Reference the key password from key.properties
|
||||
keyPassword keystoreProperties['keyPassword']
|
||||
// Reference the keystore file path from key.properties
|
||||
storeFile file(keystoreProperties['storeFile'])
|
||||
// Reference the keystore password from key.properties
|
||||
storePassword keystoreProperties['storePassword']
|
||||
}
|
||||
}
|
||||
|
||||
// Define different build types (e.g., debug, release)
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.debug
|
||||
// Apply the 'release' signing configuration defined above to the release build
|
||||
signingConfig signingConfigs.release
|
||||
// Enable code minification to reduce app size
|
||||
minifyEnabled true
|
||||
// Enable resource shrinking to remove unused resources
|
||||
shrinkResources true
|
||||
// Other release specific configurations can be added here, e.g., ProGuard rules
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Configure Flutter specific settings, pointing to the root of your Flutter project
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
|
||||
// ✅ Add required dependencies for desugaring
|
||||
dependencies {
|
||||
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.4'
|
||||
}
|
||||
|
||||
|
||||
29
android/app/google-services.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "626581282477",
|
||||
"project_id": "mtest-a0635",
|
||||
"storage_bucket": "mtest-a0635.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:626581282477:android:8d3cf5009ff92ef67ff024",
|
||||
"android_client_info": {
|
||||
"package_name": "com.marcoonfieldwork.aiot"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyCBkDQRpbSdR0bo6pO4Bm0ZIdXkdaE3z-A"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@ -6,5 +6,6 @@
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
|
||||
</manifest>
|
||||
|
||||
@ -1,9 +1,14 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.READ_CONTACTS"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
|
||||
<application
|
||||
android:label="marco"
|
||||
android:label="On Field Work"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
<activity
|
||||
@ -33,6 +38,9 @@
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
<meta-data
|
||||
android:name="com.google.firebase.messaging.default_notification_channel_id"
|
||||
android:value="high_importance_channel"/>
|
||||
</application>
|
||||
<!-- Required to query activities that can process text, see:
|
||||
https://developer.android.com/training/package-visibility and
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package com.example.marco
|
||||
package com.marcoonfieldwork.aiot
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
|
||||
|
||||
@ -1,3 +1,3 @@
|
||||
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
android.enableJetifier=false
|
||||
|
||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-all.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-all.zip
|
||||
|
||||
@ -18,8 +18,9 @@ pluginManagement {
|
||||
|
||||
plugins {
|
||||
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
|
||||
id "com.android.application" version "8.2.1" apply false
|
||||
id "org.jetbrains.kotlin.android" version "1.8.22" apply false
|
||||
id "com.android.application" version "8.6.0" apply false
|
||||
id "org.jetbrains.kotlin.android" version "2.2.21" apply false
|
||||
id("com.google.gms.google-services") version "4.4.2" apply false
|
||||
}
|
||||
|
||||
include ":app"
|
||||
|
||||
@ -1,192 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"first_name": "James Carter",
|
||||
"email": "james.carter@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "How is your day going?",
|
||||
"send_at": "2024-11-15T10:05:10Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Reminder about the project meeting tomorrow",
|
||||
"send_at": "2023-06-20T14:23:11Z",
|
||||
"from_me": true
|
||||
},
|
||||
{
|
||||
"message": "Can we meet today for a quick chat?",
|
||||
"send_at": "2023-04-19T17:30:08Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Yes, all is good. See you tomorrow at 2 PM for the meeting",
|
||||
"send_at": "2023-03-22T11:09:45Z",
|
||||
"from_me": false
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"first_name": "Sophia Lee",
|
||||
"email": "sophia.lee@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Are we meeting today for the weekly catch-up?",
|
||||
"send_at": "2023-09-10T08:45:36Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Please review these updated documents",
|
||||
"send_at": "2023-11-17T11:22:33Z",
|
||||
"from_me": true
|
||||
},
|
||||
{
|
||||
"message": "Good morning, How are you? When is our next meeting?",
|
||||
"send_at": "2023-05-13T09:25:18Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"first_name": "Ethan Scott",
|
||||
"email": "ethan.scott@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Are you available for a quick call? Need to discuss something",
|
||||
"send_at": "2023-12-05T07:40:21Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Let's meet today, shall we?",
|
||||
"send_at": "2023-03-17T14:00:12Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"first_name": "Olivia Brown",
|
||||
"email": "olivia.brown@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Let's meet today for a team discussion",
|
||||
"send_at": "2023-05-30T11:55:10Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Hope you're having a great day. Let's catch up soon",
|
||||
"send_at": "2023-07-12T12:36:44Z",
|
||||
"from_me": true
|
||||
},
|
||||
{
|
||||
"message": "I need to go buy some groceries this afternoon, I'll be a bit late.",
|
||||
"send_at": "2024-01-10T13:20:45Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"first_name": "Charlotte Miller",
|
||||
"email": "charlotte.miller@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Are you available for a quick chat?",
|
||||
"send_at": "2023-11-11T16:50:09Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "I just sent you the updated contract documents for review.",
|
||||
"send_at": "2023-10-04T18:22:56Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"first_name": "Jackson Harris",
|
||||
"email": "jackson.harris@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "How's everything going? Any updates on the project?",
|
||||
"send_at": "2023-08-25T11:10:30Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Sending over the latest draft for your review",
|
||||
"send_at": "2023-12-02T10:14:50Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"first_name": "Aiden Cooper",
|
||||
"email": "aiden.cooper@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Do you have time today for a discussion?",
|
||||
"send_at": "2023-10-05T09:18:22Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "The new update is ready for deployment, please check it.",
|
||||
"send_at": "2024-01-25T11:29:13Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"first_name": "Lily King",
|
||||
"email": "lily.king@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Would you be able to meet today for a catch-up?",
|
||||
"send_at": "2023-06-18T13:12:09Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "I have finished reviewing the files, please take a look.",
|
||||
"send_at": "2023-12-18T16:47:02Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"first_name": "Max Taylor",
|
||||
"email": "max.taylor@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Please check the attached file and confirm if everything is okay.",
|
||||
"send_at": "2023-09-29T14:10:33Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "Sending over the revised schedule for the next phase.",
|
||||
"send_at": "2024-01-02T17:12:11Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"first_name": "Avery Clark",
|
||||
"email": "avery.clark@example.com",
|
||||
"messages": [
|
||||
{
|
||||
"message": "Are we ready for the meeting today?",
|
||||
"send_at": "2023-08-22T12:43:50Z",
|
||||
"from_me": false
|
||||
},
|
||||
{
|
||||
"message": "I updated the timeline. Let me know if you have any questions.",
|
||||
"send_at": "2023-12-15T10:55:29Z",
|
||||
"from_me": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@ -1,82 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"asset": "Alaska Air Group, Inc.",
|
||||
"date": "2024-06-17T12:59:41Z",
|
||||
"ip_address": "113.9.18.110",
|
||||
"status": "Unpaid",
|
||||
"amount": 7061
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"asset": "T2 Biosystems, Inc.",
|
||||
"date": "2024-09-09T00:20:08Z",
|
||||
"ip_address": "45.51.68.143",
|
||||
"status": "Unpaid",
|
||||
"amount": 5677
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"asset": "North American Energy Partners, Inc.",
|
||||
"date": "2024-07-17T10:46:42Z",
|
||||
"ip_address": "221.131.122.193",
|
||||
"status": "Unpaid",
|
||||
"amount": 5420
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"asset": "Finjan Holdings, Inc.",
|
||||
"date": "2024-01-20T20:10:26Z",
|
||||
"ip_address": "50.242.43.22",
|
||||
"status": "Success",
|
||||
"amount": 6433
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"asset": "Omega Healthcare Investors, Inc.",
|
||||
"date": "2024-11-14T23:08:09Z",
|
||||
"ip_address": "109.125.5.131",
|
||||
"status": "Success",
|
||||
"amount": 6317
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"asset": "MediciNova, Inc.",
|
||||
"date": "2024-01-12T18:20:33Z",
|
||||
"ip_address": "54.103.156.190",
|
||||
"status": "Unpaid",
|
||||
"amount": 7952
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"asset": "PowerShares LadderRite 0-5 Year Corporate Bond Portfolio",
|
||||
"date": "2024-04-26T00:44:42Z",
|
||||
"ip_address": "169.190.183.205",
|
||||
"status": "Success",
|
||||
"amount": 6294
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"asset": "VelocityShares Daily 2x VIX Medium-Term ETN",
|
||||
"date": "2024-02-01T12:47:59Z",
|
||||
"ip_address": "144.189.211.137",
|
||||
"status": "Success",
|
||||
"amount": 4419
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"asset": "Liberty TripAdvisor Holdings, Inc.",
|
||||
"date": "2023-12-29T14:49:59Z",
|
||||
"ip_address": "166.41.221.149",
|
||||
"status": "Unpaid",
|
||||
"amount": 4195
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"asset": "Scorpio Tankers Inc.",
|
||||
"date": "2023-12-02T11:36:44Z",
|
||||
"ip_address": "27.151.0.226",
|
||||
"status": "Success",
|
||||
"amount": 8395
|
||||
}
|
||||
]
|
||||
@ -1,202 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"first_name": "Sabina",
|
||||
"last_name": "Brothwood",
|
||||
"project_name": "Wunsch, DuBuque and Green",
|
||||
"phone_number": "541-568-8047",
|
||||
"balance": "31907",
|
||||
"order_count": 7,
|
||||
"last_order": "2022-10-07T03:43:16Z"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"first_name": "Felic",
|
||||
"last_name": "Parlor",
|
||||
"project_name": "Dare LLC",
|
||||
"phone_number": "866-349-3385",
|
||||
"balance": "02260",
|
||||
"order_count": 26,
|
||||
"last_order": "2023-07-12T07:52:19Z"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"first_name": "Marnie",
|
||||
"last_name": "Kofax",
|
||||
"project_name": "Von LLC",
|
||||
"phone_number": "821-779-3766",
|
||||
"balance": "663",
|
||||
"order_count": 21,
|
||||
"last_order": "2022-10-14T21:19:33Z"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"first_name": "Tine",
|
||||
"last_name": "Meron",
|
||||
"project_name": "Stracke Inc",
|
||||
"phone_number": "901-149-2915",
|
||||
"balance": "84",
|
||||
"order_count": 8,
|
||||
"last_order": "2023-04-06T12:36:09Z"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"first_name": "Shanon",
|
||||
"last_name": "Ivashchenko",
|
||||
"project_name": "Satterfield, Schultz and Jones",
|
||||
"phone_number": "452-728-1072",
|
||||
"balance": "0878",
|
||||
"order_count": 34,
|
||||
"last_order": "2023-04-03T15:07:21Z"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"first_name": "Guthrey",
|
||||
"last_name": "Crossland",
|
||||
"project_name": "Medhurst and Sons",
|
||||
"phone_number": "212-991-7314",
|
||||
"balance": "0291",
|
||||
"order_count": 7,
|
||||
"last_order": "2022-12-03T04:24:53Z"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"first_name": "Florie",
|
||||
"last_name": "Chestnutt",
|
||||
"project_name": "Beer-Kunze",
|
||||
"phone_number": "935-525-9749",
|
||||
"balance": "07984",
|
||||
"order_count": 69,
|
||||
"last_order": "2023-01-14T10:42:28Z"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"first_name": "Wittie",
|
||||
"last_name": "Damsell",
|
||||
"project_name": "Daniel, Legros and Roberts",
|
||||
"phone_number": "632-787-4799",
|
||||
"balance": "22844",
|
||||
"order_count": 41,
|
||||
"last_order": "2023-01-18T09:38:50Z"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"first_name": "Aimee",
|
||||
"last_name": "Dibdall",
|
||||
"project_name": "Schuster LLC",
|
||||
"phone_number": "404-339-9261",
|
||||
"balance": "460",
|
||||
"order_count": 41,
|
||||
"last_order": "2023-04-15T03:08:51Z"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"first_name": "Inna",
|
||||
"last_name": "Juggins",
|
||||
"project_name": "Johnson Group",
|
||||
"phone_number": "769-573-9516",
|
||||
"balance": "77",
|
||||
"order_count": 18,
|
||||
"last_order": "2022-09-13T05:14:51Z"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"first_name": "Cathyleen",
|
||||
"last_name": "Went",
|
||||
"project_name": "DuBuque LLC",
|
||||
"phone_number": "558-736-4450",
|
||||
"balance": "24",
|
||||
"order_count": 98,
|
||||
"last_order": "2023-07-05T05:26:12Z"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"first_name": "Kora",
|
||||
"last_name": "Dowderswell",
|
||||
"project_name": "Harber, Daugherty and West",
|
||||
"phone_number": "721-147-2917",
|
||||
"balance": "32",
|
||||
"order_count": 5,
|
||||
"last_order": "2022-10-22T07:47:42Z"
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"first_name": "Loni",
|
||||
"last_name": "Armin",
|
||||
"project_name": "Fadel-Kerluke",
|
||||
"phone_number": "251-582-9867",
|
||||
"balance": "2122",
|
||||
"order_count": 4,
|
||||
"last_order": "2023-01-26T19:56:37Z"
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"first_name": "Kalle",
|
||||
"last_name": "Spybey",
|
||||
"project_name": "Kshlerin, Torp and Koelpin",
|
||||
"phone_number": "245-661-6328",
|
||||
"balance": "61034",
|
||||
"order_count": 70,
|
||||
"last_order": "2022-12-29T15:38:20Z"
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"first_name": "Verena",
|
||||
"last_name": "Skerme",
|
||||
"project_name": "Dach, Abshire and Crooks",
|
||||
"phone_number": "227-694-0272",
|
||||
"balance": "68921",
|
||||
"order_count": 3,
|
||||
"last_order": "2022-11-29T23:02:11Z"
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"first_name": "Lisle",
|
||||
"last_name": "McGowan",
|
||||
"project_name": "White, Murphy and Sawayn",
|
||||
"phone_number": "196-817-6277",
|
||||
"balance": "7250",
|
||||
"order_count": 34,
|
||||
"last_order": "2023-06-14T11:10:56Z"
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"first_name": "Bryce",
|
||||
"last_name": "Pires",
|
||||
"project_name": "Crooks Group",
|
||||
"phone_number": "424-217-0372",
|
||||
"balance": "549",
|
||||
"order_count": 50,
|
||||
"last_order": "2023-01-08T17:58:09Z"
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"first_name": "Ibrahim",
|
||||
"last_name": "Battram",
|
||||
"project_name": "Schmidt, Feil and Schaden",
|
||||
"phone_number": "836-473-5900",
|
||||
"balance": "3",
|
||||
"order_count": 86,
|
||||
"last_order": "2023-08-05T01:46:22Z"
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"first_name": "Josepha",
|
||||
"last_name": "Grishkov",
|
||||
"project_name": "Welch-Wisozk",
|
||||
"phone_number": "928-393-5306",
|
||||
"balance": "528",
|
||||
"order_count": 38,
|
||||
"last_order": "2023-08-18T19:01:25Z"
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"first_name": "Ellis",
|
||||
"last_name": "Barfoot",
|
||||
"project_name": "Davis, Ondricka and Schaefer",
|
||||
"phone_number": "169-236-9311",
|
||||
"balance": "169",
|
||||
"order_count": 11,
|
||||
"last_order": "2023-02-21T16:29:59Z"
|
||||
}
|
||||
]
|
||||
@ -1,72 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"image": "assets/dummy/dummy_1.jpg",
|
||||
"name": "Meir O'Leahy",
|
||||
"user_name": "moleahy0",
|
||||
"contact_number": "817-666-8080"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"image": "assets/dummy/dummy_2.jpg",
|
||||
"name": "Ernie Ayling",
|
||||
"user_name": "eayling1",
|
||||
"contact_number": "890-910-3243"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"image": "assets/dummy/dummy_3.jpg",
|
||||
"name": "Mead Ezzle",
|
||||
"user_name": "mezzle2",
|
||||
"contact_number": "293-162-4468"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"image": "assets/dummy/dummy_4.jpg",
|
||||
"name": "Esta Norewood",
|
||||
"user_name": "enorewood3",
|
||||
"contact_number": "532-164-0604"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"image": "assets/dummy/dummy_5.jpg",
|
||||
"name": "Bartram Cottell",
|
||||
"user_name": "bcottell4",
|
||||
"contact_number": "940-143-2842"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"image": "assets/dummy/dummy_1.jpg",
|
||||
"name": "Nicola Reolfo",
|
||||
"user_name": "nreolfo5",
|
||||
"contact_number": "356-558-8324"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"image": "assets/dummy/dummy_2.jpg",
|
||||
"name": "Normy Gilhoolie",
|
||||
"user_name": "ngilhoolie6",
|
||||
"contact_number": "256-770-5288"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"image": "assets/dummy/dummy_3.jpg",
|
||||
"name": "Octavia Margerrison",
|
||||
"user_name": "omargerrison7",
|
||||
"contact_number": "744-595-1968"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"image": "assets/dummy/dummy_4.jpg",
|
||||
"name": "Stella Barriball",
|
||||
"user_name": "sbarriball8",
|
||||
"contact_number": "906-522-1874"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"image": "assets/dummy/dummy_5.jpg",
|
||||
"name": "Panchito Chase",
|
||||
"user_name": "pchase9",
|
||||
"contact_number": "929-922-7735"
|
||||
}
|
||||
]
|
||||
@ -1,102 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"candidate": "Patrica",
|
||||
"category": "Manufacture",
|
||||
"designation": "Sr.UI Developer",
|
||||
"mail": "pbeedie0@ustream.tv",
|
||||
"location": "Pojan",
|
||||
"date": "2024-08-09T06:03:25Z",
|
||||
"type": "Freelancer"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"candidate": "Angelique",
|
||||
"category": "Marketing",
|
||||
"designation": "Team Lead",
|
||||
"mail": "asamwayes1@fotki.com",
|
||||
"location": "Jiangluo",
|
||||
"date": "2023-11-17T10:23:18Z",
|
||||
"type": "Hybride"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"candidate": "Garnet",
|
||||
"category": "Marketing",
|
||||
"designation": "Team Lead",
|
||||
"mail": "gjarrelt2@dailymail.co.uk",
|
||||
"location": "Wissembourg",
|
||||
"date": "2024-03-18T15:31:21Z",
|
||||
"type": "Freelancer"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"candidate": "Guglielmo",
|
||||
"category": "Manufacture",
|
||||
"designation": "Sales Executive",
|
||||
"mail": "gcarlone3@ted.com",
|
||||
"location": "Aoqiao",
|
||||
"date": "2024-04-08T22:04:13Z",
|
||||
"type": "Part Time"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"candidate": "Reggie",
|
||||
"category": "Manufacture",
|
||||
"designation": "Team Lead",
|
||||
"mail": "rmacieiczyk4@booking.com",
|
||||
"location": "Insrom",
|
||||
"date": "2024-01-09T06:29:40Z",
|
||||
"type": "Freelancer"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"candidate": "Florri",
|
||||
"category": "Manufacture",
|
||||
"designation": "Sales Executive",
|
||||
"mail": "fharesign5@yellowbook.com",
|
||||
"location": "Itambacuri",
|
||||
"date": "2024-09-05T11:09:36Z",
|
||||
"type": "Part Time"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"candidate": "Annabella",
|
||||
"category": "Manufacture",
|
||||
"designation": "Team Lead",
|
||||
"mail": "aossipenko6@ucoz.com",
|
||||
"location": "Watthana Nakhon",
|
||||
"date": "2024-07-27T16:17:23Z",
|
||||
"type": "Full Time"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"candidate": "Arlene",
|
||||
"category": "Manufacture",
|
||||
"designation": "Team Lead",
|
||||
"mail": "agook7@google.com.hk",
|
||||
"location": "Hayama",
|
||||
"date": "2024-09-14T13:32:31Z",
|
||||
"type": "Freelancer"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"candidate": "Shurlocke",
|
||||
"category": "Manufacture",
|
||||
"designation": "Sales Executive",
|
||||
"mail": "sgallehawk8@squidoo.com",
|
||||
"location": "Bel Air Rivière Sèche",
|
||||
"date": "2024-06-18T00:23:24Z",
|
||||
"type": "Freelancer"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"candidate": "Ricoriki",
|
||||
"category": "Service",
|
||||
"designation": "Sales Executive",
|
||||
"mail": "rgillio9@mapy.cz",
|
||||
"location": "Tawangsari",
|
||||
"date": "2024-06-14T19:59:41Z",
|
||||
"type": "Freelancer"
|
||||
}
|
||||
]
|
||||
@ -1,112 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"first_name": "Bordy",
|
||||
"email": "bjeffreys0@macromedia.com",
|
||||
"phone_number": "217-779-9808",
|
||||
"company_name": "Voonyx",
|
||||
"status": "Won Lead",
|
||||
"location": "Presidencia Roque Sáenz Peña",
|
||||
"date": "2024-06-20T06:26:12Z",
|
||||
"amount": 52397
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"first_name": "Collin",
|
||||
"email": "cgething1@paginegialle.it",
|
||||
"phone_number": "124-897-0512",
|
||||
"company_name": "Rhyzio",
|
||||
"status": "New Lead",
|
||||
"location": "Nombre de Jesús",
|
||||
"date": "2023-11-20T12:12:32Z",
|
||||
"amount": 58203
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"first_name": "Bear",
|
||||
"email": "bfowlds2@booking.com",
|
||||
"phone_number": "391-249-1041",
|
||||
"company_name": "Blogtag",
|
||||
"status": "Lost Lead",
|
||||
"location": "Shani",
|
||||
"date": "2024-11-09T07:57:49Z",
|
||||
"amount": 18717
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"first_name": "Robers",
|
||||
"email": "raujouanet3@google.cn",
|
||||
"phone_number": "128-604-5632",
|
||||
"company_name": "Quire",
|
||||
"status": "Lost Lead",
|
||||
"location": "Benghazi",
|
||||
"date": "2023-12-09T17:33:39Z",
|
||||
"amount": 11267
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"first_name": "Shirlene",
|
||||
"email": "sjoiris4@theglobeandmail.com",
|
||||
"phone_number": "471-884-5686",
|
||||
"company_name": "Voonder",
|
||||
"status": "New Lead",
|
||||
"location": "Krasnaye",
|
||||
"date": "2024-01-15T03:06:07Z",
|
||||
"amount": 66877
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"first_name": "Erik",
|
||||
"email": "ebudden5@zdnet.com",
|
||||
"phone_number": "957-550-9950",
|
||||
"company_name": "Digitube",
|
||||
"status": "Won Lead",
|
||||
"location": "Taouloukoult",
|
||||
"date": "2024-01-21T03:05:01Z",
|
||||
"amount": 55766
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"first_name": "Sabina",
|
||||
"email": "sdenman6@ning.com",
|
||||
"phone_number": "612-207-4109",
|
||||
"company_name": "Kwinu",
|
||||
"status": "Lost Lead",
|
||||
"location": "Minneapolis",
|
||||
"date": "2024-05-19T15:59:28Z",
|
||||
"amount": 24691
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"first_name": "Andi",
|
||||
"email": "aschruyer7@imdb.com",
|
||||
"phone_number": "410-936-5855",
|
||||
"company_name": "Photojam",
|
||||
"status": "Won Lead",
|
||||
"location": "Masina",
|
||||
"date": "2024-09-30T18:31:07Z",
|
||||
"amount": 7228
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"first_name": "Kathy",
|
||||
"email": "kstandall8@woothemes.com",
|
||||
"phone_number": "840-267-7381",
|
||||
"company_name": "Quinu",
|
||||
"status": "Won Lead",
|
||||
"location": "Shashi",
|
||||
"date": "2024-04-21T18:00:25Z",
|
||||
"amount": 85726
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"first_name": "Lenka",
|
||||
"email": "llennon9@hexun.com",
|
||||
"phone_number": "962-993-3146",
|
||||
"company_name": "Skaboo",
|
||||
"status": "Won Lead",
|
||||
"location": "Shireet",
|
||||
"date": "2024-06-19T12:27:05Z",
|
||||
"amount": 10069
|
||||
}
|
||||
]
|
||||
@ -1,197 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Mints - Striped Red",
|
||||
"description": "Laceration of ulnar artery at wrs/hnd lv of unsp arm",
|
||||
"price": 54,
|
||||
"stock": 72,
|
||||
"category": "Scallops 60/80 Iqf",
|
||||
"order_counts": 10,
|
||||
"created_at": "2022-07-20T09:52:34Z",
|
||||
"rating": 2.49,
|
||||
"rating_count": 42,
|
||||
"sku": "RCII"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Pasta - Ravioli",
|
||||
"description": "Oth disp fx of upper end l humer, subs for fx w delay heal",
|
||||
"price": 35,
|
||||
"stock": 64,
|
||||
"category": "Chocolate - Mi - Amere Semi",
|
||||
"order_counts": 45,
|
||||
"created_at": "2023-03-25T22:32:10Z",
|
||||
"rating": 4.66,
|
||||
"rating_count": 82,
|
||||
"sku": "RDS.A"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "Soup - Campbells Chili",
|
||||
"description": "Nondisp fx of anterior wall of left acetab, init for opn fx",
|
||||
"price": 27,
|
||||
"stock": 21,
|
||||
"category": "Tomatoes - Cherry, Yellow",
|
||||
"order_counts": 53,
|
||||
"created_at": "2022-05-18T15:56:06Z",
|
||||
"rating": 3.05,
|
||||
"rating_count": 66,
|
||||
"sku": "STNG"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"name": "Fennel - Seeds",
|
||||
"description": "Displ spiral fx shaft of ulna, r arm, 7thD",
|
||||
"price": 124,
|
||||
"stock": 56,
|
||||
"category": "Squid - U - 10 Thailand",
|
||||
"order_counts": 13,
|
||||
"created_at": "2022-04-21T11:32:39Z",
|
||||
"rating": 0.59,
|
||||
"rating_count": 55,
|
||||
"sku": "FEUZ"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"name": "Salt - Celery",
|
||||
"description": "Interstitial myositis, lower leg",
|
||||
"price": 25,
|
||||
"stock": 78,
|
||||
"category": "Gatorade - Lemon Lime",
|
||||
"order_counts": 30,
|
||||
"created_at": "2023-01-01T01:15:44Z",
|
||||
"rating": 1.42,
|
||||
"rating_count": 10,
|
||||
"sku": "VER"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"name": "Flour - Chickpea",
|
||||
"description": "Oth fx upr end unsp rad, 7thJ",
|
||||
"price": 131,
|
||||
"stock": 50,
|
||||
"category": "Sweet Pea Sprouts",
|
||||
"order_counts": 11,
|
||||
"created_at": "2023-04-09T04:41:43Z",
|
||||
"rating": 4.05,
|
||||
"rating_count": 24,
|
||||
"sku": "HDS"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"name": "Chips - Miss Vickies",
|
||||
"description": "Contusion of right hip, initial encounter",
|
||||
"price": 52,
|
||||
"stock": 63,
|
||||
"category": "Extract - Almond",
|
||||
"order_counts": 62,
|
||||
"created_at": "2022-06-24T05:25:56Z",
|
||||
"rating": 3.35,
|
||||
"rating_count": 6,
|
||||
"sku": "MACQW"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"name": "Ice Cream - Super Sandwich",
|
||||
"description": "Acute post-traumatic headache",
|
||||
"price": 87,
|
||||
"stock": 44,
|
||||
"category": "Bread - Wheat Baguette",
|
||||
"order_counts": 63,
|
||||
"created_at": "2022-07-06T05:37:09Z",
|
||||
"rating": 0.96,
|
||||
"rating_count": 38,
|
||||
"sku": "AA"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"name": "Alize Gold Passion",
|
||||
"description": "War op involving explosion of marine weapons, civilian",
|
||||
"price": 113,
|
||||
"stock": 72,
|
||||
"category": "Lid - Translucent, 3.5 And 6 Oz",
|
||||
"order_counts": 23,
|
||||
"created_at": "2022-07-09T18:19:37Z",
|
||||
"rating": 3.25,
|
||||
"rating_count": 64,
|
||||
"sku": "EVOK"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"name": "Mushrooms - Honey",
|
||||
"description": "Sltr-haris Type IV physl fx low end l femr, 7thP",
|
||||
"price": 98,
|
||||
"stock": 64,
|
||||
"category": "Lemon Balm - Fresh",
|
||||
"order_counts": 5,
|
||||
"created_at": "2022-08-05T22:14:06Z",
|
||||
"rating": 3.51,
|
||||
"rating_count": 0,
|
||||
"sku": "TDG"
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "Bread Base - Goodhearth",
|
||||
"description": "Unspecified injury of axillary artery",
|
||||
"price": 81,
|
||||
"stock": 56,
|
||||
"category": "Beef - Bones, Marrow",
|
||||
"order_counts": 76,
|
||||
"created_at": "2023-04-22T03:11:41Z",
|
||||
"rating": 4.07,
|
||||
"rating_count": 22,
|
||||
"sku": "GPAC"
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "Veal - Heart",
|
||||
"description": "Laceration without foreign body of left buttock, subs encntr",
|
||||
"price": 93,
|
||||
"stock": 13,
|
||||
"category": "Peach - Fresh",
|
||||
"order_counts": 12,
|
||||
"created_at": "2023-02-18T16:15:16Z",
|
||||
"rating": 2.08,
|
||||
"rating_count": 87,
|
||||
"sku": "PAH"
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"name": "Tomatoes - Grape",
|
||||
"description": "Nondisplaced bicondylar fracture of left tibia",
|
||||
"price": 132,
|
||||
"stock": 13,
|
||||
"category": "Veal - Striploin",
|
||||
"order_counts": 24,
|
||||
"created_at": "2022-06-08T20:49:59Z",
|
||||
"rating": 3.32,
|
||||
"rating_count": 82,
|
||||
"sku": "ENZL"
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"name": "Tomato Paste",
|
||||
"description": "Abrasion of unspecified part of neck, initial encounter",
|
||||
"price": 48,
|
||||
"stock": 24,
|
||||
"category": "Juice - Tomato, 48 Oz",
|
||||
"order_counts": 4,
|
||||
"created_at": "2022-12-03T04:03:52Z",
|
||||
"rating": 4.11,
|
||||
"rating_count": 66,
|
||||
"sku": "LTEA"
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"name": "Cheese - Roquefort Pappillon",
|
||||
"description": "Wedge comprsn fx first thor vertebra, init for opn fx",
|
||||
"price": 15,
|
||||
"stock": 68,
|
||||
"category": "Veal - Insides, Grains",
|
||||
"order_counts": 72,
|
||||
"created_at": "2022-09-22T06:22:33Z",
|
||||
"rating": 1.54,
|
||||
"rating_count": 40,
|
||||
"sku": "AIF"
|
||||
}
|
||||
]
|
||||
@ -1,102 +0,0 @@
|
||||
[
|
||||
{
|
||||
"order_id": "TWT76911",
|
||||
"customer_name": "Robinson",
|
||||
"location": "Lyubokhna",
|
||||
"order_date": "2023-09-17T00:35:06Z",
|
||||
"quantity": 6,
|
||||
"payments": "COD",
|
||||
"price": 336,
|
||||
"status": "New"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT23890",
|
||||
"customer_name": "Claudina",
|
||||
"location": "Maracha",
|
||||
"order_date": "2023-09-11T15:01:04Z",
|
||||
"quantity": 8,
|
||||
"payments": "American Express",
|
||||
"price": 428,
|
||||
"status": "Shopping"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT84616",
|
||||
"customer_name": "Dewain",
|
||||
"location": "Fuji",
|
||||
"order_date": "2023-12-26T02:42:54Z",
|
||||
"quantity": 6,
|
||||
"payments": "Credit Card",
|
||||
"price": 410,
|
||||
"status": "Shopping"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT66711",
|
||||
"customer_name": "Margette",
|
||||
"location": "Chicago",
|
||||
"order_date": "2024-01-09T18:24:04Z",
|
||||
"quantity": 10,
|
||||
"payments": "Paypal",
|
||||
"price": 268,
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT50711",
|
||||
"customer_name": "Brittany",
|
||||
"location": "Hakha",
|
||||
"order_date": "2023-09-28T14:17:02Z",
|
||||
"quantity": 2,
|
||||
"payments": "Visa Card",
|
||||
"price": 229,
|
||||
"status": "New"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT37588",
|
||||
"customer_name": "Venus",
|
||||
"location": "Sioguí Arriba",
|
||||
"order_date": "2023-10-16T18:22:32Z",
|
||||
"quantity": 5,
|
||||
"payments": "Visa Card",
|
||||
"price": 211,
|
||||
"status": "Delivered"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT36092",
|
||||
"customer_name": "Norry",
|
||||
"location": "Hongqi",
|
||||
"order_date": "2024-01-28T16:50:34Z",
|
||||
"quantity": 7,
|
||||
"payments": "American Express",
|
||||
"price": 111,
|
||||
"status": "Shopping"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT99659",
|
||||
"customer_name": "Rabbi",
|
||||
"location": "Macari",
|
||||
"order_date": "2023-03-27T17:42:51Z",
|
||||
"quantity": 9,
|
||||
"payments": "COD",
|
||||
"price": 268,
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT21952",
|
||||
"customer_name": "Hesther",
|
||||
"location": "København",
|
||||
"order_date": "2024-02-08T00:16:01Z",
|
||||
"quantity": 9,
|
||||
"payments": "Credit Card",
|
||||
"price": 392,
|
||||
"status": "Delivered"
|
||||
},
|
||||
{
|
||||
"order_id": "TWT66885",
|
||||
"customer_name": "Sioux",
|
||||
"location": "Taohua",
|
||||
"order_date": "2023-10-23T16:25:29Z",
|
||||
"quantity": 1,
|
||||
"payments": "Paypal",
|
||||
"price": 337,
|
||||
"status": "New"
|
||||
}
|
||||
]
|
||||
@ -1,82 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Marketing Manager",
|
||||
"assign_to": "Hercules",
|
||||
"date": "2024-03-10T00:14:27Z",
|
||||
"priority": "High",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Community Outreach Specialist",
|
||||
"assign_to": "Fayre",
|
||||
"date": "2024-10-07T06:24:18Z",
|
||||
"priority": "High",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Senior Quality Engineer",
|
||||
"assign_to": "Nancy",
|
||||
"date": "2024-01-11T18:22:29Z",
|
||||
"priority": "Medium",
|
||||
"status": "In Progress"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "VP Sales",
|
||||
"assign_to": "Jemimah",
|
||||
"date": "2024-06-17T17:57:40Z",
|
||||
"priority": "Low",
|
||||
"status": "Finished"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Sales Associate",
|
||||
"assign_to": "Raquel",
|
||||
"date": "2024-05-06T11:11:43Z",
|
||||
"priority": "Medium",
|
||||
"status": "Finished"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Dental Hygienist",
|
||||
"assign_to": "Vasili",
|
||||
"date": "2024-05-31T21:16:27Z",
|
||||
"priority": "High",
|
||||
"status": "Finished"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Occupational Therapist",
|
||||
"assign_to": "Lulu",
|
||||
"date": "2024-03-28T21:07:00Z",
|
||||
"priority": "Medium",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Analyst Programmer",
|
||||
"assign_to": "Egor",
|
||||
"date": "2023-12-11T08:16:01Z",
|
||||
"priority": "High",
|
||||
"status": "Finished"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Research Assistant III",
|
||||
"assign_to": "Max",
|
||||
"date": "2024-02-15T21:59:34Z",
|
||||
"priority": "High",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Developer II",
|
||||
"assign_to": "Kaela",
|
||||
"date": "2024-06-24T07:29:47Z",
|
||||
"priority": "High",
|
||||
"status": "Cancelled"
|
||||
}
|
||||
]
|
||||
@ -1,47 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"product_name": "Theobald",
|
||||
"quantity": 2,
|
||||
"customer": "Theobald Southcott",
|
||||
"status": "Shipped",
|
||||
"price": 361,
|
||||
"order_date": "2023-12-11T23:48:54Z"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"product_name": "Carla",
|
||||
"quantity": 3,
|
||||
"customer": "Carla Grgic",
|
||||
"status": "Pending",
|
||||
"price": 329,
|
||||
"order_date": "2024-05-25T09:37:51Z"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"product_name": "Liana",
|
||||
"quantity": 3,
|
||||
"customer": "Liana Swannell",
|
||||
"status": "Delivery",
|
||||
"price": 120,
|
||||
"order_date": "2024-04-06T19:02:14Z"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"product_name": "Radcliffe",
|
||||
"quantity": 4,
|
||||
"customer": "Radcliffe Venard",
|
||||
"status": "Shipped",
|
||||
"price": 750,
|
||||
"order_date": "2024-10-27T10:44:12Z"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"product_name": "Delmer",
|
||||
"quantity": 3,
|
||||
"customer": "Delmer Vamplew",
|
||||
"status": "Delivery",
|
||||
"price": 469,
|
||||
"order_date": "2024-10-16T15:55:22Z"
|
||||
}
|
||||
]
|
||||
@ -1,91 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Finish report",
|
||||
"description": "Complete the quarterly report for the team meeting.",
|
||||
"due_date": "2024-07-14T00:37:09Z",
|
||||
"priority": "High",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Team meeting",
|
||||
"description": "Attend the weekly project meeting and provide updates.",
|
||||
"due_date": "2024-04-18T01:25:27Z",
|
||||
"priority": "Medium",
|
||||
"status": "Completed"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Buy groceries",
|
||||
"description": "Purchase ingredients for dinner and weekly supplies.",
|
||||
"due_date": "2024-02-17T16:32:03Z",
|
||||
"priority": "Low",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Update website",
|
||||
"description": "Update the homepage with new content and images.",
|
||||
"due_date": "2024-07-16T15:49:59Z",
|
||||
"priority": "Medium",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Send emails",
|
||||
"description": "Send out follow-up emails to clients from last week's meeting.",
|
||||
"due_date": "2024-09-24T11:08:14Z",
|
||||
"priority": "High",
|
||||
"status": "Completed"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Organize workspace",
|
||||
"description": "Declutter desk and organize office supplies.",
|
||||
"due_date": "2024-10-06T11:49:14Z",
|
||||
"priority": "Low",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Prepare presentation",
|
||||
"description": "Create slides for next week's client pitch.",
|
||||
"due_date": "2024-05-20T04:38:51Z",
|
||||
"priority": "High",
|
||||
"status": "In Progress"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Write blog post",
|
||||
"description": "Write a blog post about industry trends for the company website.",
|
||||
"due_date": "2024-01-13T07:46:34Z",
|
||||
"priority": "Medium",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Schedule doctor's appointment",
|
||||
"description": "Call and book a check-up appointment with the doctor.",
|
||||
"due_date": "2024-09-22T10:54:21Z",
|
||||
"priority": "Low",
|
||||
"status": "Pending"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Review budget",
|
||||
"description": "Review and adjust monthly budget for expenses.",
|
||||
"due_date": "2024-08-20T03:57:48Z",
|
||||
"priority": "Medium",
|
||||
"status": "Pending"
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -1,62 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"first_name": "Roobbie",
|
||||
"last_name": "Ivashintsov",
|
||||
"email": "rivashintsov0@symantec.com"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"first_name": "Cissy",
|
||||
"last_name": "Salmons",
|
||||
"email": "csalmons1@unicef.org"
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"first_name": "Jillene",
|
||||
"last_name": "Besnardeau",
|
||||
"email": "jbesnardeau2@china.com.cn"
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"first_name": "Catriona",
|
||||
"last_name": "Wrennall",
|
||||
"email": "cwrennall3@godaddy.com"
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"first_name": "Risa",
|
||||
"last_name": "Rumens",
|
||||
"email": "rrumens4@un.org"
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"first_name": "Gianina",
|
||||
"last_name": "Pavlenkov",
|
||||
"email": "gpavlenkov5@ted.com"
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"first_name": "Tripp",
|
||||
"last_name": "Blowick",
|
||||
"email": "tblowick6@reuters.com"
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"first_name": "Ephrem",
|
||||
"last_name": "Pfertner",
|
||||
"email": "epfertner7@godaddy.com"
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"first_name": "Jacinda",
|
||||
"last_name": "Tomkies",
|
||||
"email": "jtomkies8@si.edu"
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"first_name": "Traver",
|
||||
"last_name": "Poile",
|
||||
"email": "tpoile9@phoca.cz"
|
||||
}
|
||||
]
|
||||
@ -1,56 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"session_duration": "2023-08-18T14:47:41Z",
|
||||
"channel": "Organic Search",
|
||||
"session": 547,
|
||||
"bounce_rate": 27.2,
|
||||
"target_reached": 843,
|
||||
"page_per_session": 4.4
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"session_duration": "2023-04-20T20:13:24Z",
|
||||
"channel": "Direct",
|
||||
"session": 855,
|
||||
"bounce_rate": 25.8,
|
||||
"target_reached": 998,
|
||||
"page_per_session": 6.6
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"session_duration": "2023-09-05T02:15:03Z",
|
||||
"channel": "Referral",
|
||||
"session": 337,
|
||||
"bounce_rate": 12.4,
|
||||
"target_reached": 509,
|
||||
"page_per_session": 8.0
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"session_duration": "2023-06-23T13:50:55Z",
|
||||
"channel": "Social",
|
||||
"session": 279,
|
||||
"bounce_rate": 40.4,
|
||||
"target_reached": 860,
|
||||
"page_per_session": 7.3
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"session_duration": "2023-09-14T09:01:34Z",
|
||||
"channel": "Email",
|
||||
"session": 118,
|
||||
"bounce_rate": 46.2,
|
||||
"target_reached": 168,
|
||||
"page_per_session": 3.0
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"session_duration": "2023-07-14T01:46:51Z",
|
||||
"channel": "Paid Search",
|
||||
"session": 205,
|
||||
"bounce_rate": 32.8,
|
||||
"target_reached": 583,
|
||||
"page_per_session": 2.5
|
||||
}
|
||||
]
|
||||
|
Before Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 146 KiB |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 179 KiB |
|
Before Width: | Height: | Size: 152 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 35 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 37 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 277 KiB |
|
Before Width: | Height: | Size: 341 KiB |
|
Before Width: | Height: | Size: 396 KiB |
|
Before Width: | Height: | Size: 316 KiB |
|
Before Width: | Height: | Size: 375 KiB |
|
Before Width: | Height: | Size: 380 KiB |
13
assets/service-account.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"type": "service_account",
|
||||
"project_id": "mtest-a0635",
|
||||
"private_key_id": "39a69f7d2a64234784e0d0ce6c113052296d6dc1",
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCimbxktO7PeQ4h\n81Ye2ZBcZjltDhqqD0o9XyLmNdHszzM056bwpJkvgoyyTJAIvR2fcBF3YQFyuC+1\nddLHtchP48FjflZ+zZzLp7oaA/Zh28OZLbCsu+Nm8vO3WJVoIaJYgi+jEz21G128\ncOIbgkKIpLMz1wQhPPOwDTuSdQ+WajWJb04/aNrmTRH1hMreyhHiIFmalcavUgc1\nY5FvgrGs7EaKjYBevoFN3dwmEXjfyHjfBSxnt1yytl9tbtINqdrYLYAMm1l3+KqO\nCGxicQE5kjI1osI2wRjsk105RHnpxPg2GZnI4vTIOkEY5czhRSOs94g2d628H6fq\nVzf9UqwtAgMBAAECggEARluLf3AjHbdd/CbVDwhJRRIeqye9NfTjxOaTrVWAfp2x\npKTQQbSXbE1rIAOtF3rthH3zsNpSzBcS3cwb5rqr8JW2qpySRNAnlp//ER7Bz9pO\nKsvwdO3gGj3qY117WNGk8/NxNXkv7FvpFY8q54hXzdSmjjnt2YwMThOLwXXRxt2B\nFxN3FpBWqw12epqS162nW2nIRJ34Jloil4J5x61Sc79MCFyCxyhMlrBkY+Ni/xb1\nigBXBjczxNiJqqDie0mc16WB1HMEcBP9Yjtb46Hhfs3NDDWNqDkoM8QmEMSg8EHy\nyjcSlf0Wj8I9Kf+0PZo+2FB2DbuhfA8IVR9U/c00KQKBgQDd/OULx6QpmUev1Gl/\nrwwN67ZUMJ72cRuwvLFsMTIzZ+oItO0AR1uMkRZ1crOMc490XNUvSCGP6piZQAn1\nro8qNAh+0Q/UvKHM1khOj/4DxEGZRnNOhe6QLZM9QNygENuEYfdYDD9wcQI9Xs+B\nMIOBsuuqUVHlsbvYkeYNS8M8swKBgQC7g3i1dYRC/bkNMthVS4GTlFRuLscyIjTi\nhruhdaSE+fBZ5RO3XDzz6oDHYcdo/z5ySqI7EIsckNRbwFsMCOjSP3xJapadPYwU\nIhZBU7lgNlPnHJ/BIUwA5JZqRqGTNWrFINUHZFp2RK/x2bYdfoqY8bq08eWs9gmR\nc7U7i+6jnwKBgGaO3isxExD89fewBQWuk70it1vyEp785rQimT3JBM5nJeLb49sL\nHKq2pU+hrH4pLY+vC/cKNidNVS8IPRG6kf4HiB0+7Td15rLCFSnmsI6A72Wm/MK8\ncdk+lRXpj4SMBT8GG8Yb8ns6WrSLxwaCqV8UkHhhlZqvIIAP998Qr6StAoGAQTwr\n8nU/3k6G4qCdwo7SNZWVCgAcLMTZwTU+cZ2L7vdFNwELKu9cBT/ALZ1G0rB5+Skd\n546J1xZLyt/QzQ8McJjFlIUQgQO4iAiT1YZbJ62+4tiCe54p4uWjrrWD4MLkslAJ\nzNiM4DhlPa6QPRKZBTyTx/+f99xg18l5c43rJ+ECgYBkXMfjdn8SOaG6ggJrf1xx\nas49vwAscx4AJaOdVu3D8lCwoNCuAJhBHcFqsJ0wEHWpsqKAdXxqX/Nt2x8t7zL0\nPoRCvfsq5P7GdRrNhrHxLwjDqh+OS+Ow6t0esPQ5RPBgtjvthAlb7bV2nIfkpmdl\nFbjML8vkXk9iPJsbAfO2jw==\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "firebase-adminsdk-fbsvc@mtest-a0635.iam.gserviceaccount.com",
|
||||
"client_id": "111097905744982732087",
|
||||
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
||||
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40mtest-a0635.iam.gserviceaccount.com",
|
||||
"universe_domain": "googleapis.com"
|
||||
}
|
||||
55
build_release.sh
Normal file
@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ===============================
|
||||
# Flutter APK Build Script (AAB Disabled)
|
||||
# ===============================
|
||||
|
||||
# Exit immediately if a command exits with a non-zero status
|
||||
set -e
|
||||
|
||||
# Colors for pretty output
|
||||
GREEN='\033[0;32m'
|
||||
CYAN='\033[0;36m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# App info
|
||||
APP_NAME="On Field Work"
|
||||
BUILD_DIR="build/app/outputs"
|
||||
|
||||
echo -e "${CYAN}🚀 Starting Flutter build script for $APP_NAME...${NC}"
|
||||
|
||||
# Step 1: Clean previous builds
|
||||
echo -e "${YELLOW}🧹 Cleaning previous builds...${NC}"
|
||||
flutter clean
|
||||
|
||||
# Step 2: Get dependencies
|
||||
echo -e "${YELLOW}📦 Fetching dependencies...${NC}"
|
||||
flutter pub get
|
||||
|
||||
# ==============================
|
||||
# Step 3: Build AAB (Commented)
|
||||
# ==============================
|
||||
# echo -e "${CYAN}🏗 Building AAB file...${NC}"
|
||||
# flutter build appbundle --release
|
||||
|
||||
# Step 4: Build APK
|
||||
echo -e "${CYAN}🏗 Building APK file...${NC}"
|
||||
flutter build apk --release
|
||||
|
||||
# Step 5: Show output paths
|
||||
# AAB_PATH="$BUILD_DIR/bundle/release/app-release.aab"
|
||||
APK_PATH="$BUILD_DIR/apk/release/app-release.apk"
|
||||
|
||||
echo -e "${GREEN}✅ Build completed successfully!${NC}"
|
||||
# echo -e "${YELLOW}📍 AAB file: ${CYAN}$AAB_PATH${NC}"
|
||||
echo -e "${YELLOW}📍 APK file: ${CYAN}$APK_PATH${NC}"
|
||||
|
||||
# Optional: open the folder (Mac/Linux)
|
||||
if command -v xdg-open &> /dev/null
|
||||
then
|
||||
xdg-open "$BUILD_DIR"
|
||||
elif command -v open &> /dev/null
|
||||
then
|
||||
open "$BUILD_DIR"
|
||||
fi
|
||||
3
devtools_options.yaml
Normal file
@ -0,0 +1,3 @@
|
||||
description: This file stores settings for Dart & Flutter DevTools.
|
||||
documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states
|
||||
extensions:
|
||||
@ -368,7 +368,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
@ -384,7 +384,7 @@
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco.RunnerTests;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot.RunnerTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@ -401,7 +401,7 @@
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco.RunnerTests;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot.RunnerTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
|
||||
@ -416,7 +416,7 @@
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco.RunnerTests;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot.RunnerTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner";
|
||||
@ -547,7 +547,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@ -569,7 +569,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.example.marco;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.marcoonfieldwork.aiot;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>Marco</string>
|
||||
<string>On Field Work</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@ -13,7 +13,7 @@
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>marco</string>
|
||||
<string>on field work</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
|
||||
@ -8,5 +8,5 @@ class AppConstant {
|
||||
static int iOSAppVersion = 1;
|
||||
static String version = "1.0.0";
|
||||
|
||||
static String get appName => 'Marco';
|
||||
static String get appName => 'On Field Work';
|
||||
}
|
||||
|
||||
584
lib/controller/attendance/attendance_screen_controller.dart
Normal file
@ -0,0 +1,584 @@
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import 'package:on_field_work/controller/dashboard/dashboard_controller.dart';
|
||||
import 'package:on_field_work/controller/project_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_image_compressor.dart';
|
||||
import 'package:on_field_work/helpers/widgets/time_stamp_image_helper.dart';
|
||||
import 'package:on_field_work/model/attendance/attendance_log_model.dart';
|
||||
import 'package:on_field_work/model/attendance/attendance_log_view_model.dart';
|
||||
import 'package:on_field_work/model/attendance/attendance_model.dart';
|
||||
import 'package:on_field_work/model/attendance/organization_per_project_list_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/model/project_model.dart';
|
||||
import 'package:on_field_work/model/regularization_log_model.dart';
|
||||
|
||||
class AttendanceController extends GetxController {
|
||||
// ------------------ Data Models ------------------
|
||||
final List<AttendanceModel> attendances = <AttendanceModel>[];
|
||||
final List<ProjectModel> projects = <ProjectModel>[];
|
||||
final List<EmployeeModel> employees = <EmployeeModel>[];
|
||||
final List<AttendanceLogModel> attendanceLogs = <AttendanceLogModel>[];
|
||||
final List<RegularizationLogModel> regularizationLogs =
|
||||
<RegularizationLogModel>[];
|
||||
final List<AttendanceLogViewModel> attendenceLogsView =
|
||||
<AttendanceLogViewModel>[];
|
||||
|
||||
// ------------------ Organizations ------------------
|
||||
final List<Organization> organizations = <Organization>[];
|
||||
Organization? selectedOrganization;
|
||||
final RxBool isLoadingOrganizations = false.obs;
|
||||
|
||||
// ------------------ States ------------------
|
||||
String selectedTab = 'todaysAttendance';
|
||||
|
||||
// ✅ Reactive date range
|
||||
final Rx<DateTime> startDateAttendance =
|
||||
DateTime.now().subtract(const Duration(days: 7)).obs;
|
||||
final Rx<DateTime> endDateAttendance =
|
||||
DateTime.now().subtract(const Duration(days: 1)).obs;
|
||||
|
||||
final RxBool isLoading = true.obs;
|
||||
final RxBool isLoadingProjects = true.obs;
|
||||
final RxBool isLoadingEmployees = true.obs;
|
||||
final RxBool isLoadingAttendanceLogs = true.obs;
|
||||
final RxBool isLoadingRegularizationLogs = true.obs;
|
||||
final RxBool isLoadingLogView = true.obs;
|
||||
|
||||
final RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
|
||||
|
||||
final RxBool showPendingOnly = false.obs;
|
||||
final RxString searchQuery = ''.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_initializeDefaults();
|
||||
}
|
||||
|
||||
void _initializeDefaults() {
|
||||
_setDefaultDateRange();
|
||||
}
|
||||
|
||||
void _setDefaultDateRange() {
|
||||
final DateTime today = DateTime.now();
|
||||
startDateAttendance.value = today.subtract(const Duration(days: 7));
|
||||
endDateAttendance.value = today.subtract(const Duration(days: 1));
|
||||
logSafe(
|
||||
'Default date range set: ${startDateAttendance.value} to ${endDateAttendance.value}',
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------ Computed Filters ------------------
|
||||
List<EmployeeModel> get filteredEmployees {
|
||||
final String query = searchQuery.value.trim().toLowerCase();
|
||||
if (query.isEmpty) return employees;
|
||||
return employees
|
||||
.where(
|
||||
(EmployeeModel e) => e.name.toLowerCase().contains(query),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
List<AttendanceLogModel> get filteredLogs {
|
||||
final String query = searchQuery.value.trim().toLowerCase();
|
||||
if (query.isEmpty) return attendanceLogs;
|
||||
return attendanceLogs
|
||||
.where(
|
||||
(AttendanceLogModel log) => log.name.toLowerCase().contains(query),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
List<RegularizationLogModel> get filteredRegularizationLogs {
|
||||
final String query = searchQuery.value.trim().toLowerCase();
|
||||
if (query.isEmpty) return regularizationLogs;
|
||||
return regularizationLogs
|
||||
.where(
|
||||
(RegularizationLogModel log) =>
|
||||
log.name.toLowerCase().contains(query),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
// ------------------ Project & Employee APIs ------------------
|
||||
Future<void> refreshDataFromNotification({String? projectId}) async {
|
||||
projectId ??= Get.find<ProjectController>().selectedProject?.id;
|
||||
if (projectId == null) {
|
||||
logSafe(
|
||||
'No project selected for attendance refresh from notification',
|
||||
level: LogLevel.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await fetchProjectData(projectId);
|
||||
logSafe(
|
||||
'Attendance data refreshed from notification for project $projectId',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> fetchTodaysAttendance(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingEmployees.value = true;
|
||||
|
||||
final List<dynamic>? response = await ApiService.getTodaysAttendance(
|
||||
projectId,
|
||||
organizationId: selectedOrganization?.id,
|
||||
);
|
||||
if (response != null) {
|
||||
employees
|
||||
..clear()
|
||||
..addAll(
|
||||
response
|
||||
.map<EmployeeModel>(
|
||||
(dynamic e) => EmployeeModel.fromJson(
|
||||
e as Map<String, dynamic>,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
|
||||
for (final EmployeeModel emp in employees) {
|
||||
uploadingStates[emp.id] = false.obs;
|
||||
}
|
||||
|
||||
logSafe(
|
||||
'Employees fetched: ${employees.length} for project $projectId',
|
||||
);
|
||||
} else {
|
||||
logSafe(
|
||||
'Failed to fetch employees for project $projectId',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
}
|
||||
|
||||
isLoadingEmployees.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> fetchOrganizations(String projectId) async {
|
||||
isLoadingOrganizations.value = true;
|
||||
|
||||
// Keep original return type inference from your ApiService
|
||||
final response = await ApiService.getAssignedOrganizations(projectId);
|
||||
|
||||
if (response != null) {
|
||||
organizations
|
||||
..clear()
|
||||
..addAll(response.data);
|
||||
logSafe('Organizations fetched: ${organizations.length}');
|
||||
} else {
|
||||
logSafe(
|
||||
'Failed to fetch organizations for project $projectId',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
}
|
||||
|
||||
isLoadingOrganizations.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// ------------------ Attendance Capture ------------------
|
||||
Future<bool> captureAndUploadAttendance(
|
||||
String id,
|
||||
String employeeId,
|
||||
String projectId, {
|
||||
String comment = 'Marked via mobile app',
|
||||
required int action,
|
||||
bool imageCapture = true,
|
||||
String? markTime,
|
||||
String? date,
|
||||
}) async {
|
||||
try {
|
||||
_setUploading(employeeId, true);
|
||||
|
||||
final XFile? image = await _captureAndPrepareImage(
|
||||
employeeId: employeeId,
|
||||
imageCapture: imageCapture,
|
||||
);
|
||||
if (imageCapture && image == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final Position? position = await _getCurrentPositionSafely();
|
||||
if (position == null) return false;
|
||||
|
||||
final String imageName = imageCapture
|
||||
? ApiService.generateImageName(
|
||||
employeeId,
|
||||
employees.length + 1,
|
||||
)
|
||||
: '';
|
||||
|
||||
final DateTime effectiveDate =
|
||||
_resolveEffectiveDateForAction(action, employeeId);
|
||||
|
||||
final DateTime now = DateTime.now();
|
||||
final String formattedMarkTime =
|
||||
markTime ?? DateFormat('hh:mm a').format(now);
|
||||
final String formattedDate =
|
||||
date ?? DateFormat('yyyy-MM-dd').format(effectiveDate);
|
||||
|
||||
final bool result = await ApiService.uploadAttendanceImage(
|
||||
id,
|
||||
employeeId,
|
||||
image,
|
||||
position.latitude,
|
||||
position.longitude,
|
||||
imageName: imageName,
|
||||
projectId: projectId,
|
||||
comment: comment,
|
||||
action: action,
|
||||
imageCapture: imageCapture,
|
||||
markTime: formattedMarkTime,
|
||||
date: formattedDate,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
logSafe(
|
||||
'Attendance uploaded for $employeeId, action: $action, date: $formattedDate',
|
||||
);
|
||||
|
||||
if (Get.isRegistered<DashboardController>()) {
|
||||
final DashboardController dashboardController =
|
||||
Get.find<DashboardController>();
|
||||
await dashboardController.fetchTodaysAttendance(projectId);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (e, stacktrace) {
|
||||
logSafe(
|
||||
'Error uploading attendance',
|
||||
level: LogLevel.error,
|
||||
error: e,
|
||||
stackTrace: stacktrace,
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
_setUploading(employeeId, false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<XFile?> _captureAndPrepareImage({
|
||||
required String employeeId,
|
||||
required bool imageCapture,
|
||||
}) async {
|
||||
if (!imageCapture) return null;
|
||||
|
||||
final XFile? rawImage = await ImagePicker().pickImage(
|
||||
source: ImageSource.camera,
|
||||
imageQuality: 80,
|
||||
);
|
||||
if (rawImage == null) {
|
||||
logSafe(
|
||||
'Image capture cancelled.',
|
||||
level: LogLevel.warning,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
final File timestampedFile = await TimestampImageHelper.addTimestamp(
|
||||
imageFile: File(rawImage.path),
|
||||
);
|
||||
|
||||
final List<int>? compressedBytes =
|
||||
await compressImageToUnder100KB(timestampedFile);
|
||||
if (compressedBytes == null) {
|
||||
logSafe(
|
||||
'Image compression failed.',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// FIX: convert List<int> -> Uint8List
|
||||
final Uint8List compressedUint8List = Uint8List.fromList(compressedBytes);
|
||||
|
||||
final File compressedFile =
|
||||
await saveCompressedImageToFile(compressedUint8List);
|
||||
return XFile(compressedFile.path);
|
||||
}
|
||||
|
||||
Future<Position?> _getCurrentPositionSafely() async {
|
||||
final bool permissionGranted = await _handleLocationPermission();
|
||||
if (!permissionGranted) return null;
|
||||
|
||||
return Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high,
|
||||
);
|
||||
}
|
||||
|
||||
DateTime _resolveEffectiveDateForAction(int action, String employeeId) {
|
||||
final DateTime now = DateTime.now();
|
||||
if (action != 1) return now;
|
||||
|
||||
final AttendanceLogModel? log = attendanceLogs.firstWhereOrNull(
|
||||
(AttendanceLogModel log) =>
|
||||
log.employeeId == employeeId && log.checkOut == null,
|
||||
);
|
||||
|
||||
return log?.checkIn ?? now;
|
||||
}
|
||||
|
||||
void _setUploading(String employeeId, bool value) {
|
||||
final RxBool? state = uploadingStates[employeeId];
|
||||
if (state != null) {
|
||||
state.value = value;
|
||||
} else {
|
||||
uploadingStates[employeeId] = value.obs;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _handleLocationPermission() async {
|
||||
LocationPermission permission = await Geolocator.checkPermission();
|
||||
|
||||
if (permission == LocationPermission.denied) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
logSafe(
|
||||
'Location permissions are denied',
|
||||
level: LogLevel.warning,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (permission == LocationPermission.deniedForever) {
|
||||
logSafe(
|
||||
'Location permissions are permanently denied',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ------------------ Attendance Logs ------------------
|
||||
Future<void> fetchAttendanceLogs(
|
||||
String? projectId, {
|
||||
DateTime? dateFrom,
|
||||
DateTime? dateTo,
|
||||
}) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingAttendanceLogs.value = true;
|
||||
|
||||
final List<dynamic>? response = await ApiService.getAttendanceLogs(
|
||||
projectId,
|
||||
dateFrom: dateFrom,
|
||||
dateTo: dateTo,
|
||||
organizationId: selectedOrganization?.id,
|
||||
);
|
||||
|
||||
if (response != null) {
|
||||
attendanceLogs
|
||||
..clear()
|
||||
..addAll(
|
||||
response
|
||||
.map<AttendanceLogModel>(
|
||||
(dynamic e) => AttendanceLogModel.fromJson(
|
||||
e as Map<String, dynamic>,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
logSafe('Attendance logs fetched: ${attendanceLogs.length}');
|
||||
} else {
|
||||
logSafe(
|
||||
'Failed to fetch attendance logs for project $projectId',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
}
|
||||
|
||||
isLoadingAttendanceLogs.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Map<String, List<AttendanceLogModel>> groupLogsByCheckInDate() {
|
||||
final Map<String, List<AttendanceLogModel>> groupedLogs =
|
||||
<String, List<AttendanceLogModel>>{};
|
||||
|
||||
for (final AttendanceLogModel logItem in attendanceLogs) {
|
||||
final String checkInDate = logItem.checkIn != null
|
||||
? DateFormat('dd MMM yyyy').format(logItem.checkIn!)
|
||||
: 'Unknown';
|
||||
|
||||
groupedLogs.putIfAbsent(
|
||||
checkInDate,
|
||||
() => <AttendanceLogModel>[],
|
||||
)..add(logItem);
|
||||
}
|
||||
|
||||
final List<MapEntry<String, List<AttendanceLogModel>>> sortedEntries =
|
||||
groupedLogs.entries.toList()
|
||||
..sort(
|
||||
(MapEntry<String, List<AttendanceLogModel>> a,
|
||||
MapEntry<String, List<AttendanceLogModel>> b) {
|
||||
if (a.key == 'Unknown') return 1;
|
||||
if (b.key == 'Unknown') return -1;
|
||||
|
||||
final DateTime dateA = DateFormat('dd MMM yyyy').parse(a.key);
|
||||
final DateTime dateB = DateFormat('dd MMM yyyy').parse(b.key);
|
||||
return dateB.compareTo(dateA);
|
||||
},
|
||||
);
|
||||
|
||||
return Map<String, List<AttendanceLogModel>>.fromEntries(
|
||||
sortedEntries,
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------ Regularization Logs ------------------
|
||||
Future<void> fetchRegularizationLogs(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingRegularizationLogs.value = true;
|
||||
|
||||
final List<dynamic>? response = await ApiService.getRegularizationLogs(
|
||||
projectId,
|
||||
organizationId: selectedOrganization?.id,
|
||||
);
|
||||
|
||||
if (response != null) {
|
||||
regularizationLogs
|
||||
..clear()
|
||||
..addAll(
|
||||
response
|
||||
.map<RegularizationLogModel>(
|
||||
(dynamic e) => RegularizationLogModel.fromJson(
|
||||
e as Map<String, dynamic>,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
logSafe(
|
||||
'Regularization logs fetched: ${regularizationLogs.length}',
|
||||
);
|
||||
} else {
|
||||
logSafe(
|
||||
'Failed to fetch regularization logs for project $projectId',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
}
|
||||
|
||||
isLoadingRegularizationLogs.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// ------------------ Attendance Log View ------------------
|
||||
Future<void> fetchLogsView(String? id) async {
|
||||
if (id == null) return;
|
||||
|
||||
isLoadingLogView.value = true;
|
||||
|
||||
final List<dynamic>? response = await ApiService.getAttendanceLogView(id);
|
||||
|
||||
if (response != null) {
|
||||
attendenceLogsView
|
||||
..clear()
|
||||
..addAll(
|
||||
response
|
||||
.map<AttendanceLogViewModel>(
|
||||
(dynamic e) => AttendanceLogViewModel.fromJson(
|
||||
e as Map<String, dynamic>,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
|
||||
attendenceLogsView.sort(
|
||||
(AttendanceLogViewModel a, AttendanceLogViewModel b) =>
|
||||
(b.activityTime ?? DateTime(2000))
|
||||
.compareTo(a.activityTime ?? DateTime(2000)),
|
||||
);
|
||||
|
||||
logSafe('Attendance log view fetched for ID: $id');
|
||||
} else {
|
||||
logSafe(
|
||||
'Failed to fetch attendance log view for ID $id',
|
||||
level: LogLevel.error,
|
||||
);
|
||||
}
|
||||
|
||||
isLoadingLogView.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
// ------------------ Combined Load ------------------
|
||||
Future<void> loadAttendanceData(String projectId) async {
|
||||
isLoading.value = true;
|
||||
await fetchProjectData(projectId);
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
Future<void> fetchProjectData(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
await fetchOrganizations(projectId);
|
||||
|
||||
switch (selectedTab) {
|
||||
case 'todaysAttendance':
|
||||
await fetchTodaysAttendance(projectId);
|
||||
break;
|
||||
case 'attendanceLogs':
|
||||
await fetchAttendanceLogs(
|
||||
projectId,
|
||||
dateFrom: startDateAttendance.value,
|
||||
dateTo: endDateAttendance.value,
|
||||
);
|
||||
break;
|
||||
case 'regularizationRequests':
|
||||
await fetchRegularizationLogs(projectId);
|
||||
break;
|
||||
}
|
||||
|
||||
logSafe(
|
||||
'Project data fetched for project ID: $projectId, tab: $selectedTab',
|
||||
);
|
||||
update();
|
||||
}
|
||||
|
||||
// ------------------ UI Interaction ------------------
|
||||
Future<void> selectDateRangeForAttendance(
|
||||
BuildContext context,
|
||||
AttendanceController controller,
|
||||
) async {
|
||||
final DateTime today = DateTime.now();
|
||||
|
||||
final DateTimeRange? picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2022),
|
||||
lastDate: today.subtract(const Duration(days: 1)),
|
||||
initialDateRange: DateTimeRange(
|
||||
start: startDateAttendance.value,
|
||||
end: endDateAttendance.value,
|
||||
),
|
||||
);
|
||||
|
||||
if (picked != null) {
|
||||
startDateAttendance.value = picked.start;
|
||||
endDateAttendance.value = picked.end;
|
||||
|
||||
logSafe(
|
||||
'Date range selected: ${startDateAttendance.value} to ${endDateAttendance.value}',
|
||||
);
|
||||
|
||||
await controller.fetchAttendanceLogs(
|
||||
Get.find<ProjectController>().selectedProject?.id,
|
||||
dateFrom: picked.start,
|
||||
dateTo: picked.end,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,16 +1,20 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/services/auth_service.dart';
|
||||
import 'package:marco/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:marco/helpers/widgets/my_validators.dart';
|
||||
import 'package:marco/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_validators.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
|
||||
|
||||
class ForgotPasswordController extends MyController {
|
||||
MyFormValidator basicValidator = MyFormValidator();
|
||||
bool showPassword = false;
|
||||
final MyFormValidator basicValidator = MyFormValidator();
|
||||
final RxBool isLoading = false.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
basicValidator.addField(
|
||||
'email',
|
||||
required: true,
|
||||
@ -18,49 +22,49 @@ class ForgotPasswordController extends MyController {
|
||||
validators: [MyEmailValidator()],
|
||||
controller: TextEditingController(text: "demo@example.com"),
|
||||
);
|
||||
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future<void> onLogin() async {
|
||||
if (basicValidator.validateForm()) {
|
||||
update();
|
||||
var errors = await AuthService.loginUser(basicValidator.getData());
|
||||
if (errors != null) {
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
}
|
||||
Get.toNamed('/auth/reset_password');
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
/// New: Forgot password function
|
||||
Future<void> onForgotPassword() async {
|
||||
if (basicValidator.validateForm()) {
|
||||
update();
|
||||
final data = basicValidator.getData();
|
||||
final email = data['email']?.toString() ?? '';
|
||||
if (!basicValidator.validateForm()) return;
|
||||
|
||||
isLoading.value = true;
|
||||
final data = basicValidator.getData();
|
||||
final email = data['email']?.toString() ?? '';
|
||||
|
||||
try {
|
||||
logSafe("Forgot password requested for: $email", );
|
||||
|
||||
final result = await AuthService.forgotPassword(email);
|
||||
|
||||
if (result != null) {
|
||||
if (result == null) {
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Your password reset link was sent.",
|
||||
message: "Password reset link has been sent.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
await LocalStorage.logout();
|
||||
} else {
|
||||
final errorMessage = result['error'] ?? "Failed to send reset link. Please try again.";
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Your password reset link was sent.",
|
||||
type: SnackbarType.success,
|
||||
title: "Failed",
|
||||
message: errorMessage,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
logSafe("Failed to send reset password email for $email: $errorMessage", level: LogLevel.warning, );
|
||||
}
|
||||
update();
|
||||
} catch (e, stacktrace) {
|
||||
logSafe("Error during forgot password", level: LogLevel.error, error: e, stackTrace: stacktrace);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong. Please try again later.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void gotoLogIn() {
|
||||
Get.toNamed('/auth/login');
|
||||
Get.offAllNamed('/auth/login-option');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/services/auth_service.dart';
|
||||
import 'package:marco/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:marco/helpers/widgets/my_validators.dart';
|
||||
import 'package:marco/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_validators.dart';
|
||||
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class LoginController extends MyController {
|
||||
final MyFormValidator basicValidator = MyFormValidator();
|
||||
@ -13,6 +14,7 @@ class LoginController extends MyController {
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxBool showPassword = false.obs;
|
||||
final RxBool isChecked = false.obs;
|
||||
final RxBool showSplash = false.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
@ -34,65 +36,73 @@ class LoginController extends MyController {
|
||||
'password',
|
||||
required: true,
|
||||
label: "Password",
|
||||
validators: [MyLengthValidator(min: 6, max: 10)],
|
||||
validators: [MyLengthValidator(min: 6)],
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
}
|
||||
|
||||
void onChangeCheckBox(bool? value) {
|
||||
isChecked.value = value ?? isChecked.value;
|
||||
}
|
||||
void onChangeCheckBox(bool? value) => isChecked.value = value ?? false;
|
||||
|
||||
void onChangeShowPassword() {
|
||||
showPassword.toggle();
|
||||
}
|
||||
void onChangeShowPassword() => showPassword.toggle();
|
||||
|
||||
Future<void> onLogin() async {
|
||||
if (!basicValidator.validateForm()) return;
|
||||
|
||||
isLoading.value = true;
|
||||
showSplash.value = true;
|
||||
|
||||
final errors = await AuthService.loginUser(basicValidator.getData());
|
||||
try {
|
||||
final loginData = basicValidator.getData();
|
||||
logSafe("Attempting login for user: ${loginData['username']}");
|
||||
|
||||
if (errors != null) {
|
||||
final errors = await AuthService.loginUser(loginData);
|
||||
|
||||
if (errors != null) {
|
||||
showAppSnackbar(
|
||||
title: "Login Failed",
|
||||
message: "Username or password is incorrect",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
basicValidator.addErrors(errors);
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
} else {
|
||||
await _handleRememberMe();
|
||||
enableRemoteLogging();
|
||||
logSafe("Login successful for user: ${loginData['username']}");
|
||||
Get.offNamed('/select-tenant');
|
||||
}
|
||||
} catch (e, stacktrace) {
|
||||
showAppSnackbar(
|
||||
title: "Login Failed",
|
||||
message: "Username or password is incorrect",
|
||||
title: "Login Error",
|
||||
message: "An unexpected error occurred",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
|
||||
basicValidator.addErrors(errors);
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
} else {
|
||||
await _handleRememberMe();
|
||||
|
||||
final currentRoute = ModalRoute.of(Get.context!)?.settings.name ?? "";
|
||||
final nextUrl = Uri.parse(currentRoute).queryParameters['next'] ?? "/home";
|
||||
Get.toNamed(nextUrl);
|
||||
logSafe("Exception during login",
|
||||
level: LogLevel.error, error: e, stackTrace: stacktrace);
|
||||
} finally {
|
||||
showSplash.value = false;
|
||||
}
|
||||
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
Future<void> _handleRememberMe() async {
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
if (isChecked.value) {
|
||||
await prefs.setString('username', basicValidator.getController('username')!.text);
|
||||
await prefs.setString('password', basicValidator.getController('password')!.text);
|
||||
await prefs.setBool('remember_me', true);
|
||||
await LocalStorage.setToken(
|
||||
'username', basicValidator.getController('username')!.text);
|
||||
await LocalStorage.setToken(
|
||||
'password', basicValidator.getController('password')!.text);
|
||||
await LocalStorage.setBool('remember_me', true);
|
||||
} else {
|
||||
await prefs.remove('username');
|
||||
await prefs.remove('password');
|
||||
await prefs.setBool('remember_me', false);
|
||||
await LocalStorage.removeToken('username');
|
||||
await LocalStorage.removeToken('password');
|
||||
await LocalStorage.setBool('remember_me', false);
|
||||
basicValidator.clearErrors();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadSavedCredentials() async {
|
||||
SharedPreferences prefs = await SharedPreferences.getInstance();
|
||||
final savedUsername = prefs.getString('username');
|
||||
final savedPassword = prefs.getString('password');
|
||||
final remember = prefs.getBool('remember_me') ?? false;
|
||||
final savedUsername = LocalStorage.getToken('username');
|
||||
final savedPassword = LocalStorage.getToken('password');
|
||||
final remember = LocalStorage.getBool('remember_me') ?? false;
|
||||
|
||||
isChecked.value = remember;
|
||||
|
||||
@ -102,12 +112,7 @@ class LoginController extends MyController {
|
||||
}
|
||||
}
|
||||
|
||||
void goToForgotPassword() {
|
||||
Get.toNamed('/auth/forgot_password');
|
||||
}
|
||||
void goToForgotPassword() => Get.toNamed('/auth/forgot_password');
|
||||
|
||||
void gotoRegister() {
|
||||
Get.offAndToNamed('/auth/register_account');
|
||||
}
|
||||
void gotoRegister() => Get.offAndToNamed('/auth/register_account');
|
||||
}
|
||||
|
||||
|
||||
321
lib/controller/auth/mpin_controller.dart
Normal file
@ -0,0 +1,321 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/firebase/firebase_messaging_service.dart';
|
||||
import 'package:on_field_work/controller/permission_controller.dart';
|
||||
import 'package:on_field_work/controller/project_controller.dart';
|
||||
|
||||
class MPINController extends GetxController {
|
||||
final MyFormValidator basicValidator = MyFormValidator();
|
||||
final isNewUser = false.obs;
|
||||
final isChangeMpin = false.obs;
|
||||
final RxBool isLoading = false.obs;
|
||||
final formKey = GlobalKey<FormState>();
|
||||
|
||||
// Updated to 4-digit MPIN
|
||||
final digitControllers = List.generate(4, (_) => TextEditingController());
|
||||
final focusNodes = List.generate(4, (_) => FocusNode());
|
||||
|
||||
final retypeControllers = List.generate(4, (_) => TextEditingController());
|
||||
final retypeFocusNodes = List.generate(4, (_) => FocusNode());
|
||||
|
||||
final RxInt failedAttempts = 0.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
final bool hasMpin = LocalStorage.getIsMpin();
|
||||
isNewUser.value = !hasMpin;
|
||||
logSafe("onInit called. isNewUser: ${isNewUser.value}");
|
||||
}
|
||||
|
||||
/// Enable Change MPIN mode
|
||||
void setChangeMpinMode() {
|
||||
isChangeMpin.value = true;
|
||||
isNewUser.value = false;
|
||||
clearFields();
|
||||
clearRetypeFields();
|
||||
logSafe("setChangeMpinMode activated");
|
||||
}
|
||||
|
||||
/// Handle digit entry and focus movement
|
||||
void onDigitChanged(String value, int index, {bool isRetype = false}) {
|
||||
logSafe(
|
||||
"onDigitChanged -> index: $index, value: $value, isRetype: $isRetype");
|
||||
final nodes = isRetype ? retypeFocusNodes : focusNodes;
|
||||
if (value.isNotEmpty && index < 3) {
|
||||
nodes[index + 1].requestFocus();
|
||||
} else if (value.isEmpty && index > 0) {
|
||||
nodes[index - 1].requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit MPIN for verification or generation
|
||||
Future<void> onSubmitMPIN() async {
|
||||
logSafe("onSubmitMPIN triggered");
|
||||
|
||||
if (!formKey.currentState!.validate()) {
|
||||
logSafe("Form validation failed", level: LogLevel.warning);
|
||||
return;
|
||||
}
|
||||
|
||||
final enteredMPIN = digitControllers.map((c) => c.text).join();
|
||||
logSafe("Entered MPIN: $enteredMPIN");
|
||||
|
||||
if (enteredMPIN.length < 4) {
|
||||
_showError("Please enter all 4 digits.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNewUser.value || isChangeMpin.value) {
|
||||
final retypeMPIN = retypeControllers.map((c) => c.text).join();
|
||||
logSafe("Retyped MPIN: $retypeMPIN");
|
||||
|
||||
if (retypeMPIN.length < 4) {
|
||||
_showError("Please enter all 4 digits in Retype MPIN.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (enteredMPIN != retypeMPIN) {
|
||||
_showError("MPIN and Retype MPIN do not match.");
|
||||
clearFields();
|
||||
clearRetypeFields();
|
||||
return;
|
||||
}
|
||||
|
||||
final bool success = await generateMPIN(mpin: enteredMPIN);
|
||||
|
||||
if (success) {
|
||||
logSafe("MPIN generation/change successful.");
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: isChangeMpin.value
|
||||
? "MPIN changed successfully."
|
||||
: "MPIN generated successfully. Please login again.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
await LocalStorage.logout();
|
||||
} else {
|
||||
logSafe("MPIN generation/change failed.", level: LogLevel.warning);
|
||||
clearFields();
|
||||
clearRetypeFields();
|
||||
}
|
||||
} else {
|
||||
logSafe("Existing user. Proceeding to verify MPIN.");
|
||||
await verifyMPIN();
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgot MPIN
|
||||
Future<void> onForgotMPIN() async {
|
||||
logSafe("onForgotMPIN called");
|
||||
isNewUser.value = true;
|
||||
isChangeMpin.value = false;
|
||||
clearFields();
|
||||
clearRetypeFields();
|
||||
}
|
||||
|
||||
/// Switch to login/enter MPIN screen
|
||||
void switchToEnterMPIN() {
|
||||
logSafe("switchToEnterMPIN called");
|
||||
isNewUser.value = false;
|
||||
isChangeMpin.value = false;
|
||||
clearFields();
|
||||
clearRetypeFields();
|
||||
}
|
||||
|
||||
/// Show error snackbar
|
||||
void _showError(String message) {
|
||||
logSafe("ERROR: $message", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: message,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
|
||||
/// Navigate to dashboard
|
||||
/// Navigate to tenant selection after MPIN verification
|
||||
void _navigateToTenantSelection({String? message}) {
|
||||
if (message != null) {
|
||||
logSafe("Navigating to Tenant Selection with message: $message");
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: message,
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
}
|
||||
Get.offAllNamed('/select-tenant');
|
||||
}
|
||||
|
||||
/// Clear the primary MPIN fields
|
||||
void clearFields() {
|
||||
logSafe("clearFields called");
|
||||
for (final c in digitControllers) {
|
||||
c.clear();
|
||||
}
|
||||
focusNodes.first.requestFocus();
|
||||
}
|
||||
|
||||
/// Clear the retype MPIN fields
|
||||
void clearRetypeFields() {
|
||||
logSafe("clearRetypeFields called");
|
||||
for (final c in retypeControllers) {
|
||||
c.clear();
|
||||
}
|
||||
retypeFocusNodes.first.requestFocus();
|
||||
}
|
||||
|
||||
/// Cleanup
|
||||
@override
|
||||
void onClose() {
|
||||
logSafe("onClose called");
|
||||
for (final controller in digitControllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
for (final node in focusNodes) {
|
||||
node.dispose();
|
||||
}
|
||||
for (final controller in retypeControllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
for (final node in retypeFocusNodes) {
|
||||
node.dispose();
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
/// Generate MPIN for new user/change MPIN
|
||||
Future<bool> generateMPIN({required String mpin}) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
logSafe("generateMPIN started");
|
||||
|
||||
final employeeInfo = LocalStorage.getEmployeeInfo();
|
||||
final String? employeeId = employeeInfo?.id;
|
||||
|
||||
if (employeeId == null || employeeId.isEmpty) {
|
||||
isLoading.value = false;
|
||||
_showError("Missing employee ID.");
|
||||
return false;
|
||||
}
|
||||
|
||||
logSafe("Calling AuthService.generateMpin for employeeId: $employeeId");
|
||||
|
||||
final response = await AuthService.generateMpin(
|
||||
employeeId: employeeId,
|
||||
mpin: mpin,
|
||||
);
|
||||
|
||||
isLoading.value = false;
|
||||
|
||||
if (response == null) {
|
||||
return true;
|
||||
} else {
|
||||
logSafe("MPIN generation returned error: $response",
|
||||
level: LogLevel.warning);
|
||||
showAppSnackbar(
|
||||
title: "MPIN Operation Failed",
|
||||
message: "Please check your inputs.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
basicValidator.addErrors(response);
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
isLoading.value = false;
|
||||
logSafe("Exception in generateMPIN", level: LogLevel.error, error: e);
|
||||
_showError("Failed to process MPIN.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify MPIN for existing user
|
||||
Future<void> verifyMPIN() async {
|
||||
logSafe("verifyMPIN triggered");
|
||||
|
||||
final enteredMPIN = digitControllers.map((c) => c.text).join();
|
||||
if (enteredMPIN.length < 4) {
|
||||
_showError("Please enter all 4 digits.");
|
||||
return;
|
||||
}
|
||||
|
||||
final mpinToken = await LocalStorage.getMpinToken();
|
||||
if (mpinToken == null || mpinToken.isEmpty) {
|
||||
_showError("Missing MPIN token. Please log in again.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isLoading.value = true;
|
||||
|
||||
final fcmToken = await FirebaseNotificationService().getFcmToken();
|
||||
|
||||
final response = await AuthService.verifyMpin(
|
||||
mpin: enteredMPIN,
|
||||
mpinToken: mpinToken,
|
||||
fcmToken: fcmToken ?? '',
|
||||
);
|
||||
|
||||
isLoading.value = false;
|
||||
|
||||
if (response == null) {
|
||||
logSafe("MPIN verified successfully");
|
||||
await LocalStorage.setBool('mpin_verified', true);
|
||||
|
||||
// 🔹 Ensure controllers are injected and loaded
|
||||
final token = await LocalStorage.getJwtToken();
|
||||
if (token != null && token.isNotEmpty) {
|
||||
if (!Get.isRegistered<PermissionController>()) {
|
||||
Get.put(PermissionController());
|
||||
await Get.find<PermissionController>().loadData(token);
|
||||
}
|
||||
if (!Get.isRegistered<ProjectController>()) {
|
||||
Get.put(ProjectController(), permanent: true);
|
||||
await Get.find<ProjectController>().fetchProjects();
|
||||
}
|
||||
}
|
||||
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "MPIN Verified Successfully",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
_navigateToTenantSelection();
|
||||
} else {
|
||||
final errorMessage = response["error"] ?? "Invalid MPIN";
|
||||
logSafe("MPIN verification failed: $errorMessage",
|
||||
level: LogLevel.warning);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: errorMessage,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
clearFields();
|
||||
onInvalidMPIN();
|
||||
}
|
||||
} catch (e) {
|
||||
isLoading.value = false;
|
||||
logSafe("Exception in verifyMPIN", level: LogLevel.error, error: e);
|
||||
_showError("Something went wrong. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Increment failed attempts and warn
|
||||
void onInvalidMPIN() {
|
||||
failedAttempts.value++;
|
||||
if (failedAttempts.value >= 3) {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Too many failed attempts. Consider logging in again.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
217
lib/controller/auth/otp_controller.dart
Normal file
@ -0,0 +1,217 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class OTPController extends GetxController {
|
||||
final formKey = GlobalKey<FormState>();
|
||||
|
||||
final RxString email = ''.obs;
|
||||
final RxBool isOTPSent = false.obs;
|
||||
final RxBool isSending = false.obs;
|
||||
final RxBool isResending = false.obs;
|
||||
final RxInt timer = 0.obs;
|
||||
Timer? _countdownTimer;
|
||||
|
||||
final TextEditingController emailController = TextEditingController();
|
||||
final List<TextEditingController> otpControllers =
|
||||
List.generate(4, (_) => TextEditingController());
|
||||
final List<FocusNode> focusNodes = List.generate(4, (_) => FocusNode());
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
timer.value = 0;
|
||||
_loadSavedEmail();
|
||||
logSafe("[OTPController] Initialized");
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_countdownTimer?.cancel();
|
||||
emailController.dispose();
|
||||
for (final controller in otpControllers) {
|
||||
controller.dispose();
|
||||
}
|
||||
for (final node in focusNodes) {
|
||||
node.dispose();
|
||||
}
|
||||
logSafe("[OTPController] Disposed");
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
Future<bool> _sendOTP(String email) async {
|
||||
logSafe("[OTPController] Sending OTP");
|
||||
final result = await AuthService.generateOtp(email);
|
||||
if (result == null) {
|
||||
logSafe("[OTPController] OTP sent successfully");
|
||||
return true;
|
||||
} else {
|
||||
logSafe(
|
||||
"[OTPController] OTP send failed",
|
||||
level: LogLevel.warning,
|
||||
error: result['error'],
|
||||
);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: result['error'] ?? "Failed to send OTP",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sendOTP() async {
|
||||
final userEmail = emailController.text.trim();
|
||||
logSafe("[OTPController] sendOTP called");
|
||||
|
||||
if (!_validateEmail(userEmail)) {
|
||||
logSafe("[OTPController] Invalid email format", level: LogLevel.warning);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Please enter a valid email address",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSending.value) return;
|
||||
isSending.value = true;
|
||||
|
||||
final success = await _sendOTP(userEmail);
|
||||
if (success) {
|
||||
email.value = userEmail;
|
||||
isOTPSent.value = true;
|
||||
await _saveEmailIfRemembered(userEmail);
|
||||
_startTimer();
|
||||
_clearOTPFields();
|
||||
}
|
||||
|
||||
isSending.value = false;
|
||||
}
|
||||
|
||||
Future<void> onResendOTP() async {
|
||||
if (isResending.value) return;
|
||||
logSafe("[OTPController] Resending OTP");
|
||||
|
||||
isResending.value = true;
|
||||
_clearOTPFields();
|
||||
|
||||
final success = await _sendOTP(email.value);
|
||||
if (success) {
|
||||
_startTimer();
|
||||
}
|
||||
|
||||
isResending.value = false;
|
||||
}
|
||||
|
||||
void onOTPChanged(String value, int index) {
|
||||
logSafe("[OTPController] OTP field changed: index=$index",
|
||||
level: LogLevel.debug);
|
||||
if (value.isNotEmpty) {
|
||||
if (index < otpControllers.length - 1) {
|
||||
focusNodes[index + 1].requestFocus();
|
||||
} else {
|
||||
focusNodes[index].unfocus();
|
||||
}
|
||||
} else {
|
||||
if (index > 0) {
|
||||
focusNodes[index - 1].requestFocus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyOTP() async {
|
||||
final enteredOTP = otpControllers.map((c) => c.text).join();
|
||||
final result = await AuthService.verifyOtp(
|
||||
email: email.value,
|
||||
otp: enteredOTP,
|
||||
);
|
||||
|
||||
if (result == null) {
|
||||
// ✅ Handle remember-me like in LoginController
|
||||
final remember = LocalStorage.getBool('remember_me') ?? false;
|
||||
if (remember) await LocalStorage.setToken('otp_email', email.value);
|
||||
|
||||
// ✅ Enable remote logging
|
||||
enableRemoteLogging();
|
||||
|
||||
Get.offAllNamed('/select-tenant');
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: result['error']!,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _clearOTPFields() {
|
||||
logSafe("[OTPController] Clearing OTP input fields", level: LogLevel.debug);
|
||||
for (final controller in otpControllers) {
|
||||
controller.clear();
|
||||
}
|
||||
focusNodes[0].requestFocus();
|
||||
}
|
||||
|
||||
void _startTimer() {
|
||||
logSafe("[OTPController] Starting resend timer");
|
||||
timer.value = 60;
|
||||
_countdownTimer?.cancel();
|
||||
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
|
||||
if (this.timer.value > 0) {
|
||||
this.timer.value--;
|
||||
} else {
|
||||
timer.cancel();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void resetForChangeEmail() {
|
||||
logSafe("[OTPController] Resetting OTP form for change email");
|
||||
|
||||
isOTPSent.value = false;
|
||||
email.value = '';
|
||||
emailController.clear();
|
||||
_clearOTPFields();
|
||||
|
||||
timer.value = 0;
|
||||
isSending.value = false;
|
||||
isResending.value = false;
|
||||
|
||||
for (final node in focusNodes) {
|
||||
node.unfocus();
|
||||
}
|
||||
|
||||
// Optionally remove saved email
|
||||
LocalStorage.removeToken('otp_email');
|
||||
}
|
||||
|
||||
bool _validateEmail(String email) {
|
||||
final regex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,}$');
|
||||
return regex.hasMatch(email);
|
||||
}
|
||||
|
||||
/// Save email to local storage if "remember me" is set
|
||||
Future<void> _saveEmailIfRemembered(String email) async {
|
||||
final remember = LocalStorage.getBool('remember_me') ?? false;
|
||||
if (remember) {
|
||||
await LocalStorage.setToken('otp_email', email);
|
||||
}
|
||||
}
|
||||
|
||||
/// Load email from local storage if "remember me" is true
|
||||
Future<void> _loadSavedEmail() async {
|
||||
final remember = LocalStorage.getBool('remember_me') ?? false;
|
||||
if (remember) {
|
||||
final savedEmail = LocalStorage.getToken('otp_email') ?? '';
|
||||
emailController.text = savedEmail;
|
||||
email.value = savedEmail;
|
||||
logSafe(
|
||||
"[OTPController] Loaded saved email from local storage: $savedEmail");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,18 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:marco/helpers/widgets/my_validators.dart';
|
||||
|
||||
import 'package:marco/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_validators.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class RegisterAccountController extends MyController {
|
||||
MyFormValidator basicValidator = MyFormValidator();
|
||||
|
||||
bool showPassword = false;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
logSafe("[RegisterAccountController] onInit called");
|
||||
|
||||
basicValidator.addField(
|
||||
'email',
|
||||
required: true,
|
||||
@ -38,29 +39,40 @@ class RegisterAccountController extends MyController {
|
||||
validators: [MyLengthValidator(min: 6, max: 10)],
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
Future<void> onLogin() async {
|
||||
if (basicValidator.validateForm()) {
|
||||
update();
|
||||
var errors = await AuthService.loginUser(basicValidator.getData());
|
||||
final data = basicValidator.getData();
|
||||
logSafe("[RegisterAccountController] Submitting registration data");
|
||||
|
||||
final errors = await AuthService.loginUser(data);
|
||||
if (errors != null) {
|
||||
logSafe("[RegisterAccountController] Login errors: $errors", level: LogLevel.warning);
|
||||
basicValidator.addErrors(errors);
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
}
|
||||
|
||||
logSafe("[RegisterAccountController] Redirecting to /starter");
|
||||
Get.toNamed('/starter');
|
||||
update();
|
||||
} else {
|
||||
logSafe("[RegisterAccountController] Validation failed", level: LogLevel.warning);
|
||||
}
|
||||
}
|
||||
|
||||
void onChangeShowPassword() {
|
||||
showPassword = !showPassword;
|
||||
logSafe("[RegisterAccountController] showPassword toggled: $showPassword");
|
||||
update();
|
||||
}
|
||||
|
||||
void gotoLogin() {
|
||||
Get.toNamed('/auth/login');
|
||||
logSafe("[RegisterAccountController] Navigating to /auth/login-option");
|
||||
Get.toNamed('/auth/login-option');
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,59 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/services/auth_service.dart';
|
||||
import 'package:marco/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:marco/helpers/widgets/my_validators.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/auth_service.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_validators.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class ResetPasswordController extends MyController {
|
||||
MyFormValidator basicValidator = MyFormValidator();
|
||||
bool showPassword = false;
|
||||
|
||||
bool confirmPassword = false;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
logSafe("[ResetPasswordController] onInit called");
|
||||
|
||||
basicValidator.addField(
|
||||
'password',
|
||||
required: true,
|
||||
validators: [
|
||||
MyLengthValidator(min: 6, max: 10),
|
||||
],
|
||||
validators: [MyLengthValidator(min: 6, max: 10)],
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
|
||||
basicValidator.addField(
|
||||
'confirm_password',
|
||||
required: true,
|
||||
label: "Confirm password",
|
||||
validators: [
|
||||
MyLengthValidator(min: 6, max: 10),
|
||||
],
|
||||
validators: [MyLengthValidator(min: 6, max: 10)],
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> onResetPassword() async {
|
||||
logSafe("[ResetPasswordController] onResetPassword triggered");
|
||||
|
||||
if (basicValidator.validateForm()) {
|
||||
final data = basicValidator.getData();
|
||||
logSafe("[ResetPasswordController] Reset password form data");
|
||||
|
||||
update();
|
||||
var errors = await AuthService.loginUser(basicValidator.getData());
|
||||
|
||||
final errors = await AuthService.loginUser(data); // Consider renaming this to resetPassword() for clarity
|
||||
if (errors != null) {
|
||||
logSafe("[ResetPasswordController] Received errors: $errors", level: LogLevel.warning);
|
||||
basicValidator.addErrors(errors);
|
||||
basicValidator.validateForm();
|
||||
basicValidator.clearErrors();
|
||||
}
|
||||
Get.toNamed('/home');
|
||||
|
||||
logSafe("[ResetPasswordController] Navigating to /dashboard");
|
||||
Get.toNamed('/dashboard');
|
||||
update();
|
||||
} else {
|
||||
logSafe("[ResetPasswordController] Form validation failed", level: LogLevel.warning);
|
||||
}
|
||||
}
|
||||
|
||||
void onChangeShowPassword() {
|
||||
showPassword = !showPassword;
|
||||
logSafe("[ResetPasswordController] showPassword toggled: $showPassword");
|
||||
update();
|
||||
}
|
||||
|
||||
void onConfirmPassword() {
|
||||
confirmPassword = !confirmPassword;
|
||||
logSafe("[ResetPasswordController] confirmPassword toggled: $confirmPassword");
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,162 +0,0 @@
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:marco/helpers/services/api_service.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:marco/helpers/widgets/my_snackbar.dart';
|
||||
|
||||
enum Gender {
|
||||
male,
|
||||
female,
|
||||
other;
|
||||
|
||||
const Gender();
|
||||
}
|
||||
|
||||
final Logger logger = Logger();
|
||||
|
||||
class AddEmployeeController extends MyController {
|
||||
List<PlatformFile> files = [];
|
||||
MyFormValidator basicValidator = MyFormValidator();
|
||||
Gender? selectedGender;
|
||||
List<Map<String, dynamic>> roles = [];
|
||||
String? selectedRoleId;
|
||||
final List<Map<String, String>> countries = [
|
||||
{"code": "+91", "name": "India"},
|
||||
{"code": "+1", "name": "USA"},
|
||||
{"code": "+971", "name": "UAE"},
|
||||
{"code": "+44", "name": "UK"},
|
||||
{"code": "+81", "name": "Japan"},
|
||||
{"code": "+61", "name": "Australia"},
|
||||
{"code": "+49", "name": "Germany"},
|
||||
{"code": "+33", "name": "France"},
|
||||
{"code": "+86", "name": "China"},
|
||||
];
|
||||
|
||||
final Map<String, int> minDigitsPerCountry = {
|
||||
"+91": 10,
|
||||
"+1": 10,
|
||||
"+971": 9,
|
||||
"+44": 10,
|
||||
"+81": 10,
|
||||
"+61": 9,
|
||||
"+49": 10,
|
||||
"+33": 9,
|
||||
"+86": 11,
|
||||
};
|
||||
|
||||
final Map<String, int> maxDigitsPerCountry = {
|
||||
"+91": 10,
|
||||
"+1": 10,
|
||||
"+971": 9,
|
||||
"+44": 11,
|
||||
"+81": 10,
|
||||
"+61": 9,
|
||||
"+49": 11,
|
||||
"+33": 9,
|
||||
"+86": 11,
|
||||
};
|
||||
String selectedCountryCode = "+91";
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
logger.i("Initializing AddEmployeeController...");
|
||||
fetchRoles();
|
||||
basicValidator.addField(
|
||||
'first_name',
|
||||
label: "First Name",
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
basicValidator.addField(
|
||||
'phone_number',
|
||||
label: "Phone Number",
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
basicValidator.addField(
|
||||
'last_name',
|
||||
label: "Last Name",
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
logger.i("Fields initialized for first_name, phone_number, last_name.");
|
||||
}
|
||||
|
||||
bool showOnline = true;
|
||||
|
||||
final List<String> categories = [];
|
||||
|
||||
void onGenderSelected(Gender? gender) {
|
||||
selectedGender = gender;
|
||||
logger.i("Gender selected: ${gender?.name}");
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> fetchRoles() async {
|
||||
logger.i("Fetching roles...");
|
||||
final result = await ApiService.getRoles();
|
||||
if (result != null) {
|
||||
roles = List<Map<String, dynamic>>.from(result);
|
||||
logger.i("Roles fetched successfully.");
|
||||
update();
|
||||
} else {
|
||||
logger.e("Failed to fetch roles.");
|
||||
}
|
||||
}
|
||||
|
||||
void onRoleSelected(String? roleId) {
|
||||
selectedRoleId = roleId;
|
||||
logger.i("Role selected: $roleId");
|
||||
update();
|
||||
}
|
||||
|
||||
Future<bool> createEmployees() async {
|
||||
logger.i("Starting employee creation...");
|
||||
if (selectedGender == null || selectedRoleId == null) {
|
||||
logger.w("Missing gender or role.");
|
||||
showAppSnackbar(
|
||||
title: "Missing Fields",
|
||||
message: "Please select both Gender and Role.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
final firstName = basicValidator.getController("first_name")?.text.trim();
|
||||
final lastName = basicValidator.getController("last_name")?.text.trim();
|
||||
final phoneNumber =
|
||||
basicValidator.getController("phone_number")?.text.trim();
|
||||
|
||||
logger.i(
|
||||
"Creating employee with Name: $firstName $lastName, Phone: $phoneNumber, Gender: ${selectedGender!.name}");
|
||||
|
||||
final response = await ApiService.createEmployee(
|
||||
firstName: firstName!,
|
||||
lastName: lastName!,
|
||||
phoneNumber: phoneNumber!,
|
||||
gender: selectedGender!.name,
|
||||
jobRoleId: selectedRoleId!,
|
||||
);
|
||||
|
||||
if (response == true) {
|
||||
logger.i("Employee created successfully.");
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Employee created successfully!",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
return true;
|
||||
} else {
|
||||
logger.e("Failed to create employee.");
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to create employee.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,52 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/visitor_by_channels_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class AnalyticsController extends MyController {
|
||||
String selectActivity = "Year";
|
||||
List<VisitorByChannelsModel> visitorByChannel = [];
|
||||
final TooltipBehavior columnChartToolTip = TooltipBehavior(enable: true, format: 'point.x : point.y', tooltipPosition: TooltipPosition.pointer);
|
||||
final TooltipBehavior audienceOverview = TooltipBehavior(enable: true, format: 'point.x : point.y', tooltipPosition: TooltipPosition.pointer);
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
VisitorByChannelsModel.dummyList.then((value) {
|
||||
visitorByChannel = value;
|
||||
update();
|
||||
});
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void onSelectedActivity(String time) {
|
||||
selectActivity = time;
|
||||
update();
|
||||
}
|
||||
|
||||
void removeData(index) {
|
||||
visitorByChannel.removeAt(index);
|
||||
update();
|
||||
}
|
||||
|
||||
final List<ChartSampleData> columnChart = <ChartSampleData>[
|
||||
ChartSampleData(x: 2010, y: 32, yValue: 50),
|
||||
ChartSampleData(x: 2011, y: 44, yValue: 40),
|
||||
ChartSampleData(x: 2012, y: 40, yValue: 60),
|
||||
ChartSampleData(x: 2013, y: 50, yValue: 38),
|
||||
ChartSampleData(x: 2014, y: 10, yValue: 28),
|
||||
ChartSampleData(x: 2015, y: 20, yValue: 16),
|
||||
ChartSampleData(x: 2016, y: 30, yValue: 50),
|
||||
];
|
||||
|
||||
final List<ChartSampleData> audienceOverviewChart = [
|
||||
ChartSampleData(x: 2018, y: 50, yValue: 38),
|
||||
ChartSampleData(x: 2019, y: 10, yValue: 28),
|
||||
ChartSampleData(x: 2020, y: 32, yValue: 50),
|
||||
ChartSampleData(x: 2020, y: 44, yValue: 40),
|
||||
ChartSampleData(x: 2020, y: 40, yValue: 60),
|
||||
ChartSampleData(x: 2020, y: 50, yValue: 38),
|
||||
ChartSampleData(x: 2021, y: 10, yValue: 28),
|
||||
ChartSampleData(x: 2022, y: 20, yValue: 16),
|
||||
ChartSampleData(x: 2023, y: 30, yValue: 50)
|
||||
];
|
||||
}
|
||||
@ -1,394 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
|
||||
import 'package:marco/helpers/services/api_service.dart';
|
||||
import 'package:marco/helpers/widgets/my_image_compressor.dart';
|
||||
import 'package:marco/model/attendance_model.dart';
|
||||
import 'package:marco/model/project_model.dart';
|
||||
import 'package:marco/model/employee_model.dart';
|
||||
import 'package:marco/model/attendance_log_model.dart';
|
||||
import 'package:marco/model/regularization_log_model.dart';
|
||||
import 'package:marco/model/attendance_log_view_model.dart';
|
||||
|
||||
final Logger log = Logger();
|
||||
|
||||
class AttendanceController extends GetxController {
|
||||
// Data lists
|
||||
List<AttendanceModel> attendances = [];
|
||||
List<ProjectModel> projects = [];
|
||||
List<EmployeeModel> employees = [];
|
||||
List<AttendanceLogModel> attendanceLogs = [];
|
||||
List<RegularizationLogModel> regularizationLogs = [];
|
||||
List<AttendanceLogViewModel> attendenceLogsView = [];
|
||||
|
||||
// Selected values
|
||||
String? selectedProjectId;
|
||||
String selectedTab = 'Employee List';
|
||||
|
||||
// Date range for attendance filtering
|
||||
DateTime? startDateAttendance;
|
||||
DateTime? endDateAttendance;
|
||||
|
||||
// Loading states
|
||||
RxBool isLoading = true.obs;
|
||||
RxBool isLoadingProjects = true.obs;
|
||||
RxBool isLoadingEmployees = true.obs;
|
||||
RxBool isLoadingAttendanceLogs = true.obs;
|
||||
RxBool isLoadingRegularizationLogs = true.obs;
|
||||
RxBool isLoadingLogView = true.obs;
|
||||
|
||||
// Uploading state per employee (keyed by employeeId)
|
||||
RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_initializeDefaults();
|
||||
}
|
||||
|
||||
void _initializeDefaults() {
|
||||
_setDefaultDateRange();
|
||||
fetchProjects();
|
||||
}
|
||||
|
||||
void _setDefaultDateRange() {
|
||||
final today = DateTime.now();
|
||||
startDateAttendance = today.subtract(const Duration(days: 7));
|
||||
endDateAttendance = today.subtract(const Duration(days: 1));
|
||||
log.i("Default date range set: $startDateAttendance to $endDateAttendance");
|
||||
}
|
||||
|
||||
/// Checks and requests location permission, returns true if granted.
|
||||
Future<bool> _handleLocationPermission() async {
|
||||
LocationPermission permission = await Geolocator.checkPermission();
|
||||
|
||||
if (permission == LocationPermission.denied) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
log.w('Location permissions are denied');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (permission == LocationPermission.deniedForever) {
|
||||
log.e('Location permissions are permanently denied');
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Fetches projects and initializes selected project.
|
||||
Future<void> fetchProjects() async {
|
||||
isLoadingProjects.value = true;
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getProjects();
|
||||
|
||||
if (response != null && response.isNotEmpty) {
|
||||
projects = response.map((json) => ProjectModel.fromJson(json)).toList();
|
||||
selectedProjectId = projects.first.id.toString();
|
||||
log.i("Projects fetched: ${projects.length}");
|
||||
|
||||
await fetchProjectData(selectedProjectId);
|
||||
} else {
|
||||
log.w("No projects found or API call failed.");
|
||||
}
|
||||
|
||||
isLoadingProjects.value = false;
|
||||
isLoading.value = false;
|
||||
|
||||
update(['attendance_dashboard_controller']);
|
||||
}
|
||||
|
||||
/// Fetches employees, attendance logs and regularization logs for a project.
|
||||
Future<void> fetchProjectData(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoading.value = true;
|
||||
|
||||
await Future.wait([
|
||||
fetchEmployeesByProject(projectId),
|
||||
fetchAttendanceLogs(projectId,
|
||||
dateFrom: startDateAttendance, dateTo: endDateAttendance),
|
||||
fetchRegularizationLogs(projectId),
|
||||
]);
|
||||
|
||||
isLoading.value = false;
|
||||
|
||||
log.i("Project data fetched for project ID: $projectId");
|
||||
}
|
||||
|
||||
/// Fetches employees for the given project.
|
||||
Future<void> fetchEmployeesByProject(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingEmployees.value = true;
|
||||
|
||||
final response = await ApiService.getEmployeesByProject(projectId);
|
||||
|
||||
if (response != null) {
|
||||
employees = response.map((json) => EmployeeModel.fromJson(json)).toList();
|
||||
|
||||
// Initialize uploading states for employees
|
||||
for (var emp in employees) {
|
||||
uploadingStates[emp.id] = false.obs;
|
||||
}
|
||||
|
||||
log.i("Employees fetched: ${employees.length} for project $projectId");
|
||||
update();
|
||||
} else {
|
||||
log.e("Failed to fetch employees for project $projectId");
|
||||
}
|
||||
|
||||
isLoadingEmployees.value = false;
|
||||
}
|
||||
|
||||
/// Captures image, gets location, and uploads attendance data.
|
||||
/// Returns true on success.
|
||||
Future<bool> captureAndUploadAttendance(
|
||||
String id,
|
||||
String employeeId,
|
||||
String projectId, {
|
||||
String comment = "Marked via mobile app",
|
||||
required int action,
|
||||
bool imageCapture = true,
|
||||
String? markTime,
|
||||
}) async {
|
||||
try {
|
||||
uploadingStates[employeeId]?.value = true;
|
||||
|
||||
XFile? image;
|
||||
if (imageCapture) {
|
||||
image = await ImagePicker().pickImage(
|
||||
source: ImageSource.camera,
|
||||
imageQuality: 80,
|
||||
);
|
||||
if (image == null) {
|
||||
log.w("Image capture cancelled.");
|
||||
uploadingStates[employeeId]?.value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
final compressedBytes = await compressImageToUnder100KB(File(image.path));
|
||||
if (compressedBytes == null) {
|
||||
log.e("Image compression failed.");
|
||||
uploadingStates[employeeId]?.value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
final compressedFile = await saveCompressedImageToFile(compressedBytes);
|
||||
image = XFile(compressedFile.path);
|
||||
}
|
||||
|
||||
final hasLocationPermission = await _handleLocationPermission();
|
||||
if (!hasLocationPermission) {
|
||||
uploadingStates[employeeId]?.value = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
final position = await Geolocator.getCurrentPosition(
|
||||
desiredAccuracy: LocationAccuracy.high,
|
||||
);
|
||||
|
||||
final imageName = imageCapture
|
||||
? ApiService.generateImageName(employeeId, employees.length + 1)
|
||||
: "";
|
||||
|
||||
final result = await ApiService.uploadAttendanceImage(
|
||||
id,
|
||||
employeeId,
|
||||
image,
|
||||
position.latitude,
|
||||
position.longitude,
|
||||
imageName: imageName,
|
||||
projectId: projectId,
|
||||
comment: comment,
|
||||
action: action,
|
||||
imageCapture: imageCapture,
|
||||
markTime: markTime,
|
||||
);
|
||||
|
||||
log.i("Attendance uploaded for $employeeId, action: $action");
|
||||
return result;
|
||||
} catch (e, stacktrace) {
|
||||
log.e("Error uploading attendance", error: e, stackTrace: stacktrace);
|
||||
return false;
|
||||
} finally {
|
||||
uploadingStates[employeeId]?.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a date range picker for attendance filtering and fetches logs on selection.
|
||||
Future<void> selectDateRangeForAttendance(
|
||||
BuildContext context,
|
||||
AttendanceController controller,
|
||||
) async {
|
||||
final today = DateTime.now();
|
||||
final todayDateOnly = DateTime(today.year, today.month, today.day);
|
||||
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2022),
|
||||
lastDate: todayDateOnly.subtract(const Duration(days: 1)),
|
||||
initialDateRange: DateTimeRange(
|
||||
start: startDateAttendance ?? today.subtract(const Duration(days: 7)),
|
||||
end: endDateAttendance ?? todayDateOnly.subtract(const Duration(days: 1)),
|
||||
),
|
||||
|
||||
builder: (BuildContext context, Widget? child) {
|
||||
return Center(
|
||||
child: SizedBox(
|
||||
width: 400,
|
||||
height: 500,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
colorScheme: ColorScheme.light(
|
||||
primary: const Color.fromARGB(255, 95, 132, 255),
|
||||
onPrimary: Colors.white,
|
||||
onSurface: Colors.teal.shade800,
|
||||
),
|
||||
textButtonTheme: TextButtonThemeData(
|
||||
style: TextButton.styleFrom(foregroundColor: Colors.teal),
|
||||
),
|
||||
dialogTheme: const DialogTheme(backgroundColor: Colors.white),
|
||||
),
|
||||
child: child!,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
if (picked != null) {
|
||||
startDateAttendance = picked.start;
|
||||
endDateAttendance = picked.end;
|
||||
|
||||
log.i("Date range selected: $startDateAttendance to $endDateAttendance");
|
||||
|
||||
await controller.fetchAttendanceLogs(
|
||||
controller.selectedProjectId,
|
||||
dateFrom: picked.start,
|
||||
dateTo: picked.end,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches attendance logs filtered by project and date range.
|
||||
Future<void> fetchAttendanceLogs(
|
||||
String? projectId, {
|
||||
DateTime? dateFrom,
|
||||
DateTime? dateTo,
|
||||
}) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingAttendanceLogs.value = true;
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getAttendanceLogs(
|
||||
projectId,
|
||||
dateFrom: dateFrom,
|
||||
dateTo: dateTo,
|
||||
);
|
||||
|
||||
if (response != null) {
|
||||
attendanceLogs =
|
||||
response.map((json) => AttendanceLogModel.fromJson(json)).toList();
|
||||
log.i("Attendance logs fetched: ${attendanceLogs.length}");
|
||||
update();
|
||||
} else {
|
||||
log.e("Failed to fetch attendance logs for project $projectId");
|
||||
}
|
||||
|
||||
isLoadingAttendanceLogs.value = false;
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
/// Groups attendance logs by check-in date formatted as 'dd MMM yyyy'.
|
||||
Map<String, List<AttendanceLogModel>> groupLogsByCheckInDate() {
|
||||
final groupedLogs = <String, List<AttendanceLogModel>>{};
|
||||
|
||||
for (var logItem in attendanceLogs) {
|
||||
final checkInDate = logItem.checkIn != null
|
||||
? DateFormat('dd MMM yyyy').format(logItem.checkIn!)
|
||||
: 'Unknown';
|
||||
|
||||
groupedLogs.putIfAbsent(checkInDate, () => []);
|
||||
groupedLogs[checkInDate]!.add(logItem);
|
||||
}
|
||||
|
||||
final sortedEntries = groupedLogs.entries.toList()
|
||||
..sort((a, b) {
|
||||
if (a.key == 'Unknown') return 1;
|
||||
if (b.key == 'Unknown') return -1;
|
||||
final dateA = DateFormat('dd MMM yyyy').parse(a.key);
|
||||
final dateB = DateFormat('dd MMM yyyy').parse(b.key);
|
||||
return dateB.compareTo(dateA);
|
||||
});
|
||||
|
||||
final sortedMap = Map<String, List<AttendanceLogModel>>.fromEntries(sortedEntries);
|
||||
|
||||
log.i("Logs grouped and sorted by check-in date.");
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
/// Fetches regularization logs for a project.
|
||||
Future<void> fetchRegularizationLogs(
|
||||
String? projectId, {
|
||||
DateTime? dateFrom,
|
||||
DateTime? dateTo,
|
||||
}) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoadingRegularizationLogs.value = true;
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getRegularizationLogs(projectId);
|
||||
|
||||
if (response != null) {
|
||||
regularizationLogs =
|
||||
response.map((json) => RegularizationLogModel.fromJson(json)).toList();
|
||||
log.i("Regularization logs fetched: ${regularizationLogs.length}");
|
||||
update();
|
||||
} else {
|
||||
log.e("Failed to fetch regularization logs for project $projectId");
|
||||
}
|
||||
|
||||
isLoadingRegularizationLogs.value = false;
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
/// Fetches detailed attendance log view for a specific ID.
|
||||
Future<void> fetchLogsView(String? id) async {
|
||||
if (id == null) return;
|
||||
|
||||
isLoadingLogView.value = true;
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getAttendanceLogView(id);
|
||||
|
||||
if (response != null) {
|
||||
attendenceLogsView =
|
||||
response.map((json) => AttendanceLogViewModel.fromJson(json)).toList();
|
||||
|
||||
attendenceLogsView.sort((a, b) {
|
||||
if (a.activityTime == null || b.activityTime == null) return 0;
|
||||
return b.activityTime!.compareTo(a.activityTime!);
|
||||
});
|
||||
|
||||
log.i("Attendance log view fetched for ID: $id");
|
||||
update();
|
||||
} else {
|
||||
log.e("Failed to fetch attendance log view for ID $id");
|
||||
}
|
||||
|
||||
isLoadingLogView.value = false;
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
@ -1,35 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/lead_report_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class CrmController extends MyController {
|
||||
List<ChartSampleData>? chartData;
|
||||
List<LeadReportModel> leadReport = [];
|
||||
TooltipBehavior? tooltipBehavior;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
tooltipBehavior = TooltipBehavior(enable: true);
|
||||
chartData = <ChartSampleData>[
|
||||
ChartSampleData(x: 'Jan', y: 10, secondSeriesYValue: 5),
|
||||
ChartSampleData(x: 'Feb', y: 12, secondSeriesYValue: 8),
|
||||
ChartSampleData(x: 'Mar', y: 14, secondSeriesYValue: 9),
|
||||
ChartSampleData(x: 'Apr', y: 11, secondSeriesYValue: 7),
|
||||
ChartSampleData(x: 'May', y: 15, secondSeriesYValue: 10),
|
||||
ChartSampleData(x: 'Jun', y: 9, secondSeriesYValue: 6),
|
||||
ChartSampleData(x: 'Jul', y: 13, secondSeriesYValue: 7),
|
||||
ChartSampleData(x: 'Aug', y: 12, secondSeriesYValue: 8),
|
||||
ChartSampleData(x: 'Sep', y: 14, secondSeriesYValue: 10),
|
||||
ChartSampleData(x: 'Oct', y: 15, secondSeriesYValue: 12),
|
||||
ChartSampleData(x: 'Nov', y: 13, secondSeriesYValue: 9),
|
||||
ChartSampleData(x: 'Dec', y: 11, secondSeriesYValue: 6),
|
||||
];
|
||||
|
||||
LeadReportModel.dummyList.then((value) {
|
||||
leadReport = value.sublist(0, 5);
|
||||
update();
|
||||
});
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/coin_growth_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class CryptoController extends MyController {
|
||||
List<ChartSampleData>? chartData;
|
||||
DateTimeIntervalType intervalType = DateTimeIntervalType.months;
|
||||
List<CoinGrowthModel> coinGrowth = [];
|
||||
|
||||
bool enableSolidCandle = false;
|
||||
|
||||
TrackballBehavior? trackballBehavior;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
CoinGrowthModel.dummyList.then((value) {
|
||||
coinGrowth = value.sublist(0, 5);
|
||||
update();
|
||||
});
|
||||
chartData = <ChartSampleData>[
|
||||
ChartSampleData(x: 'Jan', y: 50, secondSeriesYValue: 40, thirdSeriesYValue: 45),
|
||||
ChartSampleData(x: 'Feb', y: 47, secondSeriesYValue: 39, thirdSeriesYValue: 48),
|
||||
ChartSampleData(x: 'Mar', y: 55, secondSeriesYValue: 42, thirdSeriesYValue: 50),
|
||||
ChartSampleData(x: 'Apr', y: 60, secondSeriesYValue: 45, thirdSeriesYValue: 53),
|
||||
ChartSampleData(x: 'May', y: 70, secondSeriesYValue: 50, thirdSeriesYValue: 58),
|
||||
ChartSampleData(x: 'Jun', y: 75, secondSeriesYValue: 55, thirdSeriesYValue: 62),
|
||||
ChartSampleData(x: 'Jul', y: 80, secondSeriesYValue: 58, thirdSeriesYValue: 65),
|
||||
ChartSampleData(x: 'Aug', y: 78, secondSeriesYValue: 60, thirdSeriesYValue: 66),
|
||||
ChartSampleData(x: 'Sep', y: 72, secondSeriesYValue: 55, thirdSeriesYValue: 64),
|
||||
ChartSampleData(x: 'Oct', y: 65, secondSeriesYValue: 50, thirdSeriesYValue: 57),
|
||||
ChartSampleData(x: 'Nov', y: 58, secondSeriesYValue: 45, thirdSeriesYValue: 53),
|
||||
ChartSampleData(x: 'Dec', y: 50, secondSeriesYValue: 40, thirdSeriesYValue: 48)
|
||||
];
|
||||
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void onSelectIntervalType(DateTimeIntervalType interval) {
|
||||
intervalType = interval;
|
||||
update();
|
||||
}
|
||||
}
|
||||
@ -1,127 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:marco/helpers/services/api_service.dart';
|
||||
import 'package:marco/model/project_model.dart';
|
||||
import 'package:marco/model/daily_task_model.dart';
|
||||
|
||||
final Logger log = Logger();
|
||||
|
||||
class DailyTaskController extends GetxController {
|
||||
List<ProjectModel> projects = [];
|
||||
String? selectedProjectId;
|
||||
|
||||
DateTime? startDateTask;
|
||||
DateTime? endDateTask;
|
||||
|
||||
List<TaskModel> dailyTasks = [];
|
||||
final RxSet<String> expandedDates = <String>{}.obs;
|
||||
|
||||
void toggleDate(String dateKey) {
|
||||
if (expandedDates.contains(dateKey)) {
|
||||
expandedDates.remove(dateKey);
|
||||
} else {
|
||||
expandedDates.add(dateKey);
|
||||
}
|
||||
}
|
||||
|
||||
RxBool isLoading = false.obs;
|
||||
Map<String, List<TaskModel>> groupedDailyTasks = {};
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
_initializeDefaults();
|
||||
}
|
||||
|
||||
void _initializeDefaults() {
|
||||
_setDefaultDateRange();
|
||||
fetchProjects();
|
||||
}
|
||||
|
||||
void _setDefaultDateRange() {
|
||||
final today = DateTime.now();
|
||||
startDateTask = today.subtract(const Duration(days: 7));
|
||||
endDateTask = today;
|
||||
log.i("Default date range set: $startDateTask to $endDateTask");
|
||||
}
|
||||
|
||||
Future<void> fetchProjects() async {
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getProjects();
|
||||
isLoading.value = false;
|
||||
|
||||
if (response?.isEmpty ?? true) {
|
||||
log.w("No project data found or API call failed.");
|
||||
return;
|
||||
}
|
||||
|
||||
projects = response!.map((json) => ProjectModel.fromJson(json)).toList();
|
||||
selectedProjectId = projects.first.id.toString();
|
||||
log.i("Projects fetched: ${projects.length} projects loaded.");
|
||||
update();
|
||||
await fetchTaskData(selectedProjectId);
|
||||
}
|
||||
|
||||
Future<void> fetchTaskData(String? projectId) async {
|
||||
if (projectId == null) return;
|
||||
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getDailyTasks(
|
||||
projectId,
|
||||
dateFrom: startDateTask,
|
||||
dateTo: endDateTask,
|
||||
);
|
||||
isLoading.value = false;
|
||||
|
||||
if (response != null) {
|
||||
groupedDailyTasks.clear();
|
||||
|
||||
for (var taskJson in response) {
|
||||
TaskModel task = TaskModel.fromJson(taskJson);
|
||||
String assignmentDateKey =
|
||||
task.assignmentDate.toIso8601String().split('T')[0];
|
||||
|
||||
if (groupedDailyTasks.containsKey(assignmentDateKey)) {
|
||||
groupedDailyTasks[assignmentDateKey]?.add(task);
|
||||
} else {
|
||||
groupedDailyTasks[assignmentDateKey] = [task];
|
||||
}
|
||||
}
|
||||
|
||||
// Flatten the grouped tasks into the existing dailyTasks list
|
||||
dailyTasks = groupedDailyTasks.values.expand((list) => list).toList();
|
||||
|
||||
log.i("Daily tasks fetched and grouped: ${dailyTasks.length}");
|
||||
|
||||
update();
|
||||
} else {
|
||||
log.e("Failed to fetch daily tasks for project $projectId");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> selectDateRangeForTaskData(
|
||||
BuildContext context,
|
||||
DailyTaskController controller,
|
||||
) async {
|
||||
final picked = await showDateRangePicker(
|
||||
context: context,
|
||||
firstDate: DateTime(2022),
|
||||
lastDate: DateTime.now(),
|
||||
initialDateRange: DateTimeRange(
|
||||
start:
|
||||
startDateTask ?? DateTime.now().subtract(const Duration(days: 7)),
|
||||
end: endDateTask ?? DateTime.now(),
|
||||
),
|
||||
);
|
||||
|
||||
if (picked == null) return;
|
||||
|
||||
startDateTask = picked.start;
|
||||
endDateTask = picked.end;
|
||||
|
||||
log.i("Date range selected: $startDateTask to $endDateTask");
|
||||
|
||||
await controller.fetchTaskData(controller.selectedProjectId);
|
||||
}
|
||||
}
|
||||
370
lib/controller/dashboard/dashboard_controller.dart
Normal file
@ -0,0 +1,370 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/controller/project_controller.dart';
|
||||
import 'package:on_field_work/model/dashboard/project_progress_model.dart';
|
||||
import 'package:on_field_work/model/dashboard/pending_expenses_model.dart';
|
||||
import 'package:on_field_work/model/dashboard/expense_type_report_model.dart';
|
||||
import 'package:on_field_work/model/dashboard/monthly_expence_model.dart';
|
||||
import 'package:on_field_work/model/expense/expense_type_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/model/dashboard/collection_overview_model.dart';
|
||||
import 'package:on_field_work/model/dashboard/purchase_invoice_model.dart';
|
||||
|
||||
class DashboardController extends GetxController {
|
||||
// Dependencies
|
||||
final ProjectController projectController = Get.put(ProjectController());
|
||||
|
||||
// =========================
|
||||
// 1. STATE VARIABLES
|
||||
// =========================
|
||||
|
||||
// Attendance
|
||||
final roleWiseData = <Map<String, dynamic>>[].obs;
|
||||
final attendanceSelectedRange = '15D'.obs;
|
||||
final attendanceIsChartView = true.obs;
|
||||
final isAttendanceLoading = false.obs;
|
||||
|
||||
// Project Progress
|
||||
final projectChartData = <ChartTaskData>[].obs;
|
||||
final projectSelectedRange = '15D'.obs;
|
||||
final projectIsChartView = true.obs;
|
||||
final isProjectLoading = false.obs;
|
||||
|
||||
// Overview Counts
|
||||
final totalProjects = 0.obs;
|
||||
final ongoingProjects = 0.obs;
|
||||
final isProjectsLoading = false.obs;
|
||||
|
||||
final totalTasks = 0.obs;
|
||||
final completedTasks = 0.obs;
|
||||
final isTasksLoading = false.obs;
|
||||
|
||||
final totalEmployees = 0.obs;
|
||||
final inToday = 0.obs;
|
||||
final isTeamsLoading = false.obs;
|
||||
|
||||
// Expenses & Reports
|
||||
final isPendingExpensesLoading = false.obs;
|
||||
final pendingExpensesData = Rx<PendingExpensesData?>(null);
|
||||
|
||||
final isExpenseTypeReportLoading = false.obs;
|
||||
final expenseTypeReportData = Rx<ExpenseTypeReportData?>(null);
|
||||
final expenseReportStartDate =
|
||||
DateTime.now().subtract(const Duration(days: 15)).obs;
|
||||
final expenseReportEndDate = DateTime.now().obs;
|
||||
|
||||
final isMonthlyExpenseLoading = false.obs;
|
||||
final monthlyExpenseList = <MonthlyExpenseData>[].obs;
|
||||
final selectedMonthlyExpenseDuration =
|
||||
MonthlyExpenseDuration.twelveMonths.obs;
|
||||
final selectedMonthsCount = 12.obs;
|
||||
|
||||
final expenseTypes = <ExpenseTypeModel>[].obs;
|
||||
final selectedExpenseType = Rx<ExpenseTypeModel?>(null);
|
||||
|
||||
// Teams/Employees
|
||||
final isLoadingEmployees = true.obs;
|
||||
final employees = <EmployeeModel>[].obs;
|
||||
final uploadingStates = <String, RxBool>{}.obs;
|
||||
|
||||
// Collection
|
||||
final isCollectionOverviewLoading = true.obs;
|
||||
final collectionOverviewData = Rx<CollectionOverviewData?>(null);
|
||||
// =========================
|
||||
// Purchase Invoice Overview
|
||||
// =========================
|
||||
final isPurchaseInvoiceLoading = true.obs;
|
||||
final purchaseInvoiceOverviewData = Rx<PurchaseInvoiceOverviewData?>(null);
|
||||
// Constants
|
||||
final List<String> ranges = ['7D', '15D', '30D'];
|
||||
static const _rangeDaysMap = {
|
||||
'7D': 7,
|
||||
'15D': 15,
|
||||
'30D': 30,
|
||||
'3M': 90,
|
||||
'6M': 180
|
||||
};
|
||||
|
||||
// =========================
|
||||
// 2. COMPUTED PROPERTIES
|
||||
// =========================
|
||||
|
||||
int getAttendanceDays() => _rangeDaysMap[attendanceSelectedRange.value] ?? 7;
|
||||
int getProjectDays() => _rangeDaysMap[projectSelectedRange.value] ?? 7;
|
||||
|
||||
// DSO Calculation Constants
|
||||
static const double _w0_30 = 15.0;
|
||||
static const double _w30_60 = 45.0;
|
||||
static const double _w60_90 = 75.0;
|
||||
static const double _w90_plus = 105.0;
|
||||
|
||||
double get calculatedDSO {
|
||||
final data = collectionOverviewData.value;
|
||||
if (data == null || data.totalDueAmount == 0) return 0.0;
|
||||
|
||||
final double weightedDue = (data.bucket0To30Amount * _w0_30) +
|
||||
(data.bucket30To60Amount * _w30_60) +
|
||||
(data.bucket60To90Amount * _w60_90) +
|
||||
(data.bucket90PlusAmount * _w90_plus);
|
||||
|
||||
return weightedDue / data.totalDueAmount;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 3. LIFECYCLE
|
||||
// =========================
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
logSafe('DashboardController initialized', level: LogLevel.info);
|
||||
|
||||
// Project Selection Listener
|
||||
ever<String>(projectController.selectedProjectId, (id) {
|
||||
if (id.isNotEmpty) {
|
||||
fetchAllDashboardData();
|
||||
fetchTodaysAttendance(id);
|
||||
}
|
||||
});
|
||||
|
||||
// Expense Report Date Listener
|
||||
everAll([expenseReportStartDate, expenseReportEndDate], (_) {
|
||||
if (projectController.selectedProjectId.value.isNotEmpty) {
|
||||
fetchExpenseTypeReport(
|
||||
startDate: expenseReportStartDate.value,
|
||||
endDate: expenseReportEndDate.value,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Chart Range Listeners
|
||||
ever(attendanceSelectedRange, (_) => fetchRoleWiseAttendance());
|
||||
ever(projectSelectedRange, (_) => fetchProjectProgress());
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 4. USER ACTIONS
|
||||
// =========================
|
||||
|
||||
void updateAttendanceRange(String range) =>
|
||||
attendanceSelectedRange.value = range;
|
||||
void updateProjectRange(String range) => projectSelectedRange.value = range;
|
||||
void toggleAttendanceChartView(bool isChart) =>
|
||||
attendanceIsChartView.value = isChart;
|
||||
void toggleProjectChartView(bool isChart) =>
|
||||
projectIsChartView.value = isChart;
|
||||
|
||||
void updateSelectedExpenseType(ExpenseTypeModel? type) {
|
||||
selectedExpenseType.value = type;
|
||||
fetchMonthlyExpenses(categoryId: type?.id);
|
||||
}
|
||||
|
||||
void updateMonthlyExpenseDuration(MonthlyExpenseDuration duration) {
|
||||
selectedMonthlyExpenseDuration.value = duration;
|
||||
|
||||
// Efficient Map lookup instead of Switch
|
||||
const durationMap = {
|
||||
MonthlyExpenseDuration.oneMonth: 1,
|
||||
MonthlyExpenseDuration.threeMonths: 3,
|
||||
MonthlyExpenseDuration.sixMonths: 6,
|
||||
MonthlyExpenseDuration.twelveMonths: 12,
|
||||
MonthlyExpenseDuration.all: 0,
|
||||
};
|
||||
|
||||
selectedMonthsCount.value = durationMap[duration] ?? 12;
|
||||
fetchMonthlyExpenses();
|
||||
}
|
||||
|
||||
Future<void> refreshDashboard() => fetchAllDashboardData();
|
||||
Future<void> refreshAttendance() => fetchRoleWiseAttendance();
|
||||
Future<void> refreshProjects() => fetchProjectProgress();
|
||||
Future<void> refreshTasks() async {
|
||||
final id = projectController.selectedProjectId.value;
|
||||
if (id.isNotEmpty) await fetchDashboardTasks(projectId: id);
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 5. DATA FETCHING (API)
|
||||
// =========================
|
||||
|
||||
/// Wrapper to reduce try-finally boilerplate for loading states
|
||||
Future<void> _executeApiCall(
|
||||
RxBool loader, Future<void> Function() apiLogic) async {
|
||||
loader.value = true;
|
||||
try {
|
||||
await apiLogic();
|
||||
} finally {
|
||||
loader.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchAllDashboardData() async {
|
||||
final String projectId = projectController.selectedProjectId.value;
|
||||
if (projectId.isEmpty) return;
|
||||
|
||||
await Future.wait([
|
||||
fetchRoleWiseAttendance(),
|
||||
fetchProjectProgress(),
|
||||
fetchDashboardTasks(projectId: projectId),
|
||||
fetchDashboardTeams(projectId: projectId),
|
||||
fetchPendingExpenses(),
|
||||
fetchExpenseTypeReport(
|
||||
startDate: expenseReportStartDate.value,
|
||||
endDate: expenseReportEndDate.value,
|
||||
),
|
||||
fetchMonthlyExpenses(),
|
||||
fetchMasterData(),
|
||||
fetchCollectionOverview(),
|
||||
fetchPurchaseInvoiceOverview(),
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> fetchCollectionOverview() async {
|
||||
final projectId = projectController.selectedProjectId.value;
|
||||
if (projectId.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isCollectionOverviewLoading, () async {
|
||||
final response =
|
||||
await ApiService.getCollectionOverview(projectId: projectId);
|
||||
collectionOverviewData.value =
|
||||
(response?.success == true) ? response!.data : null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchTodaysAttendance(String projectId) async {
|
||||
await _executeApiCall(isLoadingEmployees, () async {
|
||||
final response = await ApiService.getAttendanceForDashboard(projectId);
|
||||
if (response != null) {
|
||||
employees.value = response;
|
||||
for (var emp in employees) {
|
||||
uploadingStates.putIfAbsent(emp.id, () => false.obs);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchMasterData() async {
|
||||
try {
|
||||
final data = await ApiService.getMasterExpenseTypes();
|
||||
if (data is List) {
|
||||
expenseTypes.value =
|
||||
data.map((e) => ExpenseTypeModel.fromJson(e)).toList();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> fetchMonthlyExpenses({String? categoryId}) async {
|
||||
await _executeApiCall(isMonthlyExpenseLoading, () async {
|
||||
final response = await ApiService.getDashboardMonthlyExpensesApi(
|
||||
categoryId: categoryId,
|
||||
months: selectedMonthsCount.value,
|
||||
);
|
||||
monthlyExpenseList.value =
|
||||
(response?.success == true) ? response!.data : [];
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchPurchaseInvoiceOverview() async {
|
||||
final projectId = projectController.selectedProjectId.value;
|
||||
if (projectId.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isPurchaseInvoiceLoading, () async {
|
||||
final response = await ApiService.getPurchaseInvoiceOverview(
|
||||
projectId: projectId,
|
||||
);
|
||||
purchaseInvoiceOverviewData.value =
|
||||
(response?.success == true) ? response!.data : null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchPendingExpenses() async {
|
||||
final id = projectController.selectedProjectId.value;
|
||||
if (id.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isPendingExpensesLoading, () async {
|
||||
final response = await ApiService.getPendingExpensesApi(projectId: id);
|
||||
pendingExpensesData.value =
|
||||
(response?.success == true) ? response!.data : null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchRoleWiseAttendance() async {
|
||||
final id = projectController.selectedProjectId.value;
|
||||
if (id.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isAttendanceLoading, () async {
|
||||
final response = await ApiService.getDashboardAttendanceOverview(
|
||||
id, getAttendanceDays());
|
||||
roleWiseData.value =
|
||||
response?.map((e) => Map<String, dynamic>.from(e)).toList() ?? [];
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchExpenseTypeReport(
|
||||
{required DateTime startDate, required DateTime endDate}) async {
|
||||
final id = projectController.selectedProjectId.value;
|
||||
if (id.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isExpenseTypeReportLoading, () async {
|
||||
final response = await ApiService.getExpenseTypeReportApi(
|
||||
projectId: id,
|
||||
startDate: startDate,
|
||||
endDate: endDate,
|
||||
);
|
||||
expenseTypeReportData.value =
|
||||
(response?.success == true) ? response!.data : null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchProjectProgress() async {
|
||||
final id = projectController.selectedProjectId.value;
|
||||
if (id.isEmpty) return;
|
||||
|
||||
await _executeApiCall(isProjectLoading, () async {
|
||||
final response = await ApiService.getProjectProgress(
|
||||
projectId: id, days: getProjectDays());
|
||||
if (response?.success == true) {
|
||||
projectChartData.value = response!.data
|
||||
.map((d) => ChartTaskData.fromProjectData(d))
|
||||
.toList();
|
||||
} else {
|
||||
projectChartData.clear();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchDashboardTasks({required String projectId}) async {
|
||||
await _executeApiCall(isTasksLoading, () async {
|
||||
final response = await ApiService.getDashboardTasks(projectId: projectId);
|
||||
if (response?.success == true) {
|
||||
totalTasks.value = response!.data?.totalTasks ?? 0;
|
||||
completedTasks.value = response.data?.completedTasks ?? 0;
|
||||
} else {
|
||||
totalTasks.value = 0;
|
||||
completedTasks.value = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> fetchDashboardTeams({required String projectId}) async {
|
||||
await _executeApiCall(isTeamsLoading, () async {
|
||||
final response = await ApiService.getDashboardTeams(projectId: projectId);
|
||||
if (response?.success == true) {
|
||||
totalEmployees.value = response!.data?.totalEmployees ?? 0;
|
||||
inToday.value = response.data?.inToday ?? 0;
|
||||
} else {
|
||||
totalEmployees.value = 0;
|
||||
inToday.value = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
enum MonthlyExpenseDuration {
|
||||
oneMonth,
|
||||
threeMonths,
|
||||
sixMonths,
|
||||
twelveMonths,
|
||||
all,
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/product_order_modal.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class EcommerceController extends MyController {
|
||||
List<ChartSampleData>? salesAnalyticsData;
|
||||
List<ProductOrderModal> order = [];
|
||||
String selectedTimeByLocation = "Year";
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
ProductOrderModal.dummyList.then((value) {
|
||||
order = value.sublist(0, 5);
|
||||
update();
|
||||
});
|
||||
salesAnalyticsData = <ChartSampleData>[
|
||||
ChartSampleData(x: 'Jan', y: 43, secondSeriesYValue: 37, thirdSeriesYValue: 41),
|
||||
ChartSampleData(x: 'Feb', y: 45, secondSeriesYValue: 37, thirdSeriesYValue: 45),
|
||||
ChartSampleData(x: 'Mar', y: 50, secondSeriesYValue: 39, thirdSeriesYValue: 48),
|
||||
ChartSampleData(x: 'Apr', y: 55, secondSeriesYValue: 43, thirdSeriesYValue: 52),
|
||||
ChartSampleData(x: 'May', y: 63, secondSeriesYValue: 48, thirdSeriesYValue: 57),
|
||||
ChartSampleData(x: 'Jun', y: 68, secondSeriesYValue: 54, thirdSeriesYValue: 61),
|
||||
ChartSampleData(x: 'Jul', y: 72, secondSeriesYValue: 57, thirdSeriesYValue: 66),
|
||||
ChartSampleData(x: 'Aug', y: 70, secondSeriesYValue: 57, thirdSeriesYValue: 66),
|
||||
ChartSampleData(x: 'Sep', y: 66, secondSeriesYValue: 54, thirdSeriesYValue: 63),
|
||||
ChartSampleData(x: 'Oct', y: 57, secondSeriesYValue: 48, thirdSeriesYValue: 55),
|
||||
ChartSampleData(x: 'Nov', y: 50, secondSeriesYValue: 43, thirdSeriesYValue: 50),
|
||||
ChartSampleData(x: 'Dec', y: 45, secondSeriesYValue: 37, thirdSeriesYValue: 45)
|
||||
];
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
final List<ChartSampleData> chartData = [
|
||||
ChartSampleData(x: 'Jan', y: 10, yValue: 1000),
|
||||
ChartSampleData(x: 'Fab', y: 20, yValue: 2000),
|
||||
ChartSampleData(x: 'Mar', y: 15, yValue: 1500),
|
||||
ChartSampleData(x: 'Jun', y: 5, yValue: 500),
|
||||
ChartSampleData(x: 'Jul', y: 30, yValue: 3000),
|
||||
ChartSampleData(x: 'Aug', y: 20, yValue: 2000),
|
||||
ChartSampleData(x: 'Sep', y: 40, yValue: 4000),
|
||||
ChartSampleData(x: 'Oct', y: 60, yValue: 6000),
|
||||
ChartSampleData(x: 'Nov', y: 55, yValue: 5500),
|
||||
ChartSampleData(x: 'Dec', y: 38, yValue: 3000),
|
||||
];
|
||||
final TooltipBehavior chart = TooltipBehavior(
|
||||
enable: true,
|
||||
format: 'point.x : point.yValue1 : point.yValue2',
|
||||
);
|
||||
|
||||
final List<ChartSampleData> circleChart = [
|
||||
ChartSampleData(x: 'David', y: 25, pointColor: const Color.fromRGBO(9, 0, 136, 1)),
|
||||
ChartSampleData(x: 'Steve', y: 38, pointColor: const Color.fromRGBO(147, 0, 119, 1)),
|
||||
ChartSampleData(x: 'Jack', y: 34, pointColor: const Color.fromRGBO(228, 0, 124, 1)),
|
||||
ChartSampleData(x: 'Others', y: 52, pointColor: const Color.fromRGBO(255, 189, 57, 1))
|
||||
];
|
||||
|
||||
void onSelectedTimeByLocation(String time) {
|
||||
selectedTimeByLocation = time;
|
||||
update();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
salesAnalyticsData!.clear();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@ -1,150 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:marco/helpers/services/api_service.dart';
|
||||
import 'package:marco/model/attendance_model.dart';
|
||||
import 'package:marco/model/project_model.dart';
|
||||
import 'package:marco/model/employee_model.dart';
|
||||
import 'package:marco/model/employees/employee_details_model.dart';
|
||||
|
||||
final Logger log = Logger();
|
||||
|
||||
class EmployeesScreenController extends GetxController {
|
||||
List<AttendanceModel> attendances = [];
|
||||
List<ProjectModel> projects = [];
|
||||
String? selectedProjectId;
|
||||
List<EmployeeModel> employees = [];
|
||||
List<EmployeeDetailsModel> employeeDetails = [];
|
||||
|
||||
RxBool isLoading = false.obs;
|
||||
RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
|
||||
Rxn<EmployeeDetailsModel> selectedEmployeeDetails =
|
||||
Rxn<EmployeeDetailsModel>();
|
||||
RxBool isLoadingEmployeeDetails = false.obs;
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchAllProjects();
|
||||
fetchAllEmployees();
|
||||
}
|
||||
|
||||
Future<void> fetchAllProjects() async {
|
||||
isLoading.value = true;
|
||||
await _handleApiCall(
|
||||
ApiService.getProjects,
|
||||
onSuccess: (data) {
|
||||
projects = data.map((json) => ProjectModel.fromJson(json)).toList();
|
||||
log.i("Projects fetched: ${projects.length} projects loaded.");
|
||||
},
|
||||
onEmpty: () => log.w("No project data found or API call failed."),
|
||||
);
|
||||
isLoading.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> fetchAllEmployees() async {
|
||||
isLoading.value = true;
|
||||
await _handleApiCall(
|
||||
ApiService.getAllEmployees,
|
||||
onSuccess: (data) {
|
||||
employees = data.map((json) => EmployeeModel.fromJson(json)).toList();
|
||||
log.i("All Employees fetched: ${employees.length} employees loaded.");
|
||||
},
|
||||
onEmpty: () => log.w("No Employee data found or API call failed."),
|
||||
);
|
||||
isLoading.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> fetchEmployeesByProject(String? projectId) async {
|
||||
if (projectId == null || projectId.isEmpty) {
|
||||
log.e("Project ID is required but was null or empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
await _handleApiCall(
|
||||
() => ApiService.getAllEmployeesByProject(projectId),
|
||||
onSuccess: (data) {
|
||||
employees = data.map((json) => EmployeeModel.fromJson(json)).toList();
|
||||
for (var emp in employees) {
|
||||
uploadingStates[emp.id] = false.obs;
|
||||
}
|
||||
log.i("Employees fetched: ${employees.length} for project $projectId");
|
||||
update();
|
||||
},
|
||||
onEmpty: () {
|
||||
log.w("No employees found for project $projectId.");
|
||||
employees = [];
|
||||
update();
|
||||
},
|
||||
onError: (e) =>
|
||||
log.e("Error fetching employees for project $projectId: $e"),
|
||||
);
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
Future<void> _handleApiCall(
|
||||
Future<List<dynamic>?> Function() apiCall, {
|
||||
required Function(List<dynamic>) onSuccess,
|
||||
required Function() onEmpty,
|
||||
Function(dynamic error)? onError,
|
||||
}) async {
|
||||
try {
|
||||
final response = await apiCall();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
onSuccess(response);
|
||||
} else {
|
||||
onEmpty();
|
||||
}
|
||||
} catch (e) {
|
||||
if (onError != null) {
|
||||
onError(e);
|
||||
} else {
|
||||
log.e("API call error: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchEmployeeDetails(String? employeeId) async {
|
||||
if (employeeId == null || employeeId.isEmpty) return;
|
||||
|
||||
isLoadingEmployeeDetails.value = true;
|
||||
|
||||
await _handleSingleApiCall(
|
||||
() => ApiService.getEmployeeDetails(employeeId),
|
||||
onSuccess: (data) {
|
||||
selectedEmployeeDetails.value = EmployeeDetailsModel.fromJson(data);
|
||||
},
|
||||
onEmpty: () {
|
||||
selectedEmployeeDetails.value = null;
|
||||
},
|
||||
onError: (e) {
|
||||
selectedEmployeeDetails.value = null;
|
||||
},
|
||||
);
|
||||
|
||||
isLoadingEmployeeDetails.value = false;
|
||||
}
|
||||
|
||||
Future<void> _handleSingleApiCall(
|
||||
Future<Map<String, dynamic>?> Function() apiCall, {
|
||||
required Function(Map<String, dynamic>) onSuccess,
|
||||
required Function() onEmpty,
|
||||
Function(dynamic error)? onError,
|
||||
}) async {
|
||||
try {
|
||||
final response = await apiCall();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
onSuccess(response);
|
||||
} else {
|
||||
onEmpty();
|
||||
}
|
||||
} catch (e) {
|
||||
if (onError != null) {
|
||||
onError(e);
|
||||
} else {
|
||||
log.e("API call error: $e");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/widgets/my_text_utils.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/job_recent_application_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class JobController extends MyController {
|
||||
int isSelectedListingPerformanceTime = 0;
|
||||
List<ChartSampleData>? chartData;
|
||||
TooltipBehavior? columnToolTip;
|
||||
List<JobRecentApplicationModel> recentApplication = [];
|
||||
List<String> dummyTexts = List.generate(12, (index) => MyTextUtils.getDummyText(60));
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
chartData = <ChartSampleData>[
|
||||
ChartSampleData(x: 'Jan', y: 4, secondSeriesYValue: 8),
|
||||
ChartSampleData(x: 'Feb', y: 9, secondSeriesYValue: 7),
|
||||
ChartSampleData(x: 'Mar', y: 6, secondSeriesYValue: 5),
|
||||
ChartSampleData(x: 'Apr', y: 8, secondSeriesYValue: 3),
|
||||
ChartSampleData(x: 'May', y: 7, secondSeriesYValue: 9),
|
||||
ChartSampleData(x: 'Jun', y: 10, secondSeriesYValue: 6),
|
||||
ChartSampleData(x: 'Jul', y: 5, secondSeriesYValue: 4),
|
||||
ChartSampleData(x: 'Aug', y: 3, secondSeriesYValue: 2),
|
||||
ChartSampleData(x: 'Sep', y: 6, secondSeriesYValue: 10),
|
||||
ChartSampleData(x: 'Oct', y: 4, secondSeriesYValue: 8),
|
||||
ChartSampleData(x: 'Nov', y: 9, secondSeriesYValue: 6),
|
||||
ChartSampleData(x: 'Dec', y: 7, secondSeriesYValue: 5),
|
||||
];
|
||||
columnToolTip = TooltipBehavior(enable: true);
|
||||
JobRecentApplicationModel.dummyList.then((value) {
|
||||
recentApplication = value.sublist(0, 5);
|
||||
update();
|
||||
});
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void onSelectListingPerformanceTimeToggle(index) {
|
||||
isSelectedListingPerformanceTime = index;
|
||||
update();
|
||||
}
|
||||
}
|
||||
@ -1,46 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/project_summary_model.dart';
|
||||
import 'package:marco/model/task_list_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class ProjectController extends MyController {
|
||||
TooltipBehavior? tooltipBehavior;
|
||||
List<TaskListModel> task = [];
|
||||
List<ProjectSummaryModel> projectSummary = [];
|
||||
List<ChartSampleData>? chartData;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
TaskListModel.dummyList.then((value) {
|
||||
task = value;
|
||||
update();
|
||||
});
|
||||
ProjectSummaryModel.dummyList.then((value) {
|
||||
projectSummary = value.sublist(0, 5);
|
||||
update();
|
||||
});
|
||||
chartData = <ChartSampleData>[
|
||||
ChartSampleData(x: 'Jan', y: 10, secondSeriesYValue: 8, thirdSeriesYValue: 12),
|
||||
ChartSampleData(x: 'Feb', y: 5, secondSeriesYValue: 6, thirdSeriesYValue: 7),
|
||||
ChartSampleData(x: 'Mar', y: 11, secondSeriesYValue: 9, thirdSeriesYValue: 6),
|
||||
ChartSampleData(x: 'Apr', y: 14, secondSeriesYValue: 10, thirdSeriesYValue: 13),
|
||||
ChartSampleData(x: 'May', y: 9, secondSeriesYValue: 7, thirdSeriesYValue: 5),
|
||||
ChartSampleData(x: 'Jun', y: 8, secondSeriesYValue: 12, thirdSeriesYValue: 11),
|
||||
ChartSampleData(x: 'Jul', y: 12, secondSeriesYValue: 11, thirdSeriesYValue: 9),
|
||||
ChartSampleData(x: 'Aug', y: 7, secondSeriesYValue: 13, thirdSeriesYValue: 10),
|
||||
ChartSampleData(x: 'Sep', y: 6, secondSeriesYValue: 5, thirdSeriesYValue: 8),
|
||||
ChartSampleData(x: 'Oct', y: 4, secondSeriesYValue: 14, thirdSeriesYValue: 15),
|
||||
ChartSampleData(x: 'Nov', y: 13, secondSeriesYValue: 4, thirdSeriesYValue: 11),
|
||||
ChartSampleData(x: 'Dec', y: 15, secondSeriesYValue: 3, thirdSeriesYValue: 4)
|
||||
];
|
||||
|
||||
tooltipBehavior = TooltipBehavior(enable: true, format: 'point.x : point.ym');
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
void onSelectTask(TaskListModel task) {
|
||||
task.isSelectTask = !task.isSelectTask;
|
||||
update();
|
||||
}
|
||||
}
|
||||
@ -1,56 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/model/chart_model.dart';
|
||||
import 'package:marco/model/recent_order_model.dart';
|
||||
import 'package:syncfusion_flutter_charts/charts.dart';
|
||||
|
||||
class SalesController extends MyController {
|
||||
List<ChartData>? statisticsData;
|
||||
List<RecentOrderModel> recentOrder = [];
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
RecentOrderModel.dummyList.then((value) {
|
||||
recentOrder = value;
|
||||
update();
|
||||
});
|
||||
|
||||
statisticsData = <ChartData>[
|
||||
ChartData(2005, 15, 25),
|
||||
ChartData(2006, 40, 55),
|
||||
ChartData(2007, 50, 70),
|
||||
ChartData(2008, 55, 80),
|
||||
ChartData(2009, 65, 85),
|
||||
ChartData(2010, 70, 95),
|
||||
ChartData(2011, 90, 110)
|
||||
];
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
final List<ChartSampleData> visitorChartData = [
|
||||
ChartSampleData(x: 'Jan', y: 12, yValue: 1200),
|
||||
ChartSampleData(x: 'Feb', y: 18, yValue: 1800),
|
||||
ChartSampleData(x: 'Mar', y: 22, yValue: 2200),
|
||||
ChartSampleData(x: 'Apr', y: 10, yValue: 1000),
|
||||
ChartSampleData(x: 'May', y: 25, yValue: 2500),
|
||||
ChartSampleData(x: 'Jun', y: 35, yValue: 3500),
|
||||
ChartSampleData(x: 'Jul', y: 28, yValue: 2800),
|
||||
ChartSampleData(x: 'Aug', y: 45, yValue: 4500),
|
||||
ChartSampleData(x: 'Sep', y: 50, yValue: 5000),
|
||||
ChartSampleData(x: 'Oct', y: 60, yValue: 6000),
|
||||
ChartSampleData(x: 'Nov', y: 42, yValue: 4200),
|
||||
ChartSampleData(x: 'Dec', y: 55, yValue: 5500),
|
||||
];
|
||||
|
||||
final TooltipBehavior visitorChart = TooltipBehavior(
|
||||
enable: true,
|
||||
format: 'point.x : point.yValue1 : point.yValue2',
|
||||
);
|
||||
}
|
||||
|
||||
class ChartData {
|
||||
ChartData(this.x, this.y, this.y2);
|
||||
|
||||
final double x;
|
||||
final double y;
|
||||
final double y2;
|
||||
}
|
||||
71
lib/controller/directory/add_comment_controller.dart
Normal file
@ -0,0 +1,71 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/controller/directory/directory_controller.dart';
|
||||
import 'package:on_field_work/controller/directory/notes_controller.dart';
|
||||
|
||||
class AddCommentController extends GetxController {
|
||||
final String contactId;
|
||||
|
||||
AddCommentController({required this.contactId});
|
||||
|
||||
final RxString note = ''.obs;
|
||||
final RxBool isSubmitting = false.obs;
|
||||
|
||||
Future<void> submitComment() async {
|
||||
if (note.value.trim().isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Comment",
|
||||
message: "Please enter a comment before submitting.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
isSubmitting.value = true;
|
||||
|
||||
try {
|
||||
logSafe("Submitting comment for contactId: $contactId");
|
||||
|
||||
final success = await ApiService.addContactComment(
|
||||
note.value.trim(),
|
||||
contactId,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
logSafe("Comment added successfully.");
|
||||
|
||||
// Refresh UI
|
||||
final directoryController = Get.find<DirectoryController>();
|
||||
await directoryController.fetchCommentsForContact(contactId);
|
||||
|
||||
final notesController = Get.find<NotesController>();
|
||||
await notesController.fetchNotes(
|
||||
pageSize: 1000, pageNumber: 1); // ✅ Fixed here
|
||||
|
||||
Get.back(result: true);
|
||||
|
||||
showAppSnackbar(
|
||||
title: "Comment Added",
|
||||
message: "Your comment has been successfully added.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error while submitting comment: $e", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Unexpected Error",
|
||||
message: "Something went wrong while adding your comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void updateNote(String value) {
|
||||
note.value = value;
|
||||
logSafe("Note updated: ${value.trim()}");
|
||||
}
|
||||
}
|
||||
316
lib/controller/directory/add_contact_controller.dart
Normal file
@ -0,0 +1,316 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
|
||||
class AddContactController extends GetxController {
|
||||
final RxList<String> categories = <String>[].obs;
|
||||
final RxList<String> buckets = <String>[].obs;
|
||||
final RxList<String> globalProjects = <String>[].obs;
|
||||
final RxList<String> tags = <String>[].obs;
|
||||
|
||||
final RxString selectedCategory = ''.obs;
|
||||
final RxList<String> selectedBuckets = <String>[].obs;
|
||||
final RxString selectedProject = ''.obs;
|
||||
|
||||
final RxList<String> enteredTags = <String>[].obs;
|
||||
final RxList<String> filteredSuggestions = <String>[].obs;
|
||||
final RxList<String> organizationNames = <String>[].obs;
|
||||
final RxList<String> filteredOrgSuggestions = <String>[].obs;
|
||||
|
||||
final RxMap<String, String> categoriesMap = <String, String>{}.obs;
|
||||
final RxMap<String, String> bucketsMap = <String, String>{}.obs;
|
||||
final RxMap<String, String> projectsMap = <String, String>{}.obs;
|
||||
final RxMap<String, String> tagsMap = <String, String>{}.obs;
|
||||
final RxBool isInitialized = false.obs;
|
||||
final RxList<String> selectedProjects = <String>[].obs;
|
||||
final RxBool isSubmitting = false.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
logSafe("AddContactController initialized", level: LogLevel.debug);
|
||||
fetchInitialData();
|
||||
}
|
||||
|
||||
Future<void> fetchInitialData() async {
|
||||
logSafe("Fetching initial dropdown data", level: LogLevel.debug);
|
||||
await Future.wait([
|
||||
fetchBuckets(),
|
||||
fetchGlobalProjects(),
|
||||
fetchTags(),
|
||||
fetchCategories(),
|
||||
fetchOrganizationNames(),
|
||||
]);
|
||||
|
||||
// ✅ Mark initialization as done
|
||||
isInitialized.value = true;
|
||||
}
|
||||
|
||||
void resetForm() {
|
||||
selectedCategory.value = '';
|
||||
selectedProject.value = '';
|
||||
selectedBuckets.clear();
|
||||
enteredTags.clear();
|
||||
filteredSuggestions.clear();
|
||||
filteredOrgSuggestions.clear();
|
||||
selectedProjects.clear();
|
||||
}
|
||||
|
||||
Future<void> fetchBuckets() async {
|
||||
try {
|
||||
final response = await ApiService.getContactBucketList();
|
||||
if (response != null && response['data'] is List) {
|
||||
final names = <String>[];
|
||||
for (var item in response['data']) {
|
||||
if (item['name'] != null && item['id'] != null) {
|
||||
bucketsMap[item['name']] = item['id'].toString();
|
||||
names.add(item['name']);
|
||||
}
|
||||
}
|
||||
buckets.assignAll(names);
|
||||
logSafe("Fetched \${names.length} buckets");
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Failed to fetch buckets: \$e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchOrganizationNames() async {
|
||||
try {
|
||||
final orgs = await ApiService.getOrganizationList();
|
||||
organizationNames.assignAll(orgs);
|
||||
logSafe("Fetched \${orgs.length} organization names");
|
||||
} catch (e) {
|
||||
logSafe("Failed to load organization names: \$e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> submitContact({
|
||||
String? id,
|
||||
required String name,
|
||||
required String organization,
|
||||
required List<Map<String, String>> emails,
|
||||
required List<Map<String, String>> phones,
|
||||
required String address,
|
||||
required String description,
|
||||
String? designation,
|
||||
}) async {
|
||||
if (isSubmitting.value) return;
|
||||
isSubmitting.value = true;
|
||||
|
||||
final categoryId = categoriesMap[selectedCategory.value];
|
||||
final bucketIds = selectedBuckets
|
||||
.map((name) => bucketsMap[name])
|
||||
.whereType<String>()
|
||||
.toList();
|
||||
|
||||
if (bucketIds.isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Buckets",
|
||||
message: "Please select at least one bucket.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
isSubmitting.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
final projectIds = selectedProjects
|
||||
.map((name) => projectsMap[name])
|
||||
.whereType<String>()
|
||||
.toList();
|
||||
|
||||
if (name.trim().isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Name",
|
||||
message: "Please enter the contact name.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
isSubmitting.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (organization.trim().isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Organization",
|
||||
message: "Please enter the organization name.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
isSubmitting.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedBuckets.isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Bucket",
|
||||
message: "Please select at least one bucket.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
isSubmitting.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final tagObjects = enteredTags.map((tagName) {
|
||||
final tagId = tagsMap[tagName];
|
||||
return tagId != null
|
||||
? {"id": tagId, "name": tagName}
|
||||
: {"name": tagName};
|
||||
}).toList();
|
||||
|
||||
final body = {
|
||||
if (id != null) "id": id,
|
||||
"name": name.trim(),
|
||||
"organization": organization.trim(),
|
||||
if (selectedCategory.value.isNotEmpty && categoryId != null)
|
||||
"contactCategoryId": categoryId,
|
||||
if (projectIds.isNotEmpty) "projectIds": projectIds,
|
||||
"bucketIds": bucketIds,
|
||||
if (enteredTags.isNotEmpty) "tags": tagObjects,
|
||||
if (emails.isNotEmpty) "contactEmails": emails,
|
||||
if (phones.isNotEmpty) "contactPhones": phones,
|
||||
if (address.trim().isNotEmpty) "address": address.trim(),
|
||||
if (description.trim().isNotEmpty) "description": description.trim(),
|
||||
if (designation != null && designation.trim().isNotEmpty)
|
||||
"designation": designation.trim(),
|
||||
};
|
||||
|
||||
logSafe("${id != null ? 'Updating' : 'Creating'} contact");
|
||||
|
||||
final response = id != null
|
||||
? await ApiService.updateContact(id, body)
|
||||
: await ApiService.createContact(body);
|
||||
|
||||
if (response == true) {
|
||||
Get.back(result: true);
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: id != null
|
||||
? "Contact updated successfully"
|
||||
: "Contact created successfully",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to ${id != null ? 'update' : 'create'} contact",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Submit contact error: $e", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void filterOrganizationSuggestions(String query) {
|
||||
if (query.trim().isEmpty) {
|
||||
filteredOrgSuggestions.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
final lower = query.toLowerCase();
|
||||
filteredOrgSuggestions.assignAll(
|
||||
organizationNames
|
||||
.where((name) => name.toLowerCase().contains(lower))
|
||||
.toList(),
|
||||
);
|
||||
logSafe("Filtered organization suggestions for: \$query",
|
||||
level: LogLevel.debug);
|
||||
}
|
||||
|
||||
Future<void> fetchGlobalProjects() async {
|
||||
try {
|
||||
final response = await ApiService.getGlobalProjects();
|
||||
if (response != null) {
|
||||
final names = <String>[];
|
||||
for (var item in response) {
|
||||
final name = item['name']?.toString().trim();
|
||||
final id = item['id']?.toString().trim();
|
||||
if (name != null && id != null && name.isNotEmpty) {
|
||||
projectsMap[name] = id;
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
globalProjects.assignAll(names);
|
||||
logSafe("Fetched \${names.length} global projects");
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Failed to fetch global projects: \$e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchTags() async {
|
||||
try {
|
||||
final response = await ApiService.getContactTagList();
|
||||
if (response != null && response['data'] is List) {
|
||||
tags.assignAll(List<String>.from(
|
||||
response['data'].map((e) => e['name'] ?? '').where((e) => e != ''),
|
||||
));
|
||||
logSafe("Fetched \${tags.length} tags");
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Failed to fetch tags: \$e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
void filterSuggestions(String query) {
|
||||
if (query.trim().isEmpty) {
|
||||
filteredSuggestions.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
final lower = query.toLowerCase();
|
||||
filteredSuggestions.assignAll(
|
||||
tags
|
||||
.where((tag) =>
|
||||
tag.toLowerCase().contains(lower) && !enteredTags.contains(tag))
|
||||
.toList(),
|
||||
);
|
||||
logSafe("Filtered tag suggestions for: \$query", level: LogLevel.debug);
|
||||
}
|
||||
|
||||
void clearSuggestions() {
|
||||
filteredSuggestions.clear();
|
||||
logSafe("Cleared tag suggestions", level: LogLevel.debug);
|
||||
}
|
||||
|
||||
Future<void> fetchCategories() async {
|
||||
try {
|
||||
final response = await ApiService.getContactCategoryList();
|
||||
if (response != null && response['data'] is List) {
|
||||
final names = <String>[];
|
||||
for (var item in response['data']) {
|
||||
final name = item['name']?.toString().trim();
|
||||
final id = item['id']?.toString().trim();
|
||||
if (name != null && id != null && name.isNotEmpty) {
|
||||
categoriesMap[name] = id;
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
categories.assignAll(names);
|
||||
logSafe("Fetched \${names.length} contact categories");
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Failed to fetch categories: \$e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
void addEnteredTag(String tag) {
|
||||
if (tag.trim().isNotEmpty && !enteredTags.contains(tag.trim())) {
|
||||
enteredTags.add(tag.trim());
|
||||
logSafe("Added tag: \$tag", level: LogLevel.debug);
|
||||
}
|
||||
}
|
||||
|
||||
void removeEnteredTag(String tag) {
|
||||
enteredTags.remove(tag);
|
||||
logSafe("Removed tag: \$tag", level: LogLevel.debug);
|
||||
}
|
||||
}
|
||||
70
lib/controller/directory/create_bucket_controller.dart
Normal file
@ -0,0 +1,70 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
|
||||
class BucketController extends GetxController {
|
||||
RxBool isCreating = false.obs;
|
||||
final RxString name = ''.obs;
|
||||
final RxString description = ''.obs;
|
||||
|
||||
Future<void> createBucket() async {
|
||||
if (name.value.trim().isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: "Missing Name",
|
||||
message: "Bucket name is required.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
isCreating.value = true;
|
||||
|
||||
try {
|
||||
logSafe("Creating bucket: ${name.value}");
|
||||
|
||||
final success = await ApiService.createBucket(
|
||||
name: name.value.trim(),
|
||||
description: description.value.trim(),
|
||||
);
|
||||
|
||||
if (success) {
|
||||
logSafe("Bucket created successfully");
|
||||
|
||||
Get.back(result: true); // Close bottom sheet/dialog
|
||||
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Bucket has been created successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
logSafe("Bucket creation failed", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Creation Failed",
|
||||
message: "Unable to create bucket. Please try again later.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error during bucket creation: $e", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Unexpected Error",
|
||||
message: "Something went wrong. Please try again.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isCreating.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void updateName(String value) {
|
||||
name.value = value;
|
||||
logSafe("Bucket name updated: ${value.trim()}");
|
||||
}
|
||||
|
||||
void updateDescription(String value) {
|
||||
description.value = value;
|
||||
logSafe("Bucket description updated: ${value.trim()}");
|
||||
}
|
||||
}
|
||||
390
lib/controller/directory/directory_controller.dart
Normal file
@ -0,0 +1,390 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/model/directory/contact_model.dart';
|
||||
import 'package:on_field_work/model/directory/contact_bucket_list_model.dart';
|
||||
import 'package:on_field_work/model/directory/directory_comment_model.dart';
|
||||
|
||||
class DirectoryController extends GetxController {
|
||||
// -------------------- CONTACTS --------------------
|
||||
RxList<ContactModel> allContacts = <ContactModel>[].obs;
|
||||
RxList<ContactModel> filteredContacts = <ContactModel>[].obs;
|
||||
RxList<ContactCategory> contactCategories = <ContactCategory>[].obs;
|
||||
RxList<String> selectedCategories = <String>[].obs;
|
||||
RxList<String> selectedBuckets = <String>[].obs;
|
||||
RxBool isActive = true.obs;
|
||||
RxBool isLoading = false.obs;
|
||||
RxList<ContactBucket> contactBuckets = <ContactBucket>[].obs;
|
||||
RxString searchQuery = ''.obs;
|
||||
|
||||
// -------------------- COMMENTS --------------------
|
||||
final Map<String, RxList<DirectoryComment>> activeCommentsMap = {};
|
||||
final Map<String, RxList<DirectoryComment>> inactiveCommentsMap = {};
|
||||
final editingCommentId = Rxn<String>();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchContacts();
|
||||
fetchBuckets();
|
||||
}
|
||||
|
||||
// -------------------- COMMENTS HANDLING --------------------
|
||||
|
||||
RxList<DirectoryComment> getCommentsForContact(String contactId,
|
||||
{bool active = true}) {
|
||||
return active
|
||||
? activeCommentsMap[contactId] ?? <DirectoryComment>[].obs
|
||||
: inactiveCommentsMap[contactId] ?? <DirectoryComment>[].obs;
|
||||
}
|
||||
|
||||
Future<void> fetchCommentsForContact(String contactId,
|
||||
{bool active = true}) async {
|
||||
try {
|
||||
final data =
|
||||
await ApiService.getDirectoryComments(contactId, active: active);
|
||||
var comments =
|
||||
data?.map((e) => DirectoryComment.fromJson(e)).toList() ?? [];
|
||||
|
||||
// ✅ Deduplicate by ID before storing
|
||||
final Map<String, DirectoryComment> uniqueMap = {
|
||||
for (var c in comments) c.id: c,
|
||||
};
|
||||
comments = uniqueMap.values.toList()
|
||||
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
|
||||
|
||||
if (active) {
|
||||
activeCommentsMap[contactId] = <DirectoryComment>[].obs
|
||||
..assignAll(comments);
|
||||
} else {
|
||||
inactiveCommentsMap[contactId] = <DirectoryComment>[].obs
|
||||
..assignAll(comments);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Error fetching ${active ? 'active' : 'inactive'} comments: $e",
|
||||
level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
|
||||
if (active) {
|
||||
activeCommentsMap[contactId] = <DirectoryComment>[].obs;
|
||||
} else {
|
||||
inactiveCommentsMap[contactId] = <DirectoryComment>[].obs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<DirectoryComment> combinedComments(String contactId) {
|
||||
final activeList = getCommentsForContact(contactId, active: true);
|
||||
final inactiveList = getCommentsForContact(contactId, active: false);
|
||||
|
||||
// ✅ Deduplicate by ID (active wins)
|
||||
final Map<String, DirectoryComment> byId = {};
|
||||
for (final c in inactiveList) {
|
||||
byId[c.id] = c;
|
||||
}
|
||||
for (final c in activeList) {
|
||||
byId[c.id] = c;
|
||||
}
|
||||
|
||||
final combined = byId.values.toList()
|
||||
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
|
||||
return combined;
|
||||
}
|
||||
|
||||
Future<void> updateComment(DirectoryComment comment) async {
|
||||
try {
|
||||
final existing = getCommentsForContact(comment.contactId)
|
||||
.firstWhereOrNull((c) => c.id == comment.id);
|
||||
|
||||
if (existing != null && existing.note.trim() == comment.note.trim()) {
|
||||
showAppSnackbar(
|
||||
title: "No Changes",
|
||||
message: "No changes were made to the comment.",
|
||||
type: SnackbarType.info,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final success = await ApiService.updateContactComment(
|
||||
comment.id, comment.note, comment.contactId);
|
||||
|
||||
if (success) {
|
||||
await fetchCommentsForContact(comment.contactId, active: true);
|
||||
await fetchCommentsForContact(comment.contactId, active: false);
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Comment updated successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to update comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Update comment failed: $e", level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to update comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteComment(String commentId, String contactId) async {
|
||||
try {
|
||||
final success = await ApiService.restoreContactComment(commentId, false);
|
||||
|
||||
if (success) {
|
||||
if (editingCommentId.value == commentId) editingCommentId.value = null;
|
||||
await fetchCommentsForContact(contactId, active: true);
|
||||
await fetchCommentsForContact(contactId, active: false);
|
||||
showAppSnackbar(
|
||||
title: "Deleted",
|
||||
message: "Comment deleted successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to delete comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Delete comment failed: $e", level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while deleting comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> restoreComment(String commentId, String contactId) async {
|
||||
try {
|
||||
final success = await ApiService.restoreContactComment(commentId, true);
|
||||
|
||||
if (success) {
|
||||
await fetchCommentsForContact(contactId, active: true);
|
||||
await fetchCommentsForContact(contactId, active: false);
|
||||
showAppSnackbar(
|
||||
title: "Restored",
|
||||
message: "Comment restored successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to restore comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Restore comment failed: $e", level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while restoring comment.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------- CONTACTS HANDLING --------------------
|
||||
|
||||
Future<void> fetchBuckets() async {
|
||||
try {
|
||||
final response = await ApiService.getContactBucketList();
|
||||
if (response != null && response['data'] is List) {
|
||||
final buckets = (response['data'] as List)
|
||||
.map((e) => ContactBucket.fromJson(e))
|
||||
.toList();
|
||||
contactBuckets.assignAll(buckets);
|
||||
} else {
|
||||
contactBuckets.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Bucket fetch error: $e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
// -------------------- CONTACT DELETION / RESTORE --------------------
|
||||
|
||||
Future<void> deleteContact(String contactId) async {
|
||||
try {
|
||||
final success = await ApiService.deleteDirectoryContact(contactId);
|
||||
if (success) {
|
||||
// Refresh contacts after deletion
|
||||
await fetchContacts(active: true);
|
||||
await fetchContacts(active: false);
|
||||
showAppSnackbar(
|
||||
title: "Deleted",
|
||||
message: "Contact deleted successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to delete contact.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Delete contact failed: $e", level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while deleting contact.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> restoreContact(String contactId) async {
|
||||
try {
|
||||
final success = await ApiService.restoreDirectoryContact(contactId);
|
||||
if (success) {
|
||||
// Refresh contacts after restore
|
||||
await fetchContacts(active: true);
|
||||
await fetchContacts(active: false);
|
||||
showAppSnackbar(
|
||||
title: "Restored",
|
||||
message: "Contact restored successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to restore contact.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Restore contact failed: $e", level: LogLevel.error);
|
||||
logSafe(stack.toString(), level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while restoring contact.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchContacts({bool active = true}) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getDirectoryData(isActive: active);
|
||||
|
||||
if (response != null) {
|
||||
final contacts = response.map((e) => ContactModel.fromJson(e)).toList();
|
||||
allContacts.assignAll(contacts);
|
||||
extractCategoriesFromContacts();
|
||||
applyFilters();
|
||||
} else {
|
||||
allContacts.clear();
|
||||
filteredContacts.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Directory fetch error: $e", level: LogLevel.error);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void extractCategoriesFromContacts() {
|
||||
final uniqueCategories = <String, ContactCategory>{};
|
||||
for (final contact in allContacts) {
|
||||
final category = contact.contactCategory;
|
||||
if (category != null) {
|
||||
uniqueCategories.putIfAbsent(category.id, () => category);
|
||||
}
|
||||
}
|
||||
contactCategories.value = uniqueCategories.values.toList();
|
||||
}
|
||||
|
||||
void applyFilters() {
|
||||
final query = searchQuery.value.toLowerCase();
|
||||
|
||||
filteredContacts.value = allContacts.where((contact) {
|
||||
final categoryMatch = selectedCategories.isEmpty ||
|
||||
(contact.contactCategory != null &&
|
||||
selectedCategories.contains(contact.contactCategory!.id));
|
||||
|
||||
final bucketMatch = selectedBuckets.isEmpty ||
|
||||
contact.bucketIds.any((id) => selectedBuckets.contains(id));
|
||||
|
||||
final nameMatch = contact.name.toLowerCase().contains(query);
|
||||
final orgMatch = contact.organization.toLowerCase().contains(query);
|
||||
final emailMatch = contact.contactEmails
|
||||
.any((e) => e.emailAddress.toLowerCase().contains(query));
|
||||
final phoneMatch = contact.contactPhones
|
||||
.any((p) => p.phoneNumber.toLowerCase().contains(query));
|
||||
final tagMatch =
|
||||
contact.tags.any((tag) => tag.name.toLowerCase().contains(query));
|
||||
final categoryNameMatch =
|
||||
contact.contactCategory?.name.toLowerCase().contains(query) ?? false;
|
||||
|
||||
final bucketNameMatch = contact.bucketIds.any((id) {
|
||||
final bucketName = contactBuckets
|
||||
.firstWhereOrNull((b) => b.id == id)
|
||||
?.name
|
||||
.toLowerCase() ??
|
||||
'';
|
||||
return bucketName.contains(query);
|
||||
});
|
||||
|
||||
final searchMatch = query.isEmpty ||
|
||||
nameMatch ||
|
||||
orgMatch ||
|
||||
emailMatch ||
|
||||
phoneMatch ||
|
||||
tagMatch ||
|
||||
categoryNameMatch ||
|
||||
bucketNameMatch;
|
||||
|
||||
return categoryMatch && bucketMatch && searchMatch;
|
||||
}).toList();
|
||||
|
||||
filteredContacts
|
||||
.sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
|
||||
}
|
||||
|
||||
void toggleCategory(String categoryId) {
|
||||
if (selectedCategories.contains(categoryId)) {
|
||||
selectedCategories.remove(categoryId);
|
||||
} else {
|
||||
selectedCategories.add(categoryId);
|
||||
}
|
||||
}
|
||||
|
||||
void toggleBucket(String bucketId) {
|
||||
if (selectedBuckets.contains(bucketId)) {
|
||||
selectedBuckets.remove(bucketId);
|
||||
} else {
|
||||
selectedBuckets.add(bucketId);
|
||||
}
|
||||
}
|
||||
|
||||
void updateSearchQuery(String value) {
|
||||
searchQuery.value = value;
|
||||
applyFilters();
|
||||
}
|
||||
|
||||
String getBucketNames(ContactModel contact, List<ContactBucket> allBuckets) {
|
||||
return contact.bucketIds
|
||||
.map((id) => allBuckets.firstWhereOrNull((b) => b.id == id)?.name ?? '')
|
||||
.where((name) => name.isNotEmpty)
|
||||
.join(', ');
|
||||
}
|
||||
|
||||
bool hasActiveFilters() {
|
||||
return selectedCategories.isNotEmpty ||
|
||||
selectedBuckets.isNotEmpty ||
|
||||
searchQuery.value.trim().isNotEmpty;
|
||||
}
|
||||
}
|
||||
152
lib/controller/directory/manage_bucket_controller.dart
Normal file
@ -0,0 +1,152 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/controller/directory/directory_controller.dart';
|
||||
|
||||
class ManageBucketController extends GetxController {
|
||||
RxList<EmployeeModel> allEmployees = <EmployeeModel>[].obs;
|
||||
RxBool isLoading = false.obs;
|
||||
|
||||
final DirectoryController directoryController = Get.find();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchAllEmployees();
|
||||
}
|
||||
|
||||
Future<bool> updateBucket({
|
||||
required String id,
|
||||
required String name,
|
||||
required String description,
|
||||
required List<String> employeeIds,
|
||||
required List<String> originalEmployeeIds,
|
||||
}) async {
|
||||
isLoading(true);
|
||||
update();
|
||||
|
||||
try {
|
||||
final updated = await ApiService.updateBucket(
|
||||
id: id,
|
||||
name: name,
|
||||
description: description,
|
||||
);
|
||||
|
||||
if (!updated) {
|
||||
showAppSnackbar(
|
||||
title: "Update Failed",
|
||||
message: "Unable to update bucket details.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
isLoading(false);
|
||||
update();
|
||||
return false;
|
||||
}
|
||||
|
||||
final allInvolvedIds = {...originalEmployeeIds, ...employeeIds}.toList();
|
||||
|
||||
final assignPayload = allInvolvedIds.map((empId) {
|
||||
return {
|
||||
"employeeId": empId,
|
||||
"isActive": employeeIds.contains(empId),
|
||||
};
|
||||
}).toList();
|
||||
|
||||
final assigned = await ApiService.assignEmployeesToBucket(
|
||||
bucketId: id,
|
||||
employees: assignPayload,
|
||||
);
|
||||
|
||||
if (!assigned) {
|
||||
showAppSnackbar(
|
||||
title: "Assignment Failed",
|
||||
message: "Employees couldn't be updated.",
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Bucket updated successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (e, stack) {
|
||||
logSafe("Error in updateBucket: $e", level: LogLevel.error);
|
||||
logSafe("Stack: $stack", level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Unexpected Error",
|
||||
message: "Please try again later.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
isLoading(false);
|
||||
update();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchAllEmployees() async {
|
||||
isLoading.value = true;
|
||||
|
||||
try {
|
||||
final response = await ApiService.getAllEmployees();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
allEmployees.assignAll(
|
||||
response.map((json) => EmployeeModel.fromJson(json)));
|
||||
logSafe(
|
||||
"All Employees fetched for Manage Bucket: ${allEmployees.length}",
|
||||
level: LogLevel.info,
|
||||
);
|
||||
} else {
|
||||
allEmployees.clear();
|
||||
logSafe("No employees found for Manage Bucket.",
|
||||
level: LogLevel.warning);
|
||||
}
|
||||
} catch (e) {
|
||||
allEmployees.clear();
|
||||
logSafe("Error fetching employees in Manage Bucket",
|
||||
level: LogLevel.error, error: e);
|
||||
}
|
||||
|
||||
isLoading.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> deleteBucket(String bucketId) async {
|
||||
isLoading.value = true;
|
||||
update();
|
||||
|
||||
try {
|
||||
final deleted = await ApiService.deleteBucket(bucketId);
|
||||
if (deleted) {
|
||||
directoryController.contactBuckets.removeWhere((b) => b.id == bucketId);
|
||||
showAppSnackbar(
|
||||
title: "Deleted",
|
||||
message: "Bucket deleted successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Delete Failed",
|
||||
message: "Unable to delete bucket.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Error deleting bucket: $e", level: LogLevel.error);
|
||||
logSafe("Stack: $stack", level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Unexpected Error",
|
||||
message: "Failed to delete bucket.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
update();
|
||||
}
|
||||
}
|
||||
}
|
||||
169
lib/controller/directory/notes_controller.dart
Normal file
@ -0,0 +1,169 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/model/directory/note_list_response_model.dart';
|
||||
|
||||
class NotesController extends GetxController {
|
||||
RxList<NoteModel> notesList = <NoteModel>[].obs;
|
||||
RxBool isLoading = false.obs;
|
||||
RxnString editingNoteId = RxnString();
|
||||
RxString searchQuery = ''.obs;
|
||||
|
||||
List<NoteModel> get filteredNotesList {
|
||||
if (searchQuery.isEmpty) return notesList;
|
||||
|
||||
final query = searchQuery.value.toLowerCase();
|
||||
return notesList.where((note) {
|
||||
return note.note.toLowerCase().contains(query) ||
|
||||
note.contactName.toLowerCase().contains(query) ||
|
||||
note.organizationName.toLowerCase().contains(query) ||
|
||||
note.createdBy.firstName.toLowerCase().contains(query);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchNotes();
|
||||
}
|
||||
|
||||
Future<void> fetchNotes({int pageSize = 1000, int pageNumber = 1}) async {
|
||||
isLoading.value = true;
|
||||
logSafe(
|
||||
"📤 Fetching directory notes with pageSize=$pageSize & pageNumber=$pageNumber");
|
||||
|
||||
try {
|
||||
final response = await ApiService.getDirectoryNotes(
|
||||
pageSize: pageSize, pageNumber: pageNumber);
|
||||
logSafe("💡 Directory Notes Response: $response");
|
||||
|
||||
if (response == null) {
|
||||
logSafe("⚠️ Response is null while fetching directory notes");
|
||||
notesList.clear();
|
||||
} else {
|
||||
logSafe("💡 Directory Notes Response: $response");
|
||||
notesList.value = NotePaginationData.fromJson(response).data;
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe("💥 Error occurred while fetching directory notes",
|
||||
error: e, stackTrace: st);
|
||||
notesList.clear();
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateNote(NoteModel updatedNote) async {
|
||||
try {
|
||||
logSafe(
|
||||
"Attempting to update note. id: ${updatedNote.id}, contactId: ${updatedNote.contactId}");
|
||||
|
||||
final oldNote = notesList.firstWhereOrNull((n) => n.id == updatedNote.id);
|
||||
|
||||
if (oldNote != null && oldNote.note.trim() == updatedNote.note.trim()) {
|
||||
logSafe("No changes detected in note. id: ${updatedNote.id}");
|
||||
showAppSnackbar(
|
||||
title: "No Changes",
|
||||
message: "No changes were made to the note.",
|
||||
type: SnackbarType.info,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final success = await ApiService.updateContactComment(
|
||||
updatedNote.id,
|
||||
updatedNote.note,
|
||||
updatedNote.contactId,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
logSafe("Note updated successfully. id: ${updatedNote.id}");
|
||||
final index = notesList.indexWhere((n) => n.id == updatedNote.id);
|
||||
if (index != -1) {
|
||||
notesList[index] = updatedNote;
|
||||
notesList.refresh();
|
||||
}
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Note updated successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to update note.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
logSafe("Update note failed: ${e.toString()}");
|
||||
logSafe("StackTrace: ${stackTrace.toString()}");
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to update note.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> restoreOrDeleteNote(NoteModel note,
|
||||
{bool restore = true}) async {
|
||||
final action = restore ? "restore" : "delete";
|
||||
|
||||
try {
|
||||
logSafe("Attempting to $action note id: ${note.id}");
|
||||
|
||||
final success = await ApiService.restoreContactComment(
|
||||
note.id,
|
||||
restore, // true = restore, false = delete
|
||||
);
|
||||
|
||||
if (success) {
|
||||
final index = notesList.indexWhere((n) => n.id == note.id);
|
||||
if (index != -1) {
|
||||
notesList[index] = note.copyWith(isActive: restore);
|
||||
notesList.refresh();
|
||||
}
|
||||
showAppSnackbar(
|
||||
title: restore ? "Restored" : "Deleted",
|
||||
message: restore
|
||||
? "Note has been restored successfully."
|
||||
: "Note has been deleted successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message:
|
||||
restore ? "Failed to restore note." : "Failed to delete note.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe("$action note failed: $e", error: e, stackTrace: st);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while trying to $action the note.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void addNote(NoteModel note) {
|
||||
notesList.insert(0, note);
|
||||
logSafe("Note added to list");
|
||||
}
|
||||
|
||||
void deleteNote(int index) {
|
||||
if (index >= 0 && index < notesList.length) {
|
||||
notesList.removeAt(index);
|
||||
logSafe("Note removed from list at index $index");
|
||||
}
|
||||
}
|
||||
|
||||
void clearAllNotes() {
|
||||
notesList.clear();
|
||||
logSafe("All notes cleared from list");
|
||||
}
|
||||
}
|
||||
82
lib/controller/document/document_details_controller.dart
Normal file
@ -0,0 +1,82 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/document/document_details_model.dart';
|
||||
import 'package:on_field_work/model/document/document_version_model.dart';
|
||||
|
||||
class DocumentDetailsController extends GetxController {
|
||||
/// Observables
|
||||
var isLoading = false.obs;
|
||||
var documentDetails = Rxn<DocumentDetailsResponse>();
|
||||
|
||||
var versions = <DocumentVersionItem>[].obs;
|
||||
var isVersionsLoading = false.obs;
|
||||
|
||||
// Loading states for buttons
|
||||
var isVerifyLoading = false.obs;
|
||||
var isRejectLoading = false.obs;
|
||||
|
||||
/// Fetch document details by id
|
||||
Future<void> fetchDocumentDetails(String documentId) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getDocumentDetailsApi(documentId);
|
||||
documentDetails.value = response;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch document versions by parentAttachmentId
|
||||
Future<void> fetchDocumentVersions(String parentAttachmentId) async {
|
||||
try {
|
||||
isVersionsLoading.value = true;
|
||||
final response = await ApiService.getDocumentVersionsApi(
|
||||
parentAttachmentId: parentAttachmentId,
|
||||
);
|
||||
if (response != null) {
|
||||
versions.assignAll(response.data.data);
|
||||
} else {
|
||||
versions.clear();
|
||||
}
|
||||
} finally {
|
||||
isVersionsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify document
|
||||
Future<bool> verifyDocument(String documentId) async {
|
||||
try {
|
||||
isVerifyLoading.value = true;
|
||||
final result =
|
||||
await ApiService.verifyDocumentApi(id: documentId, isVerify: true);
|
||||
if (result) await fetchDocumentDetails(documentId);
|
||||
return result;
|
||||
} finally {
|
||||
isVerifyLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject document
|
||||
Future<bool> rejectDocument(String documentId) async {
|
||||
try {
|
||||
isRejectLoading.value = true;
|
||||
final result =
|
||||
await ApiService.verifyDocumentApi(id: documentId, isVerify: false);
|
||||
if (result) await fetchDocumentDetails(documentId);
|
||||
return result;
|
||||
} finally {
|
||||
isRejectLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch Pre-Signed URL for a given version
|
||||
Future<String?> fetchPresignedUrl(String versionId) async {
|
||||
return await ApiService.getPresignedUrlApi(versionId);
|
||||
}
|
||||
|
||||
/// Clear data when leaving the screen
|
||||
void clearDetails() {
|
||||
documentDetails.value = null;
|
||||
versions.clear();
|
||||
}
|
||||
}
|
||||
239
lib/controller/document/document_upload_controller.dart
Normal file
@ -0,0 +1,239 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/document/master_document_type_model.dart';
|
||||
import 'package:on_field_work/model/document/master_document_tags.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
|
||||
class DocumentUploadController extends GetxController {
|
||||
// Observables
|
||||
var isLoading = false.obs;
|
||||
var isUploading = false.obs;
|
||||
|
||||
var categories = <DocumentType>[].obs;
|
||||
var tags = <TagItem>[].obs;
|
||||
|
||||
DocumentType? selectedCategory;
|
||||
|
||||
/// --- FILE HANDLING ---
|
||||
String? selectedFileName;
|
||||
String? selectedFileBase64;
|
||||
String? selectedFileContentType;
|
||||
int? selectedFileSize;
|
||||
|
||||
/// --- TAG HANDLING ---
|
||||
final tagCtrl = TextEditingController();
|
||||
final enteredTags = <String>[].obs;
|
||||
final filteredSuggestions = <String>[].obs;
|
||||
var documentTypes = <DocumentType>[].obs;
|
||||
DocumentType? selectedType;
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchCategories();
|
||||
fetchTags();
|
||||
}
|
||||
|
||||
/// Fetch available document categories
|
||||
Future<void> fetchCategories() async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getMasterDocumentTypesApi();
|
||||
if (response != null && response.data.isNotEmpty) {
|
||||
categories.assignAll(response.data);
|
||||
logSafe("Fetched categories: ${categories.length}");
|
||||
} else {
|
||||
logSafe("No categories fetched", level: LogLevel.warning);
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchDocumentTypes(String categoryId) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response =
|
||||
await ApiService.getDocumentTypesByCategoryApi(categoryId);
|
||||
if (response != null && response.data.isNotEmpty) {
|
||||
documentTypes.assignAll(response.data);
|
||||
selectedType = null; // reset previous type
|
||||
} else {
|
||||
documentTypes.clear();
|
||||
selectedType = null;
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> fetchPresignedUrl(String versionId) async {
|
||||
return await ApiService.getPresignedUrlApi(versionId);
|
||||
}
|
||||
|
||||
/// Fetch available document tags
|
||||
Future<void> fetchTags() async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getMasterDocumentTagsApi();
|
||||
if (response != null) {
|
||||
tags.assignAll(response.data);
|
||||
logSafe("Fetched tags: ${tags.length}");
|
||||
} else {
|
||||
logSafe("No tags fetched", level: LogLevel.warning);
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// --- TAG LOGIC ---
|
||||
void filterSuggestions(String query) {
|
||||
if (query.isEmpty) {
|
||||
filteredSuggestions.clear();
|
||||
return;
|
||||
}
|
||||
filteredSuggestions.assignAll(
|
||||
tags.map((t) => t.name).where(
|
||||
(tag) => tag.toLowerCase().contains(query.toLowerCase()),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void addEnteredTag(String tag) {
|
||||
if (tag.trim().isEmpty) return;
|
||||
if (!enteredTags.contains(tag.trim())) {
|
||||
enteredTags.add(tag.trim());
|
||||
}
|
||||
}
|
||||
|
||||
void removeEnteredTag(String tag) {
|
||||
enteredTags.remove(tag);
|
||||
}
|
||||
|
||||
void clearSuggestions() {
|
||||
filteredSuggestions.clear();
|
||||
}
|
||||
|
||||
/// Upload document
|
||||
Future<bool> uploadDocument({
|
||||
required String documentId,
|
||||
required String name,
|
||||
required String entityId,
|
||||
required String documentTypeId,
|
||||
required String fileName,
|
||||
required String base64Data,
|
||||
required String contentType,
|
||||
required int fileSize,
|
||||
String? description,
|
||||
}) async {
|
||||
try {
|
||||
isUploading.value = true;
|
||||
|
||||
final payloadTags =
|
||||
enteredTags.map((t) => {"name": t, "isActive": true}).toList();
|
||||
|
||||
final payload = {
|
||||
"documentId": documentId,
|
||||
"name": name,
|
||||
"description": description,
|
||||
"entityId": entityId,
|
||||
"documentTypeId": documentTypeId,
|
||||
"fileName": fileName,
|
||||
"base64Data":
|
||||
base64Data.isNotEmpty ? "<base64-string-truncated>" : null,
|
||||
"contentType": contentType,
|
||||
"fileSize": fileSize,
|
||||
"tags": payloadTags,
|
||||
};
|
||||
|
||||
// Log the payload (hide long base64 string for readability)
|
||||
logSafe("Upload payload: $payload");
|
||||
|
||||
final success = await ApiService.uploadDocumentApi(
|
||||
documentId: documentId,
|
||||
name: name,
|
||||
description: description,
|
||||
entityId: entityId,
|
||||
documentTypeId: documentTypeId,
|
||||
fileName: fileName,
|
||||
base64Data: base64Data,
|
||||
contentType: contentType,
|
||||
fileSize: fileSize,
|
||||
tags: payloadTags,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Document uploaded successfully",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Could not upload document",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
|
||||
return success;
|
||||
} catch (e, stack) {
|
||||
logSafe("Upload error: $e", level: LogLevel.error);
|
||||
logSafe("Stacktrace: $stack", level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "An unexpected error occurred",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> editDocument(Map<String, dynamic> payload) async {
|
||||
try {
|
||||
isUploading.value = true;
|
||||
|
||||
final attachment = payload["attachment"];
|
||||
|
||||
final success = await ApiService.editDocumentApi(
|
||||
id: payload["id"],
|
||||
name: payload["name"],
|
||||
documentId: payload["documentId"],
|
||||
description: payload["description"],
|
||||
tags: (payload["tags"] as List).cast<Map<String, dynamic>>(),
|
||||
attachment: attachment,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message: "Document updated successfully",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to update document",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
|
||||
return success;
|
||||
} catch (e, stack) {
|
||||
logSafe("Edit error: $e", level: LogLevel.error);
|
||||
logSafe("Stacktrace: $stack", level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "An unexpected error occurred",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
isUploading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
226
lib/controller/document/user_document_controller.dart
Normal file
@ -0,0 +1,226 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/document/document_filter_model.dart';
|
||||
import 'package:on_field_work/model/document/documents_list_model.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
|
||||
class DocumentController extends GetxController {
|
||||
// ==================== Observables ====================
|
||||
final isLoading = false.obs;
|
||||
final documents = <DocumentItem>[].obs;
|
||||
final filters = Rxn<DocumentFiltersData>();
|
||||
|
||||
// Selected filters (multi-select)
|
||||
final selectedUploadedBy = <String>[].obs;
|
||||
final selectedCategory = <String>[].obs;
|
||||
final selectedType = <String>[].obs;
|
||||
final selectedTag = <String>[].obs;
|
||||
|
||||
// Pagination
|
||||
final pageNumber = 1.obs;
|
||||
final pageSize = 20;
|
||||
final hasMore = true.obs;
|
||||
|
||||
// Error handling
|
||||
final errorMessage = ''.obs;
|
||||
|
||||
// Preferences
|
||||
final showInactive = false.obs;
|
||||
|
||||
// Search
|
||||
final searchQuery = ''.obs;
|
||||
final searchController = TextEditingController();
|
||||
|
||||
// Additional filters
|
||||
final isUploadedAt = true.obs;
|
||||
final isVerified = RxnBool();
|
||||
final startDate = Rxn<DateTime>();
|
||||
final endDate = Rxn<DateTime>();
|
||||
|
||||
// ==================== Lifecycle ====================
|
||||
@override
|
||||
void onClose() {
|
||||
// Don't dispose searchController here - it's managed by the page
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
// ==================== API Methods ====================
|
||||
|
||||
/// Fetch document filters for entity
|
||||
Future<void> fetchFilters(String entityTypeId) async {
|
||||
try {
|
||||
final response = await ApiService.getDocumentFilters(entityTypeId);
|
||||
|
||||
if (response != null && response.success) {
|
||||
filters.value = response.data;
|
||||
} else {
|
||||
errorMessage.value = response?.message ?? 'Failed to fetch filters';
|
||||
_showError('Failed to load filters');
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Error fetching filters: $e';
|
||||
_showError('Error loading filters');
|
||||
debugPrint('❌ Error fetching filters: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle document active/inactive state
|
||||
Future<bool> toggleDocumentActive(
|
||||
String id, {
|
||||
required bool isActive,
|
||||
required String entityTypeId,
|
||||
required String entityId,
|
||||
}) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
|
||||
final success = await ApiService.deleteDocumentApi(
|
||||
id: id,
|
||||
isActive: isActive,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
// Refresh list after state change
|
||||
await fetchDocuments(
|
||||
entityTypeId: entityTypeId,
|
||||
entityId: entityId,
|
||||
reset: true,
|
||||
);
|
||||
|
||||
// Show success snackbar
|
||||
showAppSnackbar(
|
||||
title: 'Success',
|
||||
message: isActive ? 'Document deactivated' : 'Document activated',
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
|
||||
return true;
|
||||
} else {
|
||||
errorMessage.value = 'Failed to update document state';
|
||||
_showError('Failed to update document state');
|
||||
return false;
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Error updating document: $e';
|
||||
_showError('Error updating document: $e');
|
||||
debugPrint('❌ Error toggling document state: $e');
|
||||
return false;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch documents for entity with pagination
|
||||
Future<void> fetchDocuments({
|
||||
required String entityTypeId,
|
||||
required String entityId,
|
||||
String? filter,
|
||||
String? searchString,
|
||||
bool reset = false,
|
||||
}) async {
|
||||
try {
|
||||
if (reset) {
|
||||
pageNumber.value = 1;
|
||||
documents.clear();
|
||||
hasMore.value = true;
|
||||
}
|
||||
|
||||
if (!hasMore.value && !reset) return;
|
||||
if (isLoading.value) return;
|
||||
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getDocumentListApi(
|
||||
entityTypeId: entityTypeId,
|
||||
entityId: entityId,
|
||||
filter: filter ?? '',
|
||||
searchString: searchString ?? searchQuery.value,
|
||||
pageNumber: pageNumber.value,
|
||||
pageSize: pageSize,
|
||||
isActive: !showInactive.value,
|
||||
);
|
||||
|
||||
if (response != null && response.success) {
|
||||
if (response.data?.data.isNotEmpty ?? false) {
|
||||
documents.addAll(response.data!.data);
|
||||
pageNumber.value++;
|
||||
} else {
|
||||
hasMore.value = false;
|
||||
}
|
||||
errorMessage.value = '';
|
||||
} else {
|
||||
errorMessage.value = response?.message ?? 'Failed to fetch documents';
|
||||
if (documents.isEmpty) {
|
||||
_showError('Failed to load documents');
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: 'Warning',
|
||||
message: 'No more documents to load',
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Error fetching documents: $e';
|
||||
if (documents.isEmpty) {
|
||||
_showError('Error loading documents');
|
||||
} else {
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Error fetching additional documents',
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
debugPrint('❌ Error fetching documents: $e');
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Helper Methods ====================
|
||||
|
||||
/// Clear all selected filters
|
||||
void clearFilters() {
|
||||
selectedUploadedBy.clear();
|
||||
selectedCategory.clear();
|
||||
selectedType.clear();
|
||||
selectedTag.clear();
|
||||
isUploadedAt.value = true;
|
||||
isVerified.value = null;
|
||||
startDate.value = null;
|
||||
endDate.value = null;
|
||||
}
|
||||
|
||||
/// Check if any filters are active
|
||||
bool hasActiveFilters() {
|
||||
return selectedUploadedBy.isNotEmpty ||
|
||||
selectedCategory.isNotEmpty ||
|
||||
selectedType.isNotEmpty ||
|
||||
selectedTag.isNotEmpty ||
|
||||
startDate.value != null ||
|
||||
endDate.value != null ||
|
||||
isVerified.value != null;
|
||||
}
|
||||
|
||||
/// Show error message via snackbar
|
||||
void _showError(String message) {
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: message,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
|
||||
/// Reset controller state
|
||||
void reset() {
|
||||
documents.clear();
|
||||
clearFilters();
|
||||
searchController.clear();
|
||||
searchQuery.value = '';
|
||||
pageNumber.value = 1;
|
||||
hasMore.value = true;
|
||||
showInactive.value = false;
|
||||
errorMessage.value = '';
|
||||
}
|
||||
}
|
||||
62
lib/controller/dynamicMenu/dynamic_menu_controller.dart
Normal file
@ -0,0 +1,62 @@
|
||||
import 'dart:async';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/model/dynamicMenu/dynamic_menu_model.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class DynamicMenuController extends GetxController {
|
||||
// UI reactive states
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxBool hasError = false.obs;
|
||||
final RxString errorMessage = ''.obs;
|
||||
final RxList<MenuItem> menuItems = <MenuItem>[].obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
// Fetch menus directly from API at startup
|
||||
fetchMenu();
|
||||
}
|
||||
|
||||
/// Fetch dynamic menu from API (no local cache)
|
||||
Future<void> fetchMenu() async {
|
||||
isLoading.value = true;
|
||||
hasError.value = false;
|
||||
errorMessage.value = '';
|
||||
|
||||
try {
|
||||
final responseData = await ApiService.getMenuApi();
|
||||
if (responseData != null) {
|
||||
final menuResponse = MenuResponse.fromJson(responseData);
|
||||
menuItems.assignAll(menuResponse.data);
|
||||
|
||||
logSafe("✅ Menu loaded from API with ${menuItems.length} items");
|
||||
} else {
|
||||
_handleApiFailure("Menu API returned null response");
|
||||
}
|
||||
} catch (e) {
|
||||
_handleApiFailure("Menu fetch exception: $e");
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void _handleApiFailure(String logMessage) {
|
||||
logSafe(logMessage, level: LogLevel.error);
|
||||
|
||||
// No cache available, show error state
|
||||
hasError.value = true;
|
||||
errorMessage.value = "❌ Unable to load menus. Please try again later.";
|
||||
menuItems.clear();
|
||||
}
|
||||
|
||||
bool isMenuAllowed(String menuName) {
|
||||
final menu = menuItems.firstWhereOrNull((m) => m.name == menuName);
|
||||
return menu?.available ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
super.onClose();
|
||||
}
|
||||
}
|
||||
310
lib/controller/employee/add_employee_controller.dart
Normal file
@ -0,0 +1,310 @@
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_form_validator.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:flutter_contacts/flutter_contacts.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
enum Gender {
|
||||
male,
|
||||
female,
|
||||
other;
|
||||
|
||||
const Gender();
|
||||
}
|
||||
|
||||
class AddEmployeeController extends MyController {
|
||||
Map<String, dynamic>? editingEmployeeData;
|
||||
|
||||
// State
|
||||
final MyFormValidator basicValidator = MyFormValidator();
|
||||
final List<PlatformFile> files = [];
|
||||
final List<String> categories = [];
|
||||
|
||||
Gender? selectedGender;
|
||||
List<Map<String, dynamic>> roles = [];
|
||||
String? selectedRoleId;
|
||||
String selectedCountryCode = '+91';
|
||||
bool showOnline = true;
|
||||
DateTime? joiningDate;
|
||||
String? selectedOrganizationId;
|
||||
RxString selectedOrganizationName = RxString('');
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
logSafe('Initializing AddEmployeeController...');
|
||||
_initializeFields();
|
||||
fetchRoles();
|
||||
|
||||
if (editingEmployeeData != null) {
|
||||
prefillFields();
|
||||
}
|
||||
}
|
||||
|
||||
void _initializeFields() {
|
||||
basicValidator.addField(
|
||||
'first_name',
|
||||
label: 'First Name',
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
basicValidator.addField(
|
||||
'phone_number',
|
||||
label: 'Phone Number',
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
basicValidator.addField(
|
||||
'last_name',
|
||||
label: 'Last Name',
|
||||
required: true,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
// Email is optional in controller; UI enforces when application access is checked
|
||||
basicValidator.addField(
|
||||
'email',
|
||||
label: 'Email',
|
||||
required: false,
|
||||
controller: TextEditingController(),
|
||||
);
|
||||
|
||||
logSafe('Fields initialized for first_name, phone_number, last_name, email.');
|
||||
}
|
||||
|
||||
// Prefill fields in edit mode
|
||||
void prefillFields() {
|
||||
logSafe('Prefilling data for editing...');
|
||||
basicValidator.getController('first_name')?.text =
|
||||
editingEmployeeData?['first_name'] ?? '';
|
||||
basicValidator.getController('last_name')?.text =
|
||||
editingEmployeeData?['last_name'] ?? '';
|
||||
basicValidator.getController('phone_number')?.text =
|
||||
editingEmployeeData?['phone_number'] ?? '';
|
||||
|
||||
selectedGender = editingEmployeeData?['gender'] != null
|
||||
? Gender.values.firstWhereOrNull((g) => g.name == editingEmployeeData!['gender'])
|
||||
: null;
|
||||
|
||||
basicValidator.getController('email')?.text =
|
||||
editingEmployeeData?['email'] ?? '';
|
||||
|
||||
selectedRoleId = editingEmployeeData?['job_role_id'];
|
||||
|
||||
if (editingEmployeeData?['joining_date'] != null) {
|
||||
joiningDate = DateTime.tryParse(editingEmployeeData!['joining_date']);
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void setJoiningDate(DateTime date) {
|
||||
joiningDate = date;
|
||||
logSafe('Joining date selected: $date');
|
||||
update();
|
||||
}
|
||||
|
||||
void onGenderSelected(Gender? gender) {
|
||||
selectedGender = gender;
|
||||
logSafe('Gender selected: ${gender?.name}');
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> fetchRoles() async {
|
||||
logSafe('Fetching roles...');
|
||||
try {
|
||||
final result = await ApiService.getRoles();
|
||||
if (result != null) {
|
||||
roles = List<Map<String, dynamic>>.from(result);
|
||||
logSafe('Roles fetched successfully.');
|
||||
update();
|
||||
} else {
|
||||
logSafe('Failed to fetch roles: null result', level: LogLevel.error);
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe('Error fetching roles', level: LogLevel.error, error: e, stackTrace: st);
|
||||
}
|
||||
}
|
||||
|
||||
void onRoleSelected(String? roleId) {
|
||||
selectedRoleId = roleId;
|
||||
logSafe('Role selected: $roleId');
|
||||
update();
|
||||
}
|
||||
|
||||
// Create or update employee
|
||||
Future<Map<String, dynamic>?> createOrUpdateEmployee({
|
||||
String? email,
|
||||
bool hasApplicationAccess = false,
|
||||
}) async {
|
||||
logSafe(editingEmployeeData != null
|
||||
? 'Starting employee update...'
|
||||
: 'Starting employee creation...');
|
||||
|
||||
if (selectedGender == null || selectedRoleId == null) {
|
||||
showAppSnackbar(
|
||||
title: 'Missing Fields',
|
||||
message: 'Please select both Gender and Role.',
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
final firstName = basicValidator.getController('first_name')?.text.trim();
|
||||
final lastName = basicValidator.getController('last_name')?.text.trim();
|
||||
final phoneNumber = basicValidator.getController('phone_number')?.text.trim();
|
||||
|
||||
try {
|
||||
// sanitize orgId before sending
|
||||
final String? orgId = (selectedOrganizationId != null &&
|
||||
selectedOrganizationId!.trim().isNotEmpty)
|
||||
? selectedOrganizationId
|
||||
: null;
|
||||
|
||||
final response = await ApiService.createEmployee(
|
||||
id: editingEmployeeData?['id'],
|
||||
firstName: firstName!,
|
||||
lastName: lastName!,
|
||||
phoneNumber: phoneNumber!,
|
||||
gender: selectedGender!.name,
|
||||
jobRoleId: selectedRoleId!,
|
||||
joiningDate: joiningDate?.toIso8601String() ?? '',
|
||||
organizationId: orgId,
|
||||
email: email,
|
||||
hasApplicationAccess: hasApplicationAccess,
|
||||
);
|
||||
|
||||
logSafe('Response: $response');
|
||||
|
||||
if (response != null && response['success'] == true) {
|
||||
showAppSnackbar(
|
||||
title: 'Success',
|
||||
message: editingEmployeeData != null
|
||||
? 'Employee updated successfully!'
|
||||
: 'Employee created successfully!',
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
return response;
|
||||
} else {
|
||||
logSafe('Failed operation', level: LogLevel.error);
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe('Error creating/updating employee',
|
||||
level: LogLevel.error, error: e, stackTrace: st);
|
||||
}
|
||||
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Failed to save employee.',
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<bool> _checkAndRequestContactsPermission() async {
|
||||
final status = await Permission.contacts.request();
|
||||
|
||||
if (status.isGranted) return true;
|
||||
|
||||
if (status.isPermanentlyDenied) {
|
||||
await openAppSettings();
|
||||
}
|
||||
|
||||
showAppSnackbar(
|
||||
title: 'Permission Required',
|
||||
message: 'Please allow Contacts permission from settings to pick a contact.',
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<void> pickContact(BuildContext context) async {
|
||||
final permissionGranted = await _checkAndRequestContactsPermission();
|
||||
if (!permissionGranted) return;
|
||||
|
||||
try {
|
||||
final picked = await FlutterContacts.openExternalPick();
|
||||
if (picked == null) return;
|
||||
|
||||
final contact =
|
||||
await FlutterContacts.getContact(picked.id, withProperties: true);
|
||||
if (contact == null) {
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Failed to load contact details.',
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (contact.phones.isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: 'No Phone Number',
|
||||
message: 'Selected contact has no phone number.',
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final indiaPhones = contact.phones.where((p) {
|
||||
final normalized = p.number.replaceAll(RegExp(r'[^0-9+]'), '');
|
||||
return normalized.startsWith('+91') ||
|
||||
RegExp(r'^\d{10}$').hasMatch(normalized);
|
||||
}).toList();
|
||||
|
||||
if (indiaPhones.isEmpty) {
|
||||
showAppSnackbar(
|
||||
title: 'No Indian Number',
|
||||
message: 'Selected contact has no Indian (+91) phone number.',
|
||||
type: SnackbarType.warning,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
String? selectedPhone;
|
||||
if (indiaPhones.length == 1) {
|
||||
selectedPhone = indiaPhones.first.number;
|
||||
} else {
|
||||
selectedPhone = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Choose an Indian number'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: indiaPhones
|
||||
.map(
|
||||
(p) => ListTile(
|
||||
title: Text(p.number),
|
||||
onTap: () => Navigator.of(ctx).pop(p.number),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (selectedPhone == null) return;
|
||||
}
|
||||
|
||||
final normalizedPhone = selectedPhone.replaceAll(RegExp(r'[^0-9]'), '');
|
||||
final phoneWithoutCountryCode = normalizedPhone.length > 10
|
||||
? normalizedPhone.substring(normalizedPhone.length - 10)
|
||||
: normalizedPhone;
|
||||
|
||||
basicValidator.getController('phone_number')?.text =
|
||||
phoneWithoutCountryCode;
|
||||
update();
|
||||
} catch (e, st) {
|
||||
logSafe('Error fetching contacts',
|
||||
level: LogLevel.error, error: e, stackTrace: st);
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Failed to fetch contacts.',
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
145
lib/controller/employee/assign_projects_controller.dart
Normal file
@ -0,0 +1,145 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/model/global_project_model.dart';
|
||||
import 'package:on_field_work/model/employees/assigned_projects_model.dart';
|
||||
import 'package:on_field_work/controller/project_controller.dart';
|
||||
|
||||
class AssignProjectController extends GetxController {
|
||||
final String employeeId;
|
||||
final String jobRoleId;
|
||||
|
||||
AssignProjectController({
|
||||
required this.employeeId,
|
||||
required this.jobRoleId,
|
||||
});
|
||||
|
||||
final ProjectController projectController = Get.put(ProjectController());
|
||||
|
||||
RxBool isLoading = false.obs;
|
||||
RxBool isAssigning = false.obs;
|
||||
|
||||
RxList<String> assignedProjectIds = <String>[].obs;
|
||||
RxList<String> selectedProjects = <String>[].obs;
|
||||
RxList<GlobalProjectModel> allProjects = <GlobalProjectModel>[].obs;
|
||||
RxList<GlobalProjectModel> filteredProjects = <GlobalProjectModel>[].obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
fetchAllProjectsAndAssignments();
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetch all projects and assigned projects
|
||||
Future<void> fetchAllProjectsAndAssignments() async {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
await projectController.fetchProjects();
|
||||
allProjects.assignAll(projectController.projects);
|
||||
filteredProjects.assignAll(allProjects); // initially show all
|
||||
|
||||
final responseList = await ApiService.getAssignedProjects(employeeId);
|
||||
if (responseList != null) {
|
||||
final assignedProjects =
|
||||
responseList.map((e) => AssignedProject.fromJson(e)).toList();
|
||||
|
||||
assignedProjectIds.assignAll(
|
||||
assignedProjects.map((p) => p.id).toList(),
|
||||
);
|
||||
selectedProjects.assignAll(assignedProjectIds);
|
||||
}
|
||||
|
||||
logSafe("All Projects: ${allProjects.map((e) => e.id)}");
|
||||
logSafe("Assigned Project IDs: $assignedProjectIds");
|
||||
} catch (e, stack) {
|
||||
logSafe("Error fetching projects or assignments: $e",
|
||||
level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Assign selected projects
|
||||
Future<bool> assignProjectsToEmployee() async {
|
||||
if (selectedProjects.isEmpty) {
|
||||
logSafe("No projects selected for assignment.", level: LogLevel.warning);
|
||||
return false;
|
||||
}
|
||||
|
||||
final List<Map<String, dynamic>> projectPayload =
|
||||
selectedProjects.map((id) {
|
||||
return {"projectId": id, "jobRoleId": jobRoleId, "status": true};
|
||||
}).toList();
|
||||
|
||||
isAssigning.value = true;
|
||||
try {
|
||||
final success = await ApiService.assignProjects(
|
||||
employeeId: employeeId,
|
||||
projects: projectPayload,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
logSafe("Projects assigned successfully.");
|
||||
assignedProjectIds.assignAll(selectedProjects);
|
||||
return true;
|
||||
} else {
|
||||
logSafe("Failed to assign projects.", level: LogLevel.error);
|
||||
return false;
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Error assigning projects: $e", level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
return false;
|
||||
} finally {
|
||||
isAssigning.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle project selection
|
||||
void toggleProjectSelection(String projectId, bool isSelected) {
|
||||
if (isSelected) {
|
||||
if (!selectedProjects.contains(projectId)) {
|
||||
selectedProjects.add(projectId);
|
||||
}
|
||||
} else {
|
||||
selectedProjects.remove(projectId);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if project is selected
|
||||
bool isProjectSelected(String projectId) {
|
||||
return selectedProjects.contains(projectId);
|
||||
}
|
||||
|
||||
/// Select all / deselect all
|
||||
void toggleSelectAll() {
|
||||
if (areAllSelected()) {
|
||||
selectedProjects.clear();
|
||||
} else {
|
||||
selectedProjects.assignAll(allProjects.map((p) => p.id.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Are all selected?
|
||||
bool areAllSelected() {
|
||||
return selectedProjects.length == allProjects.length &&
|
||||
allProjects.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Filter projects by search text
|
||||
void filterProjects(String query) {
|
||||
if (query.isEmpty) {
|
||||
filteredProjects.assignAll(allProjects);
|
||||
} else {
|
||||
filteredProjects.assignAll(
|
||||
allProjects
|
||||
.where((p) => p.name.toLowerCase().contains(query.toLowerCase()))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
193
lib/controller/employee/employees_screen_controller.dart
Normal file
@ -0,0 +1,193 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_details_model.dart';
|
||||
|
||||
class EmployeesScreenController extends GetxController {
|
||||
/// ✅ Data lists
|
||||
RxList<EmployeeModel> employees = <EmployeeModel>[].obs;
|
||||
Rxn<EmployeeDetailsModel> selectedEmployeeDetails =
|
||||
Rxn<EmployeeDetailsModel>();
|
||||
|
||||
/// ✅ Loading states
|
||||
RxBool isLoading = false.obs;
|
||||
RxBool isLoadingEmployeeDetails = false.obs;
|
||||
|
||||
/// ✅ Selection state
|
||||
RxBool isAllEmployeeSelected = false.obs;
|
||||
RxSet<String> selectedEmployeeIds = <String>{}.obs;
|
||||
|
||||
/// ✅ Upload state tracking (if needed later)
|
||||
RxMap<String, RxBool> uploadingStates = <String, RxBool>{}.obs;
|
||||
|
||||
RxList<EmployeeModel> selectedEmployeePrimaryManagers = <EmployeeModel>[].obs;
|
||||
RxList<EmployeeModel> selectedEmployeeSecondaryManagers =
|
||||
<EmployeeModel>[].obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchAllEmployees();
|
||||
}
|
||||
|
||||
/// 🔹 Fetch all employees (no project filter)
|
||||
Future<void> fetchAllEmployees({String? organizationId}) async {
|
||||
isLoading.value = true;
|
||||
update(['employee_screen_controller']);
|
||||
|
||||
await _handleApiCall(
|
||||
() => ApiService.getAllEmployees(organizationId: organizationId),
|
||||
onSuccess: (data) {
|
||||
employees.assignAll(data.map((json) => EmployeeModel.fromJson(json)));
|
||||
logSafe(
|
||||
"All Employees fetched: ${employees.length} employees loaded.",
|
||||
level: LogLevel.info,
|
||||
);
|
||||
|
||||
// Reset selection states when new data arrives
|
||||
selectedEmployeeIds.clear();
|
||||
isAllEmployeeSelected.value = false;
|
||||
},
|
||||
onEmpty: () {
|
||||
employees.clear();
|
||||
selectedEmployeeIds.clear();
|
||||
isAllEmployeeSelected.value = false;
|
||||
logSafe("No Employee data found or API call failed",
|
||||
level: LogLevel.warning);
|
||||
},
|
||||
);
|
||||
|
||||
isLoading.value = false;
|
||||
update(['employee_screen_controller']);
|
||||
}
|
||||
|
||||
/// 🔹 Fetch details for a specific employee
|
||||
Future<void> fetchEmployeeDetails(String? employeeId) async {
|
||||
if (employeeId == null || employeeId.isEmpty) return;
|
||||
|
||||
isLoadingEmployeeDetails.value = true;
|
||||
|
||||
await _handleSingleApiCall(
|
||||
() => ApiService.getEmployeeDetails(employeeId),
|
||||
onSuccess: (data) {
|
||||
selectedEmployeeDetails.value = EmployeeDetailsModel.fromJson(data);
|
||||
logSafe("Employee details loaded for $employeeId",
|
||||
level: LogLevel.info);
|
||||
},
|
||||
onEmpty: () {
|
||||
selectedEmployeeDetails.value = null;
|
||||
logSafe("No employee details found for $employeeId",
|
||||
level: LogLevel.warning);
|
||||
},
|
||||
onError: (e) {
|
||||
selectedEmployeeDetails.value = null;
|
||||
logSafe("Error fetching employee details for $employeeId",
|
||||
level: LogLevel.error, error: e);
|
||||
},
|
||||
);
|
||||
|
||||
isLoadingEmployeeDetails.value = false;
|
||||
}
|
||||
|
||||
/// Fetch reporting managers for a specific employee from /organization/hierarchy/list/:employeeId
|
||||
Future<void> fetchReportingManagers(String? employeeId) async {
|
||||
if (employeeId == null || employeeId.isEmpty) return;
|
||||
|
||||
try {
|
||||
// ✅ Always clear before new fetch (to avoid mixing old data)
|
||||
selectedEmployeePrimaryManagers.clear();
|
||||
selectedEmployeeSecondaryManagers.clear();
|
||||
|
||||
// Fetch from existing API helper
|
||||
final data = await ApiService.getOrganizationHierarchyList(employeeId);
|
||||
|
||||
if (data == null || data.isEmpty) {
|
||||
update(['employee_screen_controller']);
|
||||
return;
|
||||
}
|
||||
|
||||
for (final item in data) {
|
||||
try {
|
||||
final reportTo = item['reportTo'];
|
||||
if (reportTo == null) continue;
|
||||
|
||||
final emp = EmployeeModel.fromJson(reportTo);
|
||||
final isPrimary = item['isPrimary'] == true;
|
||||
|
||||
if (isPrimary) {
|
||||
if (!selectedEmployeePrimaryManagers.any((e) => e.id == emp.id)) {
|
||||
selectedEmployeePrimaryManagers.add(emp);
|
||||
}
|
||||
} else {
|
||||
if (!selectedEmployeeSecondaryManagers.any((e) => e.id == emp.id)) {
|
||||
selectedEmployeeSecondaryManagers.add(emp);
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore malformed items
|
||||
}
|
||||
}
|
||||
|
||||
update(['employee_screen_controller']);
|
||||
} catch (e) {
|
||||
logSafe("Error fetching reporting managers for $employeeId",
|
||||
level: LogLevel.error, error: e);
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔹 Clear all employee data
|
||||
void clearEmployees() {
|
||||
employees.clear();
|
||||
selectedEmployeeIds.clear();
|
||||
isAllEmployeeSelected.value = false;
|
||||
logSafe("Employees cleared", level: LogLevel.info);
|
||||
update(['employee_screen_controller']);
|
||||
}
|
||||
|
||||
/// 🔹 Generic handler for list API responses
|
||||
Future<void> _handleApiCall(
|
||||
Future<List<dynamic>?> Function() apiCall, {
|
||||
required Function(List<dynamic>) onSuccess,
|
||||
required Function() onEmpty,
|
||||
Function(dynamic error)? onError,
|
||||
}) async {
|
||||
try {
|
||||
final response = await apiCall();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
onSuccess(response);
|
||||
} else {
|
||||
onEmpty();
|
||||
}
|
||||
} catch (e) {
|
||||
if (onError != null) {
|
||||
onError(e);
|
||||
} else {
|
||||
logSafe("API call error", level: LogLevel.error, error: e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔹 Generic handler for single-object API responses
|
||||
Future<void> _handleSingleApiCall(
|
||||
Future<Map<String, dynamic>?> Function() apiCall, {
|
||||
required Function(Map<String, dynamic>) onSuccess,
|
||||
required Function() onEmpty,
|
||||
Function(dynamic error)? onError,
|
||||
}) async {
|
||||
try {
|
||||
final response = await apiCall();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
onSuccess(response);
|
||||
} else {
|
||||
onEmpty();
|
||||
}
|
||||
} catch (e) {
|
||||
if (onError != null) {
|
||||
onError(e);
|
||||
} else {
|
||||
logSafe("API call error", level: LogLevel.error, error: e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
|
||||
class ComingSoonController extends MyController {
|
||||
Timer? countdownTimer;
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
|
||||
class Error404Controller extends MyController {
|
||||
void goToDashboardScreen() {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
|
||||
class Error500Controller extends MyController {
|
||||
void goToDashboardScreen() {
|
||||
|
||||
562
lib/controller/expense/add_expense_controller.dart
Normal file
@ -0,0 +1,562 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:geocoding/geocoding.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:mime/mime.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
|
||||
import 'package:on_field_work/controller/expense/expense_screen_controller.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/model/expense/expense_type_model.dart';
|
||||
import 'package:on_field_work/model/expense/payment_types_model.dart';
|
||||
import 'package:on_field_work/helpers/widgets/time_stamp_image_helper.dart';
|
||||
|
||||
class AddExpenseController extends GetxController {
|
||||
// --- Text Controllers ---
|
||||
final controllers = <TextEditingController>[
|
||||
TextEditingController(), // amount
|
||||
TextEditingController(), // description
|
||||
TextEditingController(), // supplier
|
||||
TextEditingController(), // transactionId
|
||||
TextEditingController(), // gst
|
||||
TextEditingController(), // location
|
||||
TextEditingController(), // transactionDate
|
||||
TextEditingController(), // noOfPersons
|
||||
TextEditingController(), // employeeSearch
|
||||
];
|
||||
|
||||
TextEditingController get amountController => controllers[0];
|
||||
TextEditingController get descriptionController => controllers[1];
|
||||
TextEditingController get supplierController => controllers[2];
|
||||
TextEditingController get transactionIdController => controllers[3];
|
||||
TextEditingController get gstController => controllers[4];
|
||||
TextEditingController get locationController => controllers[5];
|
||||
TextEditingController get transactionDateController => controllers[6];
|
||||
TextEditingController get noOfPersonsController => controllers[7];
|
||||
TextEditingController get employeeSearchController => controllers[8];
|
||||
|
||||
// --- Reactive State ---
|
||||
final isLoading = false.obs;
|
||||
final isSubmitting = false.obs;
|
||||
final isFetchingLocation = false.obs;
|
||||
final isEditMode = false.obs;
|
||||
final isSearchingEmployees = false.obs;
|
||||
|
||||
// --- Paid By (Single + Multi Selection Support) ---
|
||||
|
||||
// single selection
|
||||
final selectedPaidBy = Rxn<EmployeeModel>();
|
||||
|
||||
|
||||
|
||||
// helper setters
|
||||
void setSelectedPaidBy(EmployeeModel? emp) {
|
||||
selectedPaidBy.value = emp;
|
||||
}
|
||||
|
||||
// --- Dropdown Selections & Data ---
|
||||
final selectedPaymentMode = Rxn<PaymentModeModel>();
|
||||
final selectedExpenseType = Rxn<ExpenseTypeModel>();
|
||||
// final selectedPaidBy = Rxn<EmployeeModel>();
|
||||
final selectedProject = ''.obs;
|
||||
final selectedTransactionDate = Rxn<DateTime>();
|
||||
|
||||
final attachments = <File>[].obs;
|
||||
final existingAttachments = <Map<String, dynamic>>[].obs;
|
||||
final globalProjects = <String>[].obs;
|
||||
final projectsMap = <String, String>{}.obs;
|
||||
|
||||
final expenseTypes = <ExpenseTypeModel>[].obs;
|
||||
final paymentModes = <PaymentModeModel>[].obs;
|
||||
final allEmployees = <EmployeeModel>[].obs;
|
||||
final employeeSearchResults = <EmployeeModel>[].obs;
|
||||
final isProcessingAttachment = false.obs;
|
||||
|
||||
String? editingExpenseId;
|
||||
|
||||
final expenseController = Get.find<ExpenseController>();
|
||||
final ImagePicker _picker = ImagePicker();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
loadMasterData();
|
||||
employeeSearchController.addListener(
|
||||
() => searchEmployees(employeeSearchController.text),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
for (var c in controllers) {
|
||||
c.dispose();
|
||||
}
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
// --- Employee Search ---
|
||||
Future<void> searchEmployees(String query) async {
|
||||
if (query.trim().isEmpty) return employeeSearchResults.clear();
|
||||
isSearchingEmployees.value = true;
|
||||
try {
|
||||
final data = await ApiService.searchEmployeesBasic(
|
||||
searchString: query.trim(),
|
||||
);
|
||||
|
||||
if (data is List) {
|
||||
employeeSearchResults.assignAll(
|
||||
data
|
||||
.map((e) => EmployeeModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
} else {
|
||||
employeeSearchResults.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error searching employees: $e", level: LogLevel.error);
|
||||
employeeSearchResults.clear();
|
||||
} finally {
|
||||
isSearchingEmployees.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Form Population (Edit) ---
|
||||
Future<void> populateFieldsForEdit(Map<String, dynamic> data) async {
|
||||
isEditMode.value = true;
|
||||
editingExpenseId = '${data['id']}';
|
||||
|
||||
selectedProject.value = data['projectName'] ?? '';
|
||||
amountController.text = '${data['amount'] ?? ''}';
|
||||
supplierController.text = data['supplerName'] ?? '';
|
||||
descriptionController.text = data['description'] ?? '';
|
||||
transactionIdController.text = data['transactionId'] ?? '';
|
||||
locationController.text = data['location'] ?? '';
|
||||
noOfPersonsController.text = '${data['noOfPersons'] ?? 0}';
|
||||
|
||||
_setTransactionDate(data['transactionDate']);
|
||||
_setDropdowns(data);
|
||||
await _setPaidBy(data);
|
||||
_setAttachments(data['attachments']);
|
||||
|
||||
_logPrefilledData();
|
||||
}
|
||||
|
||||
void _setTransactionDate(dynamic dateStr) {
|
||||
if (dateStr == null) {
|
||||
selectedTransactionDate.value = null;
|
||||
transactionDateController.clear();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final parsed = DateTime.parse(dateStr);
|
||||
selectedTransactionDate.value = parsed;
|
||||
transactionDateController.text = DateFormat('dd-MM-yyyy').format(parsed);
|
||||
} catch (_) {
|
||||
selectedTransactionDate.value = null;
|
||||
transactionDateController.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void _setDropdowns(Map<String, dynamic> data) {
|
||||
selectedExpenseType.value =
|
||||
expenseTypes.firstWhereOrNull((e) => e.id == data['expensesTypeId']);
|
||||
selectedPaymentMode.value =
|
||||
paymentModes.firstWhereOrNull((e) => e.id == data['paymentModeId']);
|
||||
}
|
||||
|
||||
Future<void> _setPaidBy(Map<String, dynamic> data) async {
|
||||
final paidById = '${data['paidById']}';
|
||||
selectedPaidBy.value =
|
||||
allEmployees.firstWhereOrNull((e) => e.id.trim() == paidById.trim());
|
||||
|
||||
if (selectedPaidBy.value == null && data['paidByFirstName'] != null) {
|
||||
await searchEmployees(
|
||||
'${data['paidByFirstName']} ${data['paidByLastName']}',
|
||||
);
|
||||
selectedPaidBy.value = employeeSearchResults
|
||||
.firstWhereOrNull((e) => e.id.trim() == paidById.trim());
|
||||
}
|
||||
}
|
||||
|
||||
void _setAttachments(dynamic attachmentsData) {
|
||||
existingAttachments.clear();
|
||||
if (attachmentsData is List) {
|
||||
existingAttachments.addAll(
|
||||
List<Map<String, dynamic>>.from(attachmentsData).map(
|
||||
(e) => {...e, 'isActive': true},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _logPrefilledData() {
|
||||
final info = [
|
||||
'ID: $editingExpenseId',
|
||||
'Project: ${selectedProject.value}',
|
||||
'Amount: ${amountController.text}',
|
||||
'Supplier: ${supplierController.text}',
|
||||
'Description: ${descriptionController.text}',
|
||||
'Transaction ID: ${transactionIdController.text}',
|
||||
'Location: ${locationController.text}',
|
||||
'Transaction Date: ${transactionDateController.text}',
|
||||
'No. of Persons: ${noOfPersonsController.text}',
|
||||
'Expense Category: ${selectedExpenseType.value?.name}',
|
||||
'Payment Mode: ${selectedPaymentMode.value?.name}',
|
||||
'Paid By: ${selectedPaidBy.value?.name}',
|
||||
'Attachments: ${attachments.length}',
|
||||
'Existing Attachments: ${existingAttachments.length}',
|
||||
];
|
||||
for (var line in info) {
|
||||
logSafe(line, level: LogLevel.info);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Pickers ---
|
||||
Future<void> pickTransactionDate(BuildContext context) async {
|
||||
final pickedDate = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: selectedTransactionDate.value ?? DateTime.now(),
|
||||
firstDate: DateTime(DateTime.now().year - 5),
|
||||
lastDate: DateTime.now(),
|
||||
);
|
||||
|
||||
if (pickedDate != null) {
|
||||
final now = DateTime.now();
|
||||
final finalDateTime = DateTime(
|
||||
pickedDate.year,
|
||||
pickedDate.month,
|
||||
pickedDate.day,
|
||||
now.hour,
|
||||
now.minute,
|
||||
now.second,
|
||||
);
|
||||
selectedTransactionDate.value = finalDateTime;
|
||||
transactionDateController.text =
|
||||
DateFormat('dd MMM yyyy').format(finalDateTime);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> pickAttachments() async {
|
||||
try {
|
||||
final result = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'],
|
||||
allowMultiple: true,
|
||||
);
|
||||
if (result != null) {
|
||||
attachments.addAll(
|
||||
result.paths.whereType<String>().map(File.new),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Attachment error: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void removeAttachment(File file) => attachments.remove(file);
|
||||
|
||||
Future<void> pickFromCamera() async {
|
||||
try {
|
||||
final pickedFile = await _picker.pickImage(source: ImageSource.camera);
|
||||
if (pickedFile != null) {
|
||||
isProcessingAttachment.value = true; // start loading
|
||||
File imageFile = File(pickedFile.path);
|
||||
|
||||
// Add timestamp to the captured image
|
||||
File timestampedFile = await TimestampImageHelper.addTimestamp(
|
||||
imageFile: imageFile,
|
||||
);
|
||||
|
||||
attachments.add(timestampedFile);
|
||||
attachments.refresh(); // refresh UI
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Camera error: $e");
|
||||
} finally {
|
||||
isProcessingAttachment.value = false; // stop loading
|
||||
}
|
||||
}
|
||||
|
||||
// --- Location ---
|
||||
Future<void> fetchCurrentLocation() async {
|
||||
isFetchingLocation.value = true;
|
||||
try {
|
||||
if (!await _ensureLocationPermission()) return;
|
||||
|
||||
final position = await Geolocator.getCurrentPosition();
|
||||
final placemarks =
|
||||
await placemarkFromCoordinates(position.latitude, position.longitude);
|
||||
|
||||
locationController.text = placemarks.isNotEmpty
|
||||
? [
|
||||
placemarks.first.name,
|
||||
placemarks.first.street,
|
||||
placemarks.first.locality,
|
||||
placemarks.first.administrativeArea,
|
||||
placemarks.first.country,
|
||||
].where((e) => e?.isNotEmpty == true).join(", ")
|
||||
: "${position.latitude}, ${position.longitude}";
|
||||
} catch (e) {
|
||||
_errorSnackbar("Location error: $e");
|
||||
} finally {
|
||||
isFetchingLocation.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _ensureLocationPermission() async {
|
||||
var permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied ||
|
||||
permission == LocationPermission.deniedForever) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied ||
|
||||
permission == LocationPermission.deniedForever) {
|
||||
_errorSnackbar("Location permission denied.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!await Geolocator.isLocationServiceEnabled()) {
|
||||
_errorSnackbar("Location service disabled.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- Data Fetching ---
|
||||
Future<void> loadMasterData() async =>
|
||||
Future.wait([fetchMasterData(), fetchGlobalProjects()]);
|
||||
|
||||
Future<void> fetchMasterData() async {
|
||||
try {
|
||||
final types = await ApiService.getMasterExpenseTypes();
|
||||
if (types is List) {
|
||||
expenseTypes.value = types
|
||||
.map((e) => ExpenseTypeModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
final modes = await ApiService.getMasterPaymentModes();
|
||||
if (modes is List) {
|
||||
paymentModes.value = modes
|
||||
.map((e) => PaymentModeModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
} catch (_) {
|
||||
_errorSnackbar("Failed to fetch master data");
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fetchGlobalProjects() async {
|
||||
try {
|
||||
final response = await ApiService.getGlobalProjects();
|
||||
if (response != null) {
|
||||
final names = <String>[];
|
||||
for (var item in response) {
|
||||
final name = item['name']?.toString().trim();
|
||||
final id = item['id']?.toString().trim();
|
||||
if (name != null && id != null) {
|
||||
projectsMap[name] = id;
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
globalProjects.assignAll(names);
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error fetching projects: $e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Submission ---
|
||||
Future<void> submitOrUpdateExpense() async {
|
||||
if (isSubmitting.value) return;
|
||||
isSubmitting.value = true;
|
||||
try {
|
||||
final validationMsg = validateForm();
|
||||
if (validationMsg.isNotEmpty) {
|
||||
_errorSnackbar(validationMsg, "Missing Fields");
|
||||
return;
|
||||
}
|
||||
|
||||
final payload = await _buildExpensePayload();
|
||||
final success = await _submitToApi(payload);
|
||||
|
||||
if (success) {
|
||||
await expenseController.fetchExpenses();
|
||||
Get.back();
|
||||
showAppSnackbar(
|
||||
title: "Success",
|
||||
message:
|
||||
"Expense ${isEditMode.value ? 'updated' : 'created'} successfully!",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
_errorSnackbar("Operation failed. Try again.");
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Unexpected error: $e");
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _submitToApi(Map<String, dynamic>? payload) async {
|
||||
if (payload == null) {
|
||||
_errorSnackbar("Payload is empty. Cannot submit.");
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (isEditMode.value && editingExpenseId != null) {
|
||||
// Edit existing expense
|
||||
return await ApiService.editExpenseApi(
|
||||
expenseId: editingExpenseId!,
|
||||
payload: payload,
|
||||
);
|
||||
} else {
|
||||
// Create new expense
|
||||
return await ApiService.createExpenseApi(
|
||||
projectId: payload['projectId'],
|
||||
expensesTypeId: payload['expenseCategoryId'],
|
||||
paymentModeId: payload['paymentModeId'],
|
||||
paidById: payload['paidById'],
|
||||
transactionDate: DateTime.parse(payload['transactionDate']),
|
||||
transactionId: payload['transactionId'],
|
||||
description: payload['description'],
|
||||
location: payload['location'],
|
||||
supplerName: payload['supplerName'],
|
||||
amount: payload['amount'],
|
||||
noOfPersons: payload['noOfPersons'],
|
||||
billAttachments: payload['billAttachments'],
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Failed to submit expense: $e");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> _buildExpensePayload() async {
|
||||
final now = DateTime.now();
|
||||
|
||||
// --- Get IDs safely ---
|
||||
final projectId = projectsMap[selectedProject.value];
|
||||
final expenseType = selectedExpenseType.value;
|
||||
final paymentMode = selectedPaymentMode.value;
|
||||
final paidBy = selectedPaidBy.value;
|
||||
|
||||
// --- Validate essential fields ---
|
||||
if (projectId == null) {
|
||||
_errorSnackbar("Project not selected or invalid");
|
||||
return null;
|
||||
}
|
||||
if (expenseType == null) {
|
||||
_errorSnackbar("Expense Category not selected");
|
||||
return null;
|
||||
}
|
||||
if (paymentMode == null) {
|
||||
_errorSnackbar("Payment mode not selected");
|
||||
return null;
|
||||
}
|
||||
if (paidBy == null) {
|
||||
_errorSnackbar("Paid By not selected");
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Process existing attachments (for edit mode) ---
|
||||
final existingPayload = isEditMode.value
|
||||
? existingAttachments
|
||||
.map((e) => {
|
||||
"documentId": e['documentId'],
|
||||
"fileName": e['fileName'] ?? "",
|
||||
"contentType": e['contentType'] ?? "",
|
||||
"fileSize": 0,
|
||||
"description": "",
|
||||
"url": e['url'] ?? "",
|
||||
"isActive": e['isActive'] ?? true,
|
||||
"base64Data": "",
|
||||
})
|
||||
.toList()
|
||||
: <Map<String, dynamic>>[];
|
||||
|
||||
// --- Process new attachments ---
|
||||
final newPayload = await Future.wait(
|
||||
attachments.map((file) async {
|
||||
final bytes = await file.readAsBytes();
|
||||
return {
|
||||
"fileName": file.path.split('/').last,
|
||||
"base64Data": base64Encode(bytes),
|
||||
"contentType":
|
||||
lookupMimeType(file.path) ?? 'application/octet-stream',
|
||||
"fileSize": await file.length(),
|
||||
"description": "",
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
// --- Build final payload ---
|
||||
final payload = {
|
||||
if (isEditMode.value && editingExpenseId != null) "id": editingExpenseId,
|
||||
"projectId": projectId,
|
||||
"expenseCategoryId": expenseType.id,
|
||||
"paymentModeId": paymentMode.id,
|
||||
"paidById": paidBy.id,
|
||||
"transactionDate":
|
||||
(selectedTransactionDate.value ?? now).toUtc().toIso8601String(),
|
||||
"transactionId": transactionIdController.text.trim(),
|
||||
"description": descriptionController.text.trim(),
|
||||
"location": locationController.text.trim(),
|
||||
"supplerName": supplierController.text.trim(),
|
||||
"amount": double.tryParse(amountController.text.trim()) ?? 0,
|
||||
"noOfPersons": expenseType.noOfPersonsRequired == true
|
||||
? int.tryParse(noOfPersonsController.text.trim()) ?? 0
|
||||
: 0,
|
||||
"billAttachments": [...existingPayload, ...newPayload].isEmpty
|
||||
? null
|
||||
: [...existingPayload, ...newPayload],
|
||||
};
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
String validateForm() {
|
||||
final missing = <String>[];
|
||||
|
||||
if (selectedProject.value.isEmpty) missing.add("Project");
|
||||
if (selectedExpenseType.value == null) missing.add("Expense Category");
|
||||
if (selectedPaymentMode.value == null) missing.add("Payment Mode");
|
||||
if (selectedPaidBy.value == null) missing.add("Paid By");
|
||||
if (amountController.text.trim().isEmpty) missing.add("Amount");
|
||||
if (descriptionController.text.trim().isEmpty) missing.add("Description");
|
||||
|
||||
if (selectedTransactionDate.value == null) {
|
||||
missing.add("Transaction Date");
|
||||
} else if (selectedTransactionDate.value!.isAfter(DateTime.now())) {
|
||||
missing.add("Valid Transaction Date");
|
||||
}
|
||||
|
||||
if (double.tryParse(amountController.text.trim()) == null) {
|
||||
missing.add("Valid Amount");
|
||||
}
|
||||
|
||||
final hasActiveExisting =
|
||||
existingAttachments.any((e) => e['isActive'] != false);
|
||||
if (attachments.isEmpty && !hasActiveExisting) {
|
||||
missing.add("Attachment");
|
||||
}
|
||||
|
||||
return missing.isEmpty ? '' : "Please provide: ${missing.join(', ')}.";
|
||||
}
|
||||
|
||||
// --- Snackbar Helper ---
|
||||
void _errorSnackbar(String msg, [String title = "Error"]) {
|
||||
showAppSnackbar(title: title, message: msg, type: SnackbarType.error);
|
||||
}
|
||||
}
|
||||
194
lib/controller/expense/expense_detail_controller.dart
Normal file
@ -0,0 +1,194 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/model/expense/expense_detail_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ExpenseDetailController extends GetxController {
|
||||
final Rx<ExpenseDetailModel?> expense = Rx<ExpenseDetailModel?>(null);
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxString errorMessage = ''.obs;
|
||||
final Rx<EmployeeModel?> selectedReimbursedBy = Rx<EmployeeModel?>(null);
|
||||
final RxList<EmployeeModel> allEmployees = <EmployeeModel>[].obs;
|
||||
final RxList<EmployeeModel> employeeSearchResults = <EmployeeModel>[].obs;
|
||||
late String _expenseId;
|
||||
bool _isInitialized = false;
|
||||
final employeeSearchController = TextEditingController();
|
||||
final isSearchingEmployees = false.obs;
|
||||
|
||||
/// Call this once from the screen (NOT inside build) to initialize
|
||||
void init(String expenseId) {
|
||||
if (_isInitialized) return;
|
||||
|
||||
_isInitialized = true;
|
||||
_expenseId = expenseId;
|
||||
|
||||
// Use Future.wait to fetch details and employees concurrently
|
||||
Future.wait([
|
||||
fetchExpenseDetails(),
|
||||
fetchAllEmployees(),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Generic method to handle API calls with loading and error states
|
||||
Future<T?> _apiCallWrapper<T>(
|
||||
Future<T?> Function() apiCall, String operationName) async {
|
||||
isLoading.value = true;
|
||||
errorMessage.value = ''; // Clear previous errors
|
||||
|
||||
try {
|
||||
logSafe("Initiating $operationName...");
|
||||
final result = await apiCall();
|
||||
logSafe("$operationName completed successfully.");
|
||||
return result;
|
||||
} catch (e, stack) {
|
||||
errorMessage.value =
|
||||
'An unexpected error occurred during $operationName.';
|
||||
logSafe("Exception in $operationName: $e", level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
return null;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch expense details by stored ID
|
||||
Future<void> fetchExpenseDetails() async {
|
||||
final result = await _apiCallWrapper(
|
||||
() => ApiService.getExpenseDetailsApi(expenseId: _expenseId),
|
||||
"fetch expense details");
|
||||
|
||||
if (result != null) {
|
||||
try {
|
||||
expense.value = ExpenseDetailModel.fromJson(result);
|
||||
logSafe("Expense details loaded successfully: ${expense.value?.id}");
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Failed to parse expense details: $e';
|
||||
logSafe("Parse error in fetchExpenseDetails: $e",
|
||||
level: LogLevel.error);
|
||||
}
|
||||
} else {
|
||||
errorMessage.value = 'Failed to fetch expense details from server.';
|
||||
logSafe("fetchExpenseDetails failed: null response",
|
||||
level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
// This method seems like a utility and might be better placed in a helper or utility class
|
||||
// if it's used across multiple controllers. Keeping it here for now as per original code.
|
||||
List<String> parsePermissionIds(dynamic permissionData) {
|
||||
if (permissionData == null) return [];
|
||||
if (permissionData is List) {
|
||||
return permissionData
|
||||
.map((e) => e.toString().trim())
|
||||
.where((e) => e.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
if (permissionData is String) {
|
||||
final clean = permissionData.replaceAll(RegExp(r'[\[\]]'), '');
|
||||
return clean
|
||||
.split(',')
|
||||
.map((e) => e.trim())
|
||||
.where((e) => e.isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
Future<void> searchEmployees(String query) async {
|
||||
if (query.trim().isEmpty) return employeeSearchResults.clear();
|
||||
isSearchingEmployees.value = true;
|
||||
try {
|
||||
final data =
|
||||
await ApiService.searchEmployeesBasic(searchString: query.trim());
|
||||
employeeSearchResults.assignAll(
|
||||
(data ?? []).map((e) => EmployeeModel.fromJson(e)),
|
||||
);
|
||||
} catch (e) {
|
||||
logSafe("Error searching employees: $e", level: LogLevel.error);
|
||||
employeeSearchResults.clear();
|
||||
} finally {
|
||||
isSearchingEmployees.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch all employees
|
||||
Future<void> fetchAllEmployees() async {
|
||||
final response = await _apiCallWrapper(
|
||||
() => ApiService.getAllEmployees(), "fetch all employees");
|
||||
|
||||
if (response != null && response.isNotEmpty) {
|
||||
try {
|
||||
allEmployees.assignAll(response.map((e) => EmployeeModel.fromJson(e)));
|
||||
logSafe("All Employees fetched: ${allEmployees.length}",
|
||||
level: LogLevel.info);
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Failed to parse employee data: $e';
|
||||
logSafe("Parse error in fetchAllEmployees: $e", level: LogLevel.error);
|
||||
}
|
||||
} else {
|
||||
allEmployees.clear();
|
||||
logSafe("No employees found.", level: LogLevel.warning);
|
||||
}
|
||||
// `update()` is typically not needed for RxList directly unless you have specific GetBuilder/Obx usage that requires it
|
||||
// If you are using Obx widgets, `allEmployees.assignAll` will automatically trigger a rebuild.
|
||||
}
|
||||
|
||||
/// Update expense with reimbursement info and status
|
||||
Future<bool> updateExpenseStatusWithReimbursement({
|
||||
required String comment,
|
||||
required String reimburseTransactionId,
|
||||
required String reimburseDate,
|
||||
required String reimburseById,
|
||||
required String statusId,
|
||||
double? baseAmount,
|
||||
double? taxAmount,
|
||||
double? tdsPercent,
|
||||
double? netPayable,
|
||||
}) async {
|
||||
final success = await _apiCallWrapper(
|
||||
() => ApiService.updateExpenseStatusApi(
|
||||
expenseId: _expenseId,
|
||||
statusId: statusId,
|
||||
comment: comment,
|
||||
reimburseTransactionId: reimburseTransactionId,
|
||||
reimburseDate: reimburseDate,
|
||||
reimbursedById: reimburseById,
|
||||
baseAmount: baseAmount,
|
||||
taxAmount: taxAmount,
|
||||
tdsPercent: tdsPercent,
|
||||
netPayable: netPayable,
|
||||
),
|
||||
"submit reimbursement",
|
||||
);
|
||||
|
||||
if (success == true) {
|
||||
await fetchExpenseDetails();
|
||||
return true;
|
||||
} else {
|
||||
errorMessage.value = "Failed to submit reimbursement.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Update status for this specific expense
|
||||
Future<bool> updateExpenseStatus(String statusId, {String? comment}) async {
|
||||
final success = await _apiCallWrapper(
|
||||
() => ApiService.updateExpenseStatusApi(
|
||||
expenseId: _expenseId,
|
||||
statusId: statusId,
|
||||
comment: comment,
|
||||
),
|
||||
"update expense status",
|
||||
);
|
||||
|
||||
if (success == true) {
|
||||
await fetchExpenseDetails();
|
||||
return true;
|
||||
} else {
|
||||
errorMessage.value = "Failed to update expense status.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
357
lib/controller/expense/expense_screen_controller.dart
Normal file
@ -0,0 +1,357 @@
|
||||
import 'dart:convert';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/model/expense/expense_list_model.dart';
|
||||
import 'package:on_field_work/model/expense/payment_types_model.dart';
|
||||
import 'package:on_field_work/model/expense/expense_type_model.dart';
|
||||
import 'package:on_field_work/model/expense/expense_status_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ExpenseController extends GetxController {
|
||||
final RxList<ExpenseModel> expenses = <ExpenseModel>[].obs;
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxString errorMessage = ''.obs;
|
||||
|
||||
// Master data
|
||||
final RxList<ExpenseTypeModel> expenseTypes = <ExpenseTypeModel>[].obs;
|
||||
final RxList<PaymentModeModel> paymentModes = <PaymentModeModel>[].obs;
|
||||
final RxList<ExpenseStatusModel> expenseStatuses = <ExpenseStatusModel>[].obs;
|
||||
final RxList<String> globalProjects = <String>[].obs;
|
||||
final RxMap<String, String> projectsMap = <String, String>{}.obs;
|
||||
RxList<EmployeeModel> allEmployees = <EmployeeModel>[].obs;
|
||||
|
||||
// Persistent Filter States
|
||||
final RxString selectedProject = ''.obs;
|
||||
final RxString selectedStatus = ''.obs;
|
||||
final Rx<DateTime?> startDate = Rx<DateTime?>(null);
|
||||
final Rx<DateTime?> endDate = Rx<DateTime?>(null);
|
||||
final RxList<EmployeeModel> selectedPaidByEmployees = <EmployeeModel>[].obs;
|
||||
final RxList<EmployeeModel> selectedCreatedByEmployees =
|
||||
<EmployeeModel>[].obs;
|
||||
final RxString selectedDateType = 'Transaction Date'.obs;
|
||||
|
||||
final employeeSearchController = TextEditingController();
|
||||
final isSearchingEmployees = false.obs;
|
||||
final employeeSearchResults = <EmployeeModel>[].obs;
|
||||
|
||||
final List<String> dateTypes = [
|
||||
'Transaction Date',
|
||||
'Created At',
|
||||
];
|
||||
|
||||
int _pageSize = 20;
|
||||
int _pageNumber = 1;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
loadInitialMasterData();
|
||||
fetchAllEmployees();
|
||||
employeeSearchController.addListener(() {
|
||||
searchEmployees(employeeSearchController.text);
|
||||
});
|
||||
}
|
||||
|
||||
bool get isFilterApplied {
|
||||
return selectedProject.value.isNotEmpty ||
|
||||
selectedStatus.value.isNotEmpty ||
|
||||
startDate.value != null ||
|
||||
endDate.value != null ||
|
||||
selectedPaidByEmployees.isNotEmpty ||
|
||||
selectedCreatedByEmployees.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Load master data
|
||||
Future<void> loadInitialMasterData() async {
|
||||
await fetchGlobalProjects();
|
||||
await fetchMasterData();
|
||||
}
|
||||
|
||||
Future<void> deleteExpense(String expenseId) async {
|
||||
try {
|
||||
logSafe("Attempting to delete expense: $expenseId");
|
||||
final success = await ApiService.deleteExpense(expenseId);
|
||||
if (success) {
|
||||
expenses.removeWhere((e) => e.id == expenseId);
|
||||
logSafe("Expense deleted successfully.");
|
||||
showAppSnackbar(
|
||||
title: "Deleted",
|
||||
message: "Expense has been deleted successfully.",
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
} else {
|
||||
logSafe("Failed to delete expense: $expenseId", level: LogLevel.error);
|
||||
showAppSnackbar(
|
||||
title: "Failed",
|
||||
message: "Failed to delete expense.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Exception in deleteExpense: $e", level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Something went wrong while deleting.",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> searchEmployees(String searchQuery) async {
|
||||
if (searchQuery.trim().isEmpty) {
|
||||
employeeSearchResults.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
isSearchingEmployees.value = true;
|
||||
try {
|
||||
final results = await ApiService.searchEmployeesBasic(
|
||||
searchString: searchQuery.trim(),
|
||||
);
|
||||
|
||||
if (results != null) {
|
||||
employeeSearchResults.assignAll(
|
||||
results.map((e) => EmployeeModel.fromJson(e)),
|
||||
);
|
||||
} else {
|
||||
employeeSearchResults.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error searching employees: $e", level: LogLevel.error);
|
||||
employeeSearchResults.clear();
|
||||
} finally {
|
||||
isSearchingEmployees.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch expenses using filters
|
||||
Future<void> fetchExpenses({
|
||||
List<String>? projectIds,
|
||||
List<String>? statusIds,
|
||||
List<String>? createdByIds,
|
||||
List<String>? paidByIds,
|
||||
DateTime? startDate,
|
||||
DateTime? endDate,
|
||||
int pageSize = 20,
|
||||
int pageNumber = 1,
|
||||
}) async {
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
expenses.clear();
|
||||
_pageSize = pageSize;
|
||||
_pageNumber = pageNumber;
|
||||
|
||||
final Map<String, dynamic> filterMap = {
|
||||
"projectIds": projectIds ??
|
||||
(selectedProject.value.isEmpty
|
||||
? []
|
||||
: [projectsMap[selectedProject.value] ?? '']),
|
||||
"statusIds": statusIds ??
|
||||
(selectedStatus.value.isEmpty ? [] : [selectedStatus.value]),
|
||||
"createdByIds":
|
||||
createdByIds ?? selectedCreatedByEmployees.map((e) => e.id).toList(),
|
||||
"paidByIds":
|
||||
paidByIds ?? selectedPaidByEmployees.map((e) => e.id).toList(),
|
||||
"startDate": (startDate ?? this.startDate.value)?.toIso8601String(),
|
||||
"endDate": (endDate ?? this.endDate.value)?.toIso8601String(),
|
||||
"isTransactionDate": selectedDateType.value == 'Transaction Date',
|
||||
};
|
||||
|
||||
try {
|
||||
logSafe("Fetching expenses with filter: ${jsonEncode(filterMap)}");
|
||||
|
||||
final result = await ApiService.getExpenseListApi(
|
||||
filter: jsonEncode(filterMap),
|
||||
pageSize: _pageSize,
|
||||
pageNumber: _pageNumber,
|
||||
);
|
||||
|
||||
if (result != null) {
|
||||
try {
|
||||
final expenseResponse = ExpenseResponse.fromJson(result);
|
||||
|
||||
// If the backend returns no data, treat it as empty list
|
||||
if (expenseResponse.data.data.isEmpty) {
|
||||
expenses.clear();
|
||||
errorMessage.value = ''; // no error
|
||||
logSafe("Expense list is empty.");
|
||||
} else {
|
||||
expenses.assignAll(expenseResponse.data.data);
|
||||
logSafe("Expenses loaded: ${expenses.length}");
|
||||
logSafe(
|
||||
"Pagination Info: Page ${expenseResponse.data.currentPage} of ${expenseResponse.data.totalPages} | Total: ${expenseResponse.data.totalEntites}");
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Failed to parse expenses: $e';
|
||||
logSafe("Parse error in fetchExpenses: $e", level: LogLevel.error);
|
||||
}
|
||||
} else {
|
||||
// Only treat as error if this means a network or server failure
|
||||
errorMessage.value = 'Unable to connect to the server.';
|
||||
logSafe("fetchExpenses failed: null response", level: LogLevel.error);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
errorMessage.value = 'An unexpected error occurred.';
|
||||
logSafe("Exception in fetchExpenses: $e", level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all filters
|
||||
void clearFilters() {
|
||||
selectedProject.value = '';
|
||||
selectedStatus.value = '';
|
||||
startDate.value = null;
|
||||
endDate.value = null;
|
||||
selectedPaidByEmployees.clear();
|
||||
selectedCreatedByEmployees.clear();
|
||||
}
|
||||
|
||||
/// Fetch master data: Expense Categorys, payment modes, and expense status
|
||||
Future<void> fetchMasterData() async {
|
||||
try {
|
||||
final expenseTypesData = await ApiService.getMasterExpenseTypes();
|
||||
if (expenseTypesData is List) {
|
||||
expenseTypes.value =
|
||||
expenseTypesData.map((e) => ExpenseTypeModel.fromJson(e)).toList();
|
||||
}
|
||||
|
||||
final paymentModesData = await ApiService.getMasterPaymentModes();
|
||||
if (paymentModesData is List) {
|
||||
paymentModes.value =
|
||||
paymentModesData.map((e) => PaymentModeModel.fromJson(e)).toList();
|
||||
}
|
||||
|
||||
final expenseStatusData = await ApiService.getMasterExpenseStatus();
|
||||
if (expenseStatusData is List) {
|
||||
expenseStatuses.value = expenseStatusData
|
||||
.map((e) => ExpenseStatusModel.fromJson(e))
|
||||
.toList();
|
||||
}
|
||||
} catch (e) {
|
||||
showAppSnackbar(
|
||||
title: "Error",
|
||||
message: "Failed to fetch master data: $e",
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch global projects
|
||||
Future<void> fetchGlobalProjects() async {
|
||||
try {
|
||||
final response = await ApiService.getGlobalProjects();
|
||||
if (response != null) {
|
||||
final names = <String>[];
|
||||
for (var item in response) {
|
||||
final name = item['name']?.toString().trim();
|
||||
final id = item['id']?.toString().trim();
|
||||
if (name != null && id != null && name.isNotEmpty) {
|
||||
projectsMap[name] = id;
|
||||
names.add(name);
|
||||
}
|
||||
}
|
||||
globalProjects.assignAll(names);
|
||||
logSafe("Fetched ${names.length} global projects");
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Failed to fetch global projects: $e", level: LogLevel.error);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch all employees
|
||||
Future<void> fetchAllEmployees() async {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
final response = await ApiService.getAllEmployees();
|
||||
if (response != null && response.isNotEmpty) {
|
||||
allEmployees
|
||||
.assignAll(response.map((json) => EmployeeModel.fromJson(json)));
|
||||
logSafe(
|
||||
"All Employees fetched for Manage Bucket: ${allEmployees.length}",
|
||||
level: LogLevel.info,
|
||||
);
|
||||
} else {
|
||||
allEmployees.clear();
|
||||
logSafe("No employees found for Manage Bucket.",
|
||||
level: LogLevel.warning);
|
||||
}
|
||||
} catch (e) {
|
||||
allEmployees.clear();
|
||||
logSafe("Error fetching employees in Manage Bucket",
|
||||
level: LogLevel.error, error: e);
|
||||
}
|
||||
isLoading.value = false;
|
||||
update();
|
||||
}
|
||||
|
||||
Future<void> loadMoreExpenses() async {
|
||||
if (isLoading.value) return;
|
||||
|
||||
_pageNumber += 1;
|
||||
isLoading.value = true;
|
||||
|
||||
final Map<String, dynamic> filterMap = {
|
||||
"projectIds": selectedProject.value.isEmpty
|
||||
? []
|
||||
: [projectsMap[selectedProject.value] ?? ''],
|
||||
"statusIds": selectedStatus.value.isEmpty ? [] : [selectedStatus.value],
|
||||
"createdByIds": selectedCreatedByEmployees.map((e) => e.id).toList(),
|
||||
"paidByIds": selectedPaidByEmployees.map((e) => e.id).toList(),
|
||||
"startDate": startDate.value?.toIso8601String(),
|
||||
"endDate": endDate.value?.toIso8601String(),
|
||||
"isTransactionDate": selectedDateType.value == 'Transaction Date',
|
||||
};
|
||||
|
||||
try {
|
||||
final result = await ApiService.getExpenseListApi(
|
||||
filter: jsonEncode(filterMap),
|
||||
pageSize: _pageSize,
|
||||
pageNumber: _pageNumber,
|
||||
);
|
||||
|
||||
if (result != null) {
|
||||
final expenseResponse = ExpenseResponse.fromJson(result);
|
||||
expenses.addAll(expenseResponse.data.data);
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error in loadMoreExpenses: $e", level: LogLevel.error);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Update expense status
|
||||
Future<bool> updateExpenseStatus(String expenseId, String statusId) async {
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
try {
|
||||
logSafe("Updating status for expense: $expenseId -> $statusId");
|
||||
final success = await ApiService.updateExpenseStatusApi(
|
||||
expenseId: expenseId,
|
||||
statusId: statusId,
|
||||
);
|
||||
if (success) {
|
||||
logSafe("Expense status updated successfully.");
|
||||
await fetchExpenses();
|
||||
return true;
|
||||
} else {
|
||||
errorMessage.value = "Failed to update expense status.";
|
||||
return false;
|
||||
}
|
||||
} catch (e, stack) {
|
||||
errorMessage.value = 'An unexpected error occurred.';
|
||||
logSafe("Exception in updateExpenseStatus: $e", level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
return false;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/widgets/my_text_utils.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_text_utils.dart';
|
||||
|
||||
class FaqsController extends MyController {
|
||||
final List<bool> dataExpansionPanel = [true, false, false, false, false, false];
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
|
||||
class PricingController extends MyController {
|
||||
bool isMonth = false;
|
||||
|
||||
@ -1,17 +0,0 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:marco/helpers/widgets/my_text_utils.dart';
|
||||
import 'package:marco/model/time_line.dart';
|
||||
|
||||
class TimeLineController extends MyController {
|
||||
List<TimeLineModel> timeline = [];
|
||||
List<String> dummyTexts = List.generate(12, (index) => MyTextUtils.getDummyText(60));
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
TimeLineModel.dummyList.then((value) {
|
||||
timeline = value.sublist(0, 6);
|
||||
update();
|
||||
});
|
||||
super.onInit();
|
||||
}
|
||||
}
|
||||
419
lib/controller/finance/add_payment_request_controller.dart
Normal file
@ -0,0 +1,419 @@
|
||||
// payment_request_controller.dart
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:mime/mime.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/helpers/widgets/time_stamp_image_helper.dart';
|
||||
import 'package:on_field_work/model/finance/expense_category_model.dart';
|
||||
import 'package:on_field_work/model/finance/currency_list_model.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
|
||||
class AddPaymentRequestController extends GetxController {
|
||||
// Loading States
|
||||
final isLoadingPayees = false.obs;
|
||||
final isLoadingCategories = false.obs;
|
||||
final isLoadingCurrencies = false.obs;
|
||||
final isProcessingAttachment = false.obs;
|
||||
final isSubmitting = false.obs;
|
||||
|
||||
// Data Lists
|
||||
final payees = <String>[].obs;
|
||||
final categories = <ExpenseCategory>[].obs;
|
||||
final currencies = <Currency>[].obs;
|
||||
final globalProjects = <Map<String, dynamic>>[].obs;
|
||||
|
||||
// Selected Values
|
||||
final selectedProject = Rx<Map<String, dynamic>?>(null);
|
||||
final selectedCategory = Rx<ExpenseCategory?>(null);
|
||||
final selectedPayee = Rx<EmployeeModel?>(null);
|
||||
final selectedCurrency = Rx<Currency?>(null);
|
||||
final isAdvancePayment = false.obs;
|
||||
final selectedDueDate = Rx<DateTime?>(null);
|
||||
|
||||
// Text Controllers
|
||||
final titleController = TextEditingController();
|
||||
final dueDateController = TextEditingController();
|
||||
final amountController = TextEditingController();
|
||||
final descriptionController = TextEditingController();
|
||||
final removedAttachments = <Map<String, dynamic>>[].obs;
|
||||
|
||||
// Attachments
|
||||
final attachments = <File>[].obs;
|
||||
final existingAttachments = <Map<String, dynamic>>[].obs;
|
||||
final ImagePicker _picker = ImagePicker();
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchAllMasterData();
|
||||
fetchGlobalProjects();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
titleController.dispose();
|
||||
dueDateController.dispose();
|
||||
amountController.dispose();
|
||||
descriptionController.dispose();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
/// Fetch all master data concurrently
|
||||
Future<void> fetchAllMasterData() async {
|
||||
await Future.wait([
|
||||
_fetchData(
|
||||
payees, ApiService.getExpensePaymentRequestPayeeApi, isLoadingPayees),
|
||||
_fetchData(categories, ApiService.getMasterExpenseCategoriesApi,
|
||||
isLoadingCategories),
|
||||
_fetchData(
|
||||
currencies, ApiService.getMasterCurrenciesApi, isLoadingCurrencies),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Generic fetch handler
|
||||
Future<void> _fetchData<T>(
|
||||
RxList<T> list, Future<dynamic> Function() apiCall, RxBool loader) async {
|
||||
try {
|
||||
loader.value = true;
|
||||
final response = await apiCall();
|
||||
if (response != null && response.data.isNotEmpty) {
|
||||
list.value = response.data;
|
||||
} else {
|
||||
list.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
logSafe("Error fetching data: $e", level: LogLevel.error);
|
||||
list.clear();
|
||||
} finally {
|
||||
loader.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch projects
|
||||
Future<void> fetchGlobalProjects() async {
|
||||
try {
|
||||
final response = await ApiService.getGlobalProjects();
|
||||
globalProjects.value = (response ?? [])
|
||||
.map<Map<String, dynamic>>((e) => {
|
||||
'id': e['id']?.toString() ?? '',
|
||||
'name': e['name']?.toString().trim() ?? '',
|
||||
})
|
||||
.where((p) => p['id']!.isNotEmpty && p['name']!.isNotEmpty)
|
||||
.toList();
|
||||
} catch (e) {
|
||||
logSafe("Error fetching projects: $e", level: LogLevel.error);
|
||||
globalProjects.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick due date
|
||||
Future<void> pickDueDate(BuildContext context) async {
|
||||
final pickedDate = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: selectedDueDate.value ?? DateTime.now(),
|
||||
firstDate: DateTime(DateTime.now().year - 5),
|
||||
lastDate: DateTime(DateTime.now().year + 5),
|
||||
);
|
||||
|
||||
if (pickedDate != null) {
|
||||
selectedDueDate.value = pickedDate;
|
||||
dueDateController.text = DateFormat('dd MMM yyyy').format(pickedDate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic file picker for multiple sources
|
||||
Future<void> pickAttachments(
|
||||
{bool fromGallery = false, bool fromCamera = false}) async {
|
||||
try {
|
||||
if (fromCamera) {
|
||||
final pickedFile = await _picker.pickImage(source: ImageSource.camera);
|
||||
if (pickedFile != null) {
|
||||
isProcessingAttachment.value = true;
|
||||
final timestamped = await TimestampImageHelper.addTimestamp(
|
||||
imageFile: File(pickedFile.path));
|
||||
attachments.add(timestamped);
|
||||
}
|
||||
} else if (fromGallery) {
|
||||
final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
|
||||
if (pickedFile != null) attachments.add(File(pickedFile.path));
|
||||
} else {
|
||||
final result = await FilePicker.platform
|
||||
.pickFiles(type: FileType.any, allowMultiple: true);
|
||||
if (result != null && result.paths.isNotEmpty)
|
||||
attachments.addAll(result.paths.whereType<String>().map(File.new));
|
||||
}
|
||||
attachments.refresh();
|
||||
} catch (e) {
|
||||
_errorSnackbar("Attachment error: $e");
|
||||
} finally {
|
||||
isProcessingAttachment.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> pickFromCamera() async {
|
||||
try {
|
||||
final pickedFile = await _picker.pickImage(source: ImageSource.camera);
|
||||
if (pickedFile != null) {
|
||||
isProcessingAttachment.value = true;
|
||||
File imageFile = File(pickedFile.path);
|
||||
|
||||
// Add timestamp to the captured image
|
||||
File timestampedFile = await TimestampImageHelper.addTimestamp(
|
||||
imageFile: imageFile,
|
||||
);
|
||||
|
||||
attachments.add(timestampedFile);
|
||||
attachments.refresh(); // refresh UI
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Camera error: $e");
|
||||
} finally {
|
||||
isProcessingAttachment.value = false; // stop loading
|
||||
}
|
||||
}
|
||||
|
||||
/// Selection handlers
|
||||
void selectProject(Map<String, dynamic> project) =>
|
||||
selectedProject.value = project;
|
||||
void selectCategory(ExpenseCategory category) =>
|
||||
selectedCategory.value = category;
|
||||
void selectPayee(EmployeeModel payee) => selectedPayee.value = payee;
|
||||
void selectCurrency(Currency currency) => selectedCurrency.value = currency;
|
||||
|
||||
void addAttachment(File file) => attachments.add(file);
|
||||
void removeAttachment(File file) {
|
||||
if (attachments.contains(file)) {
|
||||
attachments.remove(file);
|
||||
}
|
||||
}
|
||||
|
||||
void removeExistingAttachment(Map<String, dynamic> existingAttachment) {
|
||||
final index = existingAttachments.indexWhere(
|
||||
(e) => e['id'] == existingAttachment['id']); // match by normalized id
|
||||
|
||||
if (index != -1) {
|
||||
// Mark as inactive
|
||||
existingAttachments[index]['isActive'] = false;
|
||||
existingAttachments.refresh();
|
||||
|
||||
// Add to removedAttachments to inform API
|
||||
removedAttachments.add({
|
||||
"documentId": existingAttachment['id'], // ensure API receives id
|
||||
"isActive": false,
|
||||
});
|
||||
|
||||
// Show snackbar feedback
|
||||
showAppSnackbar(
|
||||
title: 'Removed',
|
||||
message: 'Attachment has been removed.',
|
||||
type: SnackbarType.success,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build attachment payload
|
||||
Future<List<Map<String, dynamic>>> buildAttachmentPayload() async {
|
||||
final existingPayload = existingAttachments
|
||||
.map((e) => {
|
||||
"documentId": e['id'], // use the normalized id
|
||||
"fileName": e['fileName'],
|
||||
"contentType": e['contentType'] ?? 'application/octet-stream',
|
||||
"fileSize": e['fileSize'] ?? 0,
|
||||
"description": "",
|
||||
"url": e['url'],
|
||||
"isActive": e['isActive'] ?? true,
|
||||
})
|
||||
.toList();
|
||||
|
||||
final newPayload = await Future.wait(attachments.map((file) async {
|
||||
final bytes = await file.readAsBytes();
|
||||
return {
|
||||
"fileName": file.path.split('/').last,
|
||||
"base64Data": base64Encode(bytes),
|
||||
"contentType": lookupMimeType(file.path) ?? 'application/octet-stream',
|
||||
"fileSize": await file.length(),
|
||||
"description": "",
|
||||
};
|
||||
}));
|
||||
|
||||
// Combine active + removed attachments
|
||||
return [...existingPayload, ...newPayload, ...removedAttachments];
|
||||
}
|
||||
|
||||
/// Submit edited payment request
|
||||
Future<bool> submitEditedPaymentRequest({required String requestId}) async {
|
||||
if (isSubmitting.value) return false;
|
||||
|
||||
try {
|
||||
isSubmitting.value = true;
|
||||
|
||||
// Validate form
|
||||
if (!_validateForm()) return false;
|
||||
|
||||
// Build attachment payload
|
||||
final billAttachments = await buildAttachmentPayload();
|
||||
|
||||
final payload = {
|
||||
"id": requestId,
|
||||
"title": titleController.text.trim(),
|
||||
"projectId": selectedProject.value?['id'] ?? '',
|
||||
"expenseCategoryId": selectedCategory.value?.id ?? '',
|
||||
"amount": double.tryParse(amountController.text.trim()) ?? 0,
|
||||
"currencyId": selectedCurrency.value?.id ?? '',
|
||||
"description": descriptionController.text.trim(),
|
||||
"payee": selectedPayee.value?.id ?? "",
|
||||
"dueDate": selectedDueDate.value?.toIso8601String(),
|
||||
"isAdvancePayment": isAdvancePayment.value,
|
||||
"billAttachments": billAttachments.map((a) {
|
||||
return {
|
||||
"documentId": a['documentId'],
|
||||
"fileName": a['fileName'],
|
||||
"base64Data": a['base64Data'] ?? "",
|
||||
"contentType": a['contentType'],
|
||||
"fileSize": a['fileSize'],
|
||||
"description": a['description'] ?? "",
|
||||
"isActive": a['isActive'] ?? true,
|
||||
};
|
||||
}).toList(),
|
||||
};
|
||||
|
||||
logSafe("💡 Submitting Edited Payment Request: ${jsonEncode(payload)}");
|
||||
|
||||
final success = await ApiService.editExpensePaymentRequestApi(
|
||||
id: payload['id'],
|
||||
title: payload['title'],
|
||||
projectId: payload['projectId'],
|
||||
expenseCategoryId: payload['expenseCategoryId'],
|
||||
amount: payload['amount'],
|
||||
currencyId: payload['currencyId'],
|
||||
description: payload['description'],
|
||||
payee: payload['payee'],
|
||||
dueDate: payload['dueDate'] ?? '',
|
||||
isAdvancePayment: payload['isAdvancePayment'],
|
||||
billAttachments: payload['billAttachments'],
|
||||
);
|
||||
|
||||
logSafe("💡 Edit Payment Request API Response: $success");
|
||||
|
||||
if (success == true) {
|
||||
logSafe("✅ Payment request edited successfully.");
|
||||
return true;
|
||||
} else {
|
||||
return _errorSnackbar("Failed to edit payment request.");
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe("💥 Submit Edited Payment Request Error: $e\n$st",
|
||||
level: LogLevel.error);
|
||||
return _errorSnackbar("Something went wrong. Please try again later.");
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Submit payment request (Project API style)
|
||||
Future<bool> submitPaymentRequest() async {
|
||||
if (isSubmitting.value) return false;
|
||||
|
||||
try {
|
||||
isSubmitting.value = true;
|
||||
|
||||
// Validate form
|
||||
if (!_validateForm()) return false;
|
||||
|
||||
// Build attachment payload
|
||||
final billAttachments = await buildAttachmentPayload();
|
||||
|
||||
final payload = {
|
||||
"title": titleController.text.trim(),
|
||||
"projectId": selectedProject.value?['id'] ?? '',
|
||||
"expenseCategoryId": selectedCategory.value?.id ?? '',
|
||||
"amount": double.tryParse(amountController.text.trim()) ?? 0,
|
||||
"currencyId": selectedCurrency.value?.id ?? '',
|
||||
"description": descriptionController.text.trim(),
|
||||
"payee": selectedPayee.value?.id ?? "",
|
||||
"dueDate": selectedDueDate.value?.toIso8601String(),
|
||||
"isAdvancePayment": isAdvancePayment.value,
|
||||
"billAttachments": billAttachments.map((a) {
|
||||
return {
|
||||
"fileName": a['fileName'],
|
||||
"fileSize": a['fileSize'],
|
||||
"contentType": a['contentType'],
|
||||
};
|
||||
}).toList(),
|
||||
};
|
||||
|
||||
logSafe("💡 Submitting Payment Request: ${jsonEncode(payload)}");
|
||||
|
||||
final success = await ApiService.createExpensePaymentRequestApi(
|
||||
title: payload['title'],
|
||||
projectId: payload['projectId'],
|
||||
expenseCategoryId: payload['expenseCategoryId'],
|
||||
amount: payload['amount'],
|
||||
currencyId: payload['currencyId'],
|
||||
description: payload['description'],
|
||||
payee: payload['payee'],
|
||||
dueDate: selectedDueDate.value,
|
||||
isAdvancePayment: payload['isAdvancePayment'],
|
||||
billAttachments: billAttachments,
|
||||
);
|
||||
|
||||
logSafe("💡 Payment Request API Response: $success");
|
||||
|
||||
if (success == true) {
|
||||
logSafe("✅ Payment request created successfully.");
|
||||
return true;
|
||||
} else {
|
||||
return _errorSnackbar("Failed to create payment request.");
|
||||
}
|
||||
} catch (e, st) {
|
||||
logSafe("💥 Submit Payment Request Error: $e\n$st",
|
||||
level: LogLevel.error);
|
||||
return _errorSnackbar("Something went wrong. Please try again later.");
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Form validation
|
||||
bool _validateForm() {
|
||||
if (selectedProject.value == null ||
|
||||
selectedProject.value!['id'].toString().isEmpty)
|
||||
return _errorSnackbar("Please select a project");
|
||||
if (selectedCategory.value == null)
|
||||
return _errorSnackbar("Please select a category");
|
||||
if (selectedPayee.value == null)
|
||||
return _errorSnackbar("Please select a payee");
|
||||
if (selectedCurrency.value == null)
|
||||
return _errorSnackbar("Please select currency");
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _errorSnackbar(String msg, [String title = "Error"]) {
|
||||
showAppSnackbar(title: title, message: msg, type: SnackbarType.error);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Clear form
|
||||
void clearForm() {
|
||||
titleController.clear();
|
||||
dueDateController.clear();
|
||||
amountController.clear();
|
||||
descriptionController.clear();
|
||||
selectedProject.value = null;
|
||||
selectedCategory.value = null;
|
||||
selectedPayee.value = null;
|
||||
selectedCurrency.value = null;
|
||||
isAdvancePayment.value = false;
|
||||
attachments.clear();
|
||||
existingAttachments.clear();
|
||||
removedAttachments.clear();
|
||||
}
|
||||
}
|
||||
149
lib/controller/finance/advance_payment_controller.dart
Normal file
@ -0,0 +1,149 @@
|
||||
import 'dart:async';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/model/finance/advance_payment_model.dart';
|
||||
import 'package:on_field_work/model/finance/get_employee_model.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
|
||||
class AdvancePaymentController extends GetxController {
|
||||
/// Advance payments list
|
||||
var payments = <AdvancePayment>[].obs;
|
||||
var isLoading = false.obs;
|
||||
|
||||
/// Employees for dropdown search
|
||||
var employees = <Employee>[].obs;
|
||||
var allEmployees = <Employee>[]; // cache of last API response
|
||||
var employeesLoading = false.obs;
|
||||
var searchQuery = ''.obs;
|
||||
var selectedEmployee = Rxn<Employee>();
|
||||
|
||||
/// Prevents unwanted API calls while programmatically updating search
|
||||
var _suppressSearch = false.obs;
|
||||
|
||||
Timer? _debounceTimer;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
|
||||
ever<String>(searchQuery, (q) {
|
||||
if (_suppressSearch.value) return; // Skip while selecting employee
|
||||
|
||||
// 🔹 When user types new text, clear previous employee + payments instantly
|
||||
if (selectedEmployee.value != null) {
|
||||
selectedEmployee.value = null;
|
||||
payments.clear();
|
||||
}
|
||||
|
||||
// 🔹 Show fresh dropdown results for new query
|
||||
_debounceTimer?.cancel();
|
||||
_debounceTimer = Timer(const Duration(milliseconds: 400), () {
|
||||
if (q.isNotEmpty) {
|
||||
fetchEmployees(q); // repopulate dropdown
|
||||
} else {
|
||||
employees.clear(); // hide dropdown when search cleared
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
_debounceTimer?.cancel();
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
/// Fetch employees by query
|
||||
Future<void> fetchEmployees(String q) async {
|
||||
if (q.isEmpty) {
|
||||
employees.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (employeesLoading.value) return;
|
||||
|
||||
try {
|
||||
employeesLoading.value = true;
|
||||
|
||||
// Build query params
|
||||
final queryParams = {
|
||||
'allEmployee': 'true',
|
||||
if (q.isNotEmpty) 'q': q, // only include search query if not empty
|
||||
};
|
||||
|
||||
final list = await ApiService.getEmployees(queryParams: queryParams);
|
||||
final parsed = Employee.listFromJson(list);
|
||||
logSafe(
|
||||
"✅ Employees fetched from API: ${parsed.map((e) => e.name).toList()}");
|
||||
|
||||
allEmployees = parsed;
|
||||
_filterEmployees(q);
|
||||
} catch (e, s) {
|
||||
logSafe("❌ fetchEmployees error: $e\n$s", level: LogLevel.error);
|
||||
employees.clear();
|
||||
} finally {
|
||||
employeesLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Local filter to update list based on search text
|
||||
void _filterEmployees(String query) {
|
||||
final q = query.toLowerCase();
|
||||
employees
|
||||
..clear()
|
||||
..addAll(allEmployees.where((e) {
|
||||
return e.name.toLowerCase().contains(q) ||
|
||||
e.email.toLowerCase().contains(q);
|
||||
}));
|
||||
}
|
||||
|
||||
/// When user selects employee
|
||||
void selectEmployee(Employee emp) {
|
||||
_suppressSearch.value = true;
|
||||
|
||||
selectedEmployee.value = emp;
|
||||
employees.clear(); // hide dropdown
|
||||
searchQuery.value = emp.name;
|
||||
|
||||
fetchAdvancePayments(emp.id);
|
||||
|
||||
// Re-enable search after a short delay
|
||||
Future.delayed(const Duration(milliseconds: 300), () {
|
||||
_suppressSearch.value = false;
|
||||
});
|
||||
}
|
||||
|
||||
/// Fetch advance payments for the selected employee
|
||||
Future<void> fetchAdvancePayments(String employeeId) async {
|
||||
if (employeeId.isEmpty) {
|
||||
payments.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final list = await ApiService.getAdvancePayments(employeeId);
|
||||
payments.assignAll(list);
|
||||
} catch (e, s) {
|
||||
logSafe("❌ fetchAdvancePayments error: $e\n$s", level: LogLevel.error);
|
||||
payments.clear();
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear employee selection
|
||||
void clearSelection() {
|
||||
selectedEmployee.value = null;
|
||||
payments.clear();
|
||||
employees.clear();
|
||||
searchQuery.value = '';
|
||||
}
|
||||
|
||||
void resetSelectionOnNewSearch() {
|
||||
if (selectedEmployee.value != null) {
|
||||
selectedEmployee.value = null;
|
||||
payments.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
134
lib/controller/finance/payment_request_controller.dart
Normal file
@ -0,0 +1,134 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/finance/payment_request_list_model.dart';
|
||||
import 'package:on_field_work/model/finance/payment_request_filter.dart';
|
||||
import 'package:on_field_work/helpers/services/app_logger.dart';
|
||||
|
||||
class PaymentRequestController extends GetxController {
|
||||
// ---------------- Observables ----------------
|
||||
final RxList<PaymentRequest> paymentRequests = <PaymentRequest>[].obs;
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxString errorMessage = ''.obs;
|
||||
final RxBool isFilterApplied = false.obs;
|
||||
|
||||
// ---------------- Pagination ----------------
|
||||
int _pageSize = 20;
|
||||
int _pageNumber = 1;
|
||||
bool _hasMoreData = true;
|
||||
|
||||
// ---------------- Filters ----------------
|
||||
RxMap<String, dynamic> appliedFilter = <String, dynamic>{}.obs;
|
||||
RxString searchString = ''.obs;
|
||||
|
||||
// ---------------- Filter Options ----------------
|
||||
RxList<IdNameModel> projects = <IdNameModel>[].obs;
|
||||
RxList<IdNameModel> payees = <IdNameModel>[].obs;
|
||||
RxList<IdNameModel> categories = <IdNameModel>[].obs;
|
||||
RxList<IdNameModel> currencies = <IdNameModel>[].obs;
|
||||
RxList<IdNameModel> statuses = <IdNameModel>[].obs;
|
||||
RxList<IdNameModel> createdBy = <IdNameModel>[].obs;
|
||||
|
||||
// ---------------- Fetch Filter Options ----------------
|
||||
Future<void> fetchPaymentRequestFilterOptions() async {
|
||||
try {
|
||||
final response = await ApiService.getExpensePaymentRequestFilterApi();
|
||||
|
||||
if (response != null && response.data != null) {
|
||||
projects.assignAll(response.data!.projects ?? []);
|
||||
payees.assignAll(response.data!.payees ?? []);
|
||||
categories.assignAll(response.data!.expenseCategory ?? []);
|
||||
currencies.assignAll(response.data!.currency ?? []);
|
||||
statuses.assignAll(response.data!.status ?? []);
|
||||
createdBy.assignAll(response.data!.createdBy ?? []);
|
||||
} else {
|
||||
logSafe("Payment request filter API returned null",
|
||||
level: LogLevel.warning);
|
||||
}
|
||||
} catch (e, stack) {
|
||||
logSafe("Exception in fetchPaymentRequestFilterOptions: $e",
|
||||
level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Fetch Payment Requests ----------------
|
||||
Future<void> fetchPaymentRequests({int pageSize = 20}) async {
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
_pageNumber = 1;
|
||||
_pageSize = pageSize;
|
||||
_hasMoreData = true;
|
||||
paymentRequests.clear();
|
||||
|
||||
await _fetchPaymentRequestsFromApi();
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
// ---------------- Load More ----------------
|
||||
Future<void> loadMorePaymentRequests() async {
|
||||
if (isLoading.value || !_hasMoreData) return;
|
||||
|
||||
_pageNumber += 1;
|
||||
isLoading.value = true;
|
||||
|
||||
await _fetchPaymentRequestsFromApi();
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
// ---------------- Internal API Call ----------------
|
||||
Future<void> _fetchPaymentRequestsFromApi() async {
|
||||
try {
|
||||
final response = await ApiService.getExpensePaymentRequestListApi(
|
||||
pageSize: _pageSize,
|
||||
pageNumber: _pageNumber,
|
||||
filter: appliedFilter,
|
||||
searchString: searchString.value,
|
||||
);
|
||||
|
||||
final data = response?.data;
|
||||
final reqList = data?.data ?? [];
|
||||
|
||||
if (response != null && data != null && reqList.isNotEmpty) {
|
||||
if (_pageNumber == 1) {
|
||||
paymentRequests.assignAll(reqList);
|
||||
} else {
|
||||
paymentRequests.addAll(reqList);
|
||||
}
|
||||
|
||||
if (reqList.length < _pageSize) {
|
||||
_hasMoreData = false;
|
||||
}
|
||||
} else {
|
||||
if (_pageNumber == 1) {
|
||||
errorMessage.value = 'No payment requests found.';
|
||||
}
|
||||
_hasMoreData = false;
|
||||
}
|
||||
} catch (e, stack) {
|
||||
errorMessage.value = 'Failed to fetch payment requests.';
|
||||
logSafe("Exception in _fetchPaymentRequestsFromApi: $e",
|
||||
level: LogLevel.error);
|
||||
logSafe("StackTrace: $stack", level: LogLevel.debug);
|
||||
_hasMoreData = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Filter Management ----------------
|
||||
void setFilterApplied(bool applied) {
|
||||
isFilterApplied.value = applied;
|
||||
}
|
||||
|
||||
void applyFilter(Map<String, dynamic> filter, {String search = ''}) {
|
||||
appliedFilter.assignAll(filter);
|
||||
searchString.value = search;
|
||||
isFilterApplied.value = filter.isNotEmpty || search.isNotEmpty;
|
||||
fetchPaymentRequests();
|
||||
}
|
||||
|
||||
void clearFilter() {
|
||||
appliedFilter.clear();
|
||||
searchString.value = '';
|
||||
isFilterApplied.value = false;
|
||||
fetchPaymentRequests();
|
||||
}
|
||||
}
|
||||
363
lib/controller/finance/payment_request_detail_controller.dart
Normal file
@ -0,0 +1,363 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
|
||||
import 'package:on_field_work/model/employees/employee_model.dart';
|
||||
import 'package:on_field_work/model/finance/payment_request_details_model.dart';
|
||||
import 'package:on_field_work/model/expense/payment_types_model.dart';
|
||||
import 'package:on_field_work/helpers/widgets/time_stamp_image_helper.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:geocoding/geocoding.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:mime/mime.dart';
|
||||
import 'package:on_field_work/controller/finance/payment_request_controller.dart';
|
||||
|
||||
class PaymentRequestDetailController extends GetxController {
|
||||
final Rx<PaymentRequestData?> paymentRequest = Rx<PaymentRequestData?>(null);
|
||||
final RxBool isLoading = false.obs;
|
||||
final RxString errorMessage = ''.obs;
|
||||
final RxList<PaymentModeModel> paymentModes = <PaymentModeModel>[].obs;
|
||||
|
||||
// Employee selection
|
||||
final Rx<EmployeeModel?> selectedReimbursedBy = Rx<EmployeeModel?>(null);
|
||||
final RxList<EmployeeModel> allEmployees = <EmployeeModel>[].obs;
|
||||
final RxList<EmployeeModel> employeeSearchResults = <EmployeeModel>[].obs;
|
||||
final TextEditingController employeeSearchController =
|
||||
TextEditingController();
|
||||
PaymentRequestController get paymentRequestController =>
|
||||
Get.find<PaymentRequestController>();
|
||||
final RxBool isSearchingEmployees = false.obs;
|
||||
|
||||
// Attachments
|
||||
final RxList<File> attachments = <File>[].obs;
|
||||
final RxList<Map<String, dynamic>> existingAttachments =
|
||||
<Map<String, dynamic>>[].obs;
|
||||
final isProcessingAttachment = false.obs;
|
||||
|
||||
// Payment mode
|
||||
final selectedPaymentMode = Rxn<PaymentModeModel>();
|
||||
|
||||
// Text controllers for form
|
||||
final TextEditingController locationController = TextEditingController();
|
||||
final TextEditingController gstNumberController = TextEditingController();
|
||||
|
||||
// Form submission state
|
||||
final RxBool isSubmitting = false.obs;
|
||||
|
||||
late String _requestId;
|
||||
bool _isInitialized = false;
|
||||
RxBool paymentSheetOpened = false.obs;
|
||||
final ImagePicker _picker = ImagePicker();
|
||||
|
||||
/// Initialize controller
|
||||
void init(String requestId) {
|
||||
if (_isInitialized) return;
|
||||
_isInitialized = true;
|
||||
|
||||
_requestId = requestId;
|
||||
|
||||
// Fetch payment request details + employees concurrently
|
||||
Future.wait([
|
||||
fetchPaymentRequestDetail(),
|
||||
fetchAllEmployees(),
|
||||
fetchPaymentModes(),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Generic API wrapper for error handling
|
||||
Future<T?> _apiCallWrapper<T>(
|
||||
Future<T?> Function() apiCall, String operationName) async {
|
||||
isLoading.value = true;
|
||||
errorMessage.value = '';
|
||||
try {
|
||||
final result = await apiCall();
|
||||
return result;
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Error during $operationName: $e';
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: errorMessage.value,
|
||||
type: SnackbarType.error);
|
||||
return null;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch payment request details
|
||||
Future<void> fetchPaymentRequestDetail() async {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
final response =
|
||||
await ApiService.getExpensePaymentRequestDetailApi(_requestId);
|
||||
if (response != null) {
|
||||
paymentRequest.value = response.data;
|
||||
} else {
|
||||
errorMessage.value = "Failed to fetch payment request details";
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: errorMessage.value,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = "Error fetching payment request details: $e";
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: errorMessage.value,
|
||||
type: SnackbarType.error,
|
||||
);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick files from gallery or file picker
|
||||
Future<void> pickAttachments() async {
|
||||
try {
|
||||
final result = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'],
|
||||
allowMultiple: true,
|
||||
);
|
||||
if (result != null) {
|
||||
attachments.addAll(
|
||||
result.paths.whereType<String>().map(File.new),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Attachment error: $e");
|
||||
}
|
||||
}
|
||||
|
||||
void removeAttachment(File file) => attachments.remove(file);
|
||||
|
||||
Future<void> pickFromCamera() async {
|
||||
try {
|
||||
final pickedFile = await _picker.pickImage(source: ImageSource.camera);
|
||||
if (pickedFile != null) {
|
||||
isProcessingAttachment.value = true;
|
||||
File imageFile = File(pickedFile.path);
|
||||
|
||||
File timestampedFile = await TimestampImageHelper.addTimestamp(
|
||||
imageFile: imageFile,
|
||||
);
|
||||
|
||||
attachments.add(timestampedFile);
|
||||
attachments.refresh();
|
||||
}
|
||||
} catch (e) {
|
||||
_errorSnackbar("Camera error: $e");
|
||||
} finally {
|
||||
isProcessingAttachment.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Location ---
|
||||
final RxBool isFetchingLocation = false.obs;
|
||||
|
||||
Future<void> fetchCurrentLocation() async {
|
||||
isFetchingLocation.value = true;
|
||||
try {
|
||||
if (!await _ensureLocationPermission()) return;
|
||||
|
||||
final position = await Geolocator.getCurrentPosition();
|
||||
final placemarks =
|
||||
await placemarkFromCoordinates(position.latitude, position.longitude);
|
||||
|
||||
locationController.text = placemarks.isNotEmpty
|
||||
? [
|
||||
placemarks.first.name,
|
||||
placemarks.first.street,
|
||||
placemarks.first.locality,
|
||||
placemarks.first.administrativeArea,
|
||||
placemarks.first.country,
|
||||
].where((e) => e?.isNotEmpty == true).join(", ")
|
||||
: "${position.latitude}, ${position.longitude}";
|
||||
} catch (e) {
|
||||
_errorSnackbar("Location error: $e");
|
||||
} finally {
|
||||
isFetchingLocation.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _ensureLocationPermission() async {
|
||||
var permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied ||
|
||||
permission == LocationPermission.deniedForever) {
|
||||
permission = await Geolocator.requestPermission();
|
||||
if (permission == LocationPermission.denied ||
|
||||
permission == LocationPermission.deniedForever) {
|
||||
_errorSnackbar("Location permission denied.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!await Geolocator.isLocationServiceEnabled()) {
|
||||
_errorSnackbar("Location service disabled.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Fetch all employees
|
||||
Future<void> fetchAllEmployees() async {
|
||||
final response = await _apiCallWrapper(
|
||||
() => ApiService.getAllEmployees(), "fetch all employees");
|
||||
|
||||
if (response != null && response.isNotEmpty) {
|
||||
try {
|
||||
allEmployees.assignAll(response.map((e) => EmployeeModel.fromJson(e)));
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Failed to parse employee data: $e';
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: errorMessage.value,
|
||||
type: SnackbarType.error);
|
||||
}
|
||||
} else {
|
||||
allEmployees.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch payment modes
|
||||
Future<void> fetchPaymentModes() async {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
final paymentModesData = await ApiService.getMasterPaymentModes();
|
||||
if (paymentModesData is List) {
|
||||
paymentModes.value =
|
||||
paymentModesData.map((e) => PaymentModeModel.fromJson(e)).toList();
|
||||
} else {
|
||||
paymentModes.clear();
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Failed to fetch payment modes',
|
||||
type: SnackbarType.error);
|
||||
}
|
||||
} catch (e) {
|
||||
paymentModes.clear();
|
||||
showAppSnackbar(
|
||||
title: 'Error',
|
||||
message: 'Error fetching payment modes: $e',
|
||||
type: SnackbarType.error);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Search employees
|
||||
Future<void> searchEmployees(String query) async {
|
||||
if (query.trim().isEmpty) {
|
||||
employeeSearchResults.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
isSearchingEmployees.value = true;
|
||||
try {
|
||||
final data =
|
||||
await ApiService.searchEmployeesBasic(searchString: query.trim());
|
||||
employeeSearchResults.assignAll(
|
||||
(data ?? []).map((e) => EmployeeModel.fromJson(e)),
|
||||
);
|
||||
} catch (e) {
|
||||
employeeSearchResults.clear();
|
||||
} finally {
|
||||
isSearchingEmployees.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Update payment request status
|
||||
Future<bool> updatePaymentRequestStatus({
|
||||
required String statusId,
|
||||
required String comment,
|
||||
String? paidTransactionId,
|
||||
String? paidById,
|
||||
DateTime? paidAt,
|
||||
double? baseAmount,
|
||||
double? taxAmount,
|
||||
String? tdsPercentage,
|
||||
}) async {
|
||||
isLoading.value = true;
|
||||
|
||||
try {
|
||||
final success = await ApiService.updateExpensePaymentRequestStatusApi(
|
||||
paymentRequestId: _requestId,
|
||||
statusId: statusId,
|
||||
comment: comment,
|
||||
paidTransactionId: paidTransactionId,
|
||||
paidById: paidById,
|
||||
paidAt: paidAt,
|
||||
baseAmount: baseAmount,
|
||||
taxAmount: taxAmount,
|
||||
tdsPercentage: tdsPercentage,
|
||||
);
|
||||
|
||||
if (success) {
|
||||
// Controller refreshes the data but does not show snackbars.
|
||||
await fetchPaymentRequestDetail();
|
||||
paymentRequestController.fetchPaymentRequests();
|
||||
}
|
||||
|
||||
return success;
|
||||
} catch (e) {
|
||||
// Controller returns false on error; UI will show the snackbar.
|
||||
return false;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- Snackbar Helper ---
|
||||
void _errorSnackbar(String msg, [String title = "Error"]) {
|
||||
showAppSnackbar(title: title, message: msg, type: SnackbarType.error);
|
||||
}
|
||||
|
||||
// --- Payment Mode Selection ---
|
||||
void selectPaymentMode(PaymentModeModel mode) {
|
||||
selectedPaymentMode.value = mode;
|
||||
}
|
||||
|
||||
// --- Submit Expense ---
|
||||
Future<bool> submitExpense(
|
||||
{required String statusId, String? comment}) async {
|
||||
if (selectedPaymentMode.value == null) return false;
|
||||
|
||||
isSubmitting.value = true;
|
||||
try {
|
||||
// prepare attachments
|
||||
final success = await ApiService.createExpenseForPRApi(
|
||||
paymentModeId: selectedPaymentMode.value!.id,
|
||||
location: locationController.text,
|
||||
gstNumber: gstNumberController.text,
|
||||
paymentRequestId: _requestId,
|
||||
billAttachments: attachments.map((file) {
|
||||
final bytes = file.readAsBytesSync();
|
||||
final mimeType =
|
||||
lookupMimeType(file.path) ?? 'application/octet-stream';
|
||||
return {
|
||||
"fileName": file.path.split('/').last,
|
||||
"base64Data": base64Encode(bytes),
|
||||
"contentType": mimeType,
|
||||
"description": "",
|
||||
"fileSize": bytes.length,
|
||||
"isActive": true,
|
||||
};
|
||||
}).toList(),
|
||||
statusId: statusId,
|
||||
comment: comment ?? '',
|
||||
);
|
||||
|
||||
if (success) {
|
||||
// Refresh the payment request details so the UI updates
|
||||
await fetchPaymentRequestDetail();
|
||||
}
|
||||
|
||||
return success;
|
||||
} finally {
|
||||
isSubmitting.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,48 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/infra_project/infra_project_list.dart';
|
||||
|
||||
class InfraProjectController extends GetxController {
|
||||
final projects = <ProjectData>[].obs;
|
||||
final isLoading = false.obs;
|
||||
final searchQuery = ''.obs;
|
||||
|
||||
// Filtered list
|
||||
List<ProjectData> get filteredProjects {
|
||||
final q = searchQuery.value.trim().toLowerCase();
|
||||
if (q.isEmpty) return projects;
|
||||
|
||||
return projects.where((p) {
|
||||
return (p.name?.toLowerCase().contains(q) ?? false) ||
|
||||
(p.shortName?.toLowerCase().contains(q) ?? false) ||
|
||||
(p.projectAddress?.toLowerCase().contains(q) ?? false) ||
|
||||
(p.contactPerson?.toLowerCase().contains(q) ?? false);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
// Fetch Projects
|
||||
Future<void> fetchProjects({int pageNumber = 1, int pageSize = 20}) async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
|
||||
final response = await ApiService.getInfraProjectsList(
|
||||
pageNumber: pageNumber,
|
||||
pageSize: pageSize,
|
||||
);
|
||||
|
||||
if (response != null && response.data != null) {
|
||||
projects.assignAll(response.data!.data ?? []);
|
||||
} else {
|
||||
projects.clear();
|
||||
}
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
void updateSearch(String query) {
|
||||
searchQuery.value = query;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:on_field_work/helpers/services/api_service.dart';
|
||||
import 'package:on_field_work/model/infra_project/infra_project_details.dart';
|
||||
|
||||
class InfraProjectDetailsController extends GetxController {
|
||||
final String projectId;
|
||||
|
||||
InfraProjectDetailsController({required this.projectId});
|
||||
|
||||
var isLoading = true.obs;
|
||||
var projectDetails = Rxn<ProjectData>();
|
||||
var errorMessage = ''.obs;
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
fetchProjectDetails();
|
||||
}
|
||||
|
||||
Future<void> fetchProjectDetails() async {
|
||||
try {
|
||||
isLoading.value = true;
|
||||
final response = await ApiService.getInfraProjectDetails(projectId: projectId);
|
||||
|
||||
if (response != null && response.success == true && response.data != null) {
|
||||
projectDetails.value = response.data;
|
||||
isLoading.value = false;
|
||||
|
||||
} else {
|
||||
errorMessage.value = response?.message ?? "Failed to load project details";
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = "Error fetching project details: $e";
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,3 +1,3 @@
|
||||
import 'package:marco/controller/my_controller.dart';
|
||||
import 'package:on_field_work/controller/my_controller.dart';
|
||||
|
||||
class AuthLayout2Controller extends MyController {}
|
||||
|
||||