From dc7e29aaeb3655c5e4beb99efdb50e623d316eb2 Mon Sep 17 00:00:00 2001 From: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> Date: Wed, 28 Aug 2024 10:04:20 +0530 Subject: [PATCH] v1.5 (#531) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Updated the integer form picker and added a new text block component (#441) * updated the integer picker and added a new text block component * added a field to change the width of button * modified text block component to conditionally render children --------- Co-authored-by: rachana-egov * updated description for household location and details page (#443) Co-authored-by: rachana-egov * replaced product variant dropdown to selection card (#445) Co-authored-by: rachana-egov * HLM-6283:: IRS- Household Details Fields added (#444) * Updated checklist for a new type boolean (#446) * updated checklist for a new type boolean * added To Do to fix hard code options --------- Co-authored-by: rachana-egov * HLM-6282 and HLM-6283:: House Structure Details Page added (#447) * HLM-6283:: IRS- Household Details Fields added * HLM-6283:: House Structure Details Page * integrated checklist inside the beneficiary flow and updated gender field to selection card (#450) Co-authored-by: rachana-egov * HLM-6371:: Beneficiary Registration Summary Page (#452) * HLM-6283:: IRS- Household Details Fields added * HLM-6283:: House Structure Details Page * HLM-6371:: Beneficiary Registration Summary Page * Updated registration_delivery script * Added refused delivery page (#451) * integrated checklist inside the beneficiary flow and updated gender field to selection card * fetching refusal reasons * added refused delivery page * added refused delivery page --------- Co-authored-by: rachana-egov Co-authored-by: Naveen J <83631045+naveen-egov@users.noreply.github.com> * No delivery flow page (#453) Co-authored-by: rachana-egov * HLM-6367:: Auto Create project beneficiary (#454) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved --------- Co-authored-by: Naveen Renati * Hlm 6414 - MDMS StatusFilter, Filter search (#448) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) --------- Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * HCMPRE-98 Filter search pagination, Removed private PageState (#457) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery --------- Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * Created a new package for marking closed household (#459) * Created a new package for marking closed household * fixed build issues * updated the name to userAction --------- Co-authored-by: rachana-egov * HCMPRE-98 - Inventory TeamCode fixes, Filter search fixes (#460) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery * removed multiple filter selection modified filter search * fixed delivery team scanner issues in stock_details.dart * Fixed - missing addition of scanned resources to additional fields filter search bug fixes * HCMPRE-74, HCMPRE-82, HCMPRE-83:: Household Reload Fix, Validations for Household details added (#458) * updated individual global search added beneficiary type check in view_beneficiary_card.dart removed commented code in household_overview.dart * Added null check for beneficiaryTag in closed_household_summary.dart --------- Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * Hcmpre 118 - Closed Household, Filter improvements, Bug fixes (#467) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery * removed multiple filter selection modified filter search * fixed delivery team scanner issues in stock_details.dart * Fixed - missing addition of scanned resources to additional fields filter search bug fixes * HCMPRE-74, HCMPRE-82, HCMPRE-83:: Household Reload Fix, Validations for Household details added (#458) * updated individual global search added beneficiary type check in view_beneficiary_card.dart removed commented code in household_overview.dart * Added null check for beneficiaryTag in closed_household_summary.dart * Exposed Registration delivery pages * updated remote repository and some miner fixes (#461) Co-authored-by: rachana-egov * HCMPRE-82:: Validations and Bug Fixes * small css fixes (#462) Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * merge fix * added closed household search * status model fix * Closed-household-registration (#464) * closed-household-registration * closed-household-registration * updated pub file --------- Co-authored-by: rachana-egov * added closed household init file modified user_action.dart model and db corrected modified closed household status * updated registration for closed household * added closed_household search and updating closed household status * clearing search before navigating to registration flow * getting last tasks in household_overview.dart * HCMPRE-107:: Summary page added for Delivery Flow, HCMPRE-111:: Disable Delete household if beneficiary not present (#463) * Validation and gps fixes * fixed closed household count clearing closedhould results for clear * pagination fix for closed household * sync down for closed household, updated scan voucher button, and remove the tag when we navigate to a different page (#465) Co-authored-by: rachana-egov * DeliverySummary Route added to main app * seperated closedhousehold search Bug fixes - HCMPRE-112, 110, 113 * updated all the points of this ticket HCMPRE-120 (#466) Co-authored-by: rachana-egov * Bug Fixes, dev version release of packages * HCMPRE-119:: IRS Demo fixes (#468) * HCMPRE-119:: IRS Demo fixes * Removed unused code * updated closed button action to push closedhousehold tasks filter with last fix * updated validation for closed household name and fix error message size (#470) Co-authored-by: rachana-egov * Irs demo fix patch (#469) * HCMPRE-119:: IRS Demo fixes * Removed unused code * Edit Household if no project beneficiary fix * reverted hiding of digit search bar when closed filter is applied * status update based on last task status in household_overview.dart mapped administered success in beneficiary_card.dart moved getstatus to utils.dart * fixed offset increasing twice * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes (#471) * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes * Added date formats to constants * fixed offset increasing twice closed household distance fix emitting scanner state loading * dev version bump-up for registration and scanner * version updates for packages --------- Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov * Hcmpre 155 - ClosedHousehold flow change (#478) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery * removed multiple filter selection modified filter search * fixed delivery team scanner issues in stock_details.dart * Fixed - missing addition of scanned resources to additional fields filter search bug fixes * HCMPRE-74, HCMPRE-82, HCMPRE-83:: Household Reload Fix, Validations for Household details added (#458) * updated individual global search added beneficiary type check in view_beneficiary_card.dart removed commented code in household_overview.dart * Added null check for beneficiaryTag in closed_household_summary.dart * Exposed Registration delivery pages * updated remote repository and some miner fixes (#461) Co-authored-by: rachana-egov * HCMPRE-82:: Validations and Bug Fixes * small css fixes (#462) Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * merge fix * added closed household search * status model fix * Closed-household-registration (#464) * closed-household-registration * closed-household-registration * updated pub file --------- Co-authored-by: rachana-egov * added closed household init file modified user_action.dart model and db corrected modified closed household status * updated registration for closed household * added closed_household search and updating closed household status * clearing search before navigating to registration flow * getting last tasks in household_overview.dart * HCMPRE-107:: Summary page added for Delivery Flow, HCMPRE-111:: Disable Delete household if beneficiary not present (#463) * Validation and gps fixes * fixed closed household count clearing closedhould results for clear * pagination fix for closed household * sync down for closed household, updated scan voucher button, and remove the tag when we navigate to a different page (#465) Co-authored-by: rachana-egov * DeliverySummary Route added to main app * seperated closedhousehold search Bug fixes - HCMPRE-112, 110, 113 * updated all the points of this ticket HCMPRE-120 (#466) Co-authored-by: rachana-egov * Bug Fixes, dev version release of packages * HCMPRE-119:: IRS Demo fixes (#468) * HCMPRE-119:: IRS Demo fixes * Removed unused code * updated closed button action to push closedhousehold tasks filter with last fix * updated validation for closed household name and fix error message size (#470) Co-authored-by: rachana-egov * Irs demo fix patch (#469) * HCMPRE-119:: IRS Demo fixes * Removed unused code * Edit Household if no project beneficiary fix * reverted hiding of digit search bar when closed filter is applied * status update based on last task status in household_overview.dart mapped administered success in beneficiary_card.dart moved getstatus to utils.dart * fixed offset increasing twice * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes (#471) * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes * Added date formats to constants * fixed offset increasing twice closed household distance fix emitting scanner state loading * dev version bump-up for registration and scanner * version updates for packages * View Household button added in delete individual success page, Search project beneficiary fix * added close button to close the filter and disabled the clear button … (#475) * added close button to close the filter and disabled the clear button unless something is selected * added validation for closed household head name same as individual * updated the condition for validation of closehousehold head --------- Co-authored-by: rachana-egov * View Household button added in delete individual success page, Search project beneficiary fix (#474) * Search beneficiary fix * Search beneficiary fix * Bloc dispose fix * Bloc dispose fix * Updated task based search for household * Modified closed household package to use registration flow for creating a household and related data along with task as closed deleted user_action from data_model package Updating closed_household to not_delivered status after closed household registration * version updates of closed_household, digit_components, digit_data_model, registration_delivery * version upgrade for registration_delivery --------- Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * Hcmpre 164, 165 - Count implementation for filter search (#485) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * Resolved code comments --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * fixed reports are not getting refreshed after updating facility (#486) Co-authored-by: rachana-egov * Delivery summary page Resources and quantity added (#473) * Delivery summary page Resources and quantity added * fix for offset increment twice * Delivery summary page Resources and quantity added --------- Co-authored-by: Naveen Renati Co-authored-by: Naveen J <83631045+naveen-egov@users.noreply.github.com> * updated script for closed household (#489) Co-authored-by: rachana-egov * Hcmpre 166 - Moved Localization from ISAR To SQL (#488) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * created new table for localization TODO: separate packages localization delegates to individual package and move the localization model to data_model package for common usage Delete localization related isar files once tested * init Boundary code wise localization.dart * create localization local repo modified module separation from query to exclude and include specified module * modified module exclude in boundary page * modified localization call for boundary selection bug where first value is localized in dropdown * removed un-required localization bloc calls * updated index value to selected language on home * removed login cred --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Removed null condition, fixed double is not a subtype of string issue and added null check for table (#490) * HCMPRE-156 : type 'double' is not a subtype of type 'String' * added check if the first table row is null --------- Co-authored-by: rachana-egov Co-authored-by: Naveen J <83631045+naveen-egov@users.noreply.github.com> * HCMPRE-177:: Metric and Table Charts Integration in Mobile dashboard and digit_dss package initial release (#480) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * HCMPRE-55 Dashboard Static Screen added * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery * removed multiple filter selection modified filter search * fixed delivery team scanner issues in stock_details.dart * Fixed - missing addition of scanned resources to additional fields filter search bug fixes * HCMPRE-74, HCMPRE-82, HCMPRE-83:: Household Reload Fix, Validations for Household details added (#458) * updated individual global search added beneficiary type check in view_beneficiary_card.dart removed commented code in household_overview.dart * Added null check for beneficiaryTag in closed_household_summary.dart * Exposed Registration delivery pages * updated remote repository and some miner fixes (#461) Co-authored-by: rachana-egov * HCMPRE-82:: Validations and Bug Fixes * small css fixes (#462) Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * merge fix * added closed household search * status model fix * Closed-household-registration (#464) * closed-household-registration * closed-household-registration * updated pub file --------- Co-authored-by: rachana-egov * added closed household init file modified user_action.dart model and db corrected modified closed household status * updated registration for closed household * added closed_household search and updating closed household status * clearing search before navigating to registration flow * getting last tasks in household_overview.dart * HCMPRE-107:: Summary page added for Delivery Flow, HCMPRE-111:: Disable Delete household if beneficiary not present (#463) * Validation and gps fixes * fixed closed household count clearing closedhould results for clear * pagination fix for closed household * sync down for closed household, updated scan voucher button, and remove the tag when we navigate to a different page (#465) Co-authored-by: rachana-egov * DeliverySummary Route added to main app * seperated closedhousehold search Bug fixes - HCMPRE-112, 110, 113 * updated all the points of this ticket HCMPRE-120 (#466) Co-authored-by: rachana-egov * Bug Fixes, dev version release of packages * HCMPRE-119:: IRS Demo fixes (#468) * HCMPRE-119:: IRS Demo fixes * Removed unused code * updated closed button action to push closedhousehold tasks filter with last fix * updated validation for closed household name and fix error message size (#470) Co-authored-by: rachana-egov * Irs demo fix patch (#469) * HCMPRE-119:: IRS Demo fixes * Removed unused code * Edit Household if no project beneficiary fix * reverted hiding of digit search bar when closed filter is applied * status update based on last task status in household_overview.dart mapped administered success in beneficiary_card.dart moved getstatus to utils.dart * fixed offset increasing twice * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes (#471) * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes * Added date formats to constants * fixed offset increasing twice closed household distance fix emitting scanner state loading * dev version bump-up for registration and scanner * version updates for packages * View Household button added in delete individual success page, Search project beneficiary fix * added close button to close the filter and disabled the clear button … (#475) * added close button to close the filter and disabled the clear button unless something is selected * added validation for closed household head name same as individual * updated the condition for validation of closehousehold head --------- Co-authored-by: rachana-egov * View Household button added in delete individual success page, Search project beneficiary fix (#474) * Search beneficiary fix * Search beneficiary fix * Bloc dispose fix * Bloc dispose fix * Updated task based search for household * HCMPRE-177:: Metric Chart Integration and digit_dss package setup * HCMPRE-177:: Added Refresh Indicator for refreshing the dashboard * HCMPRE-177:: Table chart integration and Refresh logic update * Added code comments for digit_dss package * Added enums and constants * Resolved code comments and updated versions for packages * HCMPRE177:: Moved dashboard UI Config to MDMS * HCMPRE177:: Added dss_import script for digit_dss package * Resolved code comments * Updated dashboard Config * Added dashboard config search to try catch block * Resolved conflicts * published data_model and registration_delivery * Added Read me file and updated pubspec.yaml --------- Co-authored-by: Naveen Renati Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * HCMPRE-177:: Fetch and send attendees uuids of registers to dss filters (#491) * added translator for administration area * Fixed Facility search based on tenant ID * Added disable battery optimization permission for background service * Added disable battery optimization ask permission on App start and background service start * HLM-5984:: Get Precise location on Submitting latitude longitude details * Reverted install_bricks.sh * added new status REGISTERED, NOT_REGISTERED updated conditional check for status by project beneficiaries * added static status_filter.dart integration in search_beneficiary.dart * TODO for selected_filters display condition * integrated household search filters with mdms implemented search based on filters with pagination for Registered and NotRegistered * updated status filter component merge with develop * create individual_global_search and implemented search * Auto Create Project Beneficiary on Edit Household, and disable record delivery if no project beneficiary present * Conflicts resolved * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty * implemented household_global_search.dart fixed individual_global_search.dart * updated proximity search for household_global_search.dart * Pop State recapture during registration flow, Disable delivery flow for individual based campaign if project beneficiaries is empty (#456) * updated class state from private for customization override in registration_delivery and inventory added pagination for filter search TODO: combination search for registered and not registered needs fix which return only last selected results * adding missed changes for last commit * HCMPRE-55 Dashboard Static Screen added * displaying selected filter value for applied filters in search_beneficiary.dart * updated changelog for inventory and registration_delivery for new dev versions * updated pubspec lock of registration_delivery * removed multiple filter selection modified filter search * fixed delivery team scanner issues in stock_details.dart * Fixed - missing addition of scanned resources to additional fields filter search bug fixes * HCMPRE-74, HCMPRE-82, HCMPRE-83:: Household Reload Fix, Validations for Household details added (#458) * updated individual global search added beneficiary type check in view_beneficiary_card.dart removed commented code in household_overview.dart * Added null check for beneficiaryTag in closed_household_summary.dart * Exposed Registration delivery pages * updated remote repository and some miner fixes (#461) Co-authored-by: rachana-egov * HCMPRE-82:: Validations and Bug Fixes * small css fixes (#462) Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * merge fix * added closed household search * status model fix * Closed-household-registration (#464) * closed-household-registration * closed-household-registration * updated pub file --------- Co-authored-by: rachana-egov * added closed household init file modified user_action.dart model and db corrected modified closed household status * updated registration for closed household * added closed_household search and updating closed household status * clearing search before navigating to registration flow * getting last tasks in household_overview.dart * HCMPRE-107:: Summary page added for Delivery Flow, HCMPRE-111:: Disable Delete household if beneficiary not present (#463) * Validation and gps fixes * fixed closed household count clearing closedhould results for clear * pagination fix for closed household * sync down for closed household, updated scan voucher button, and remove the tag when we navigate to a different page (#465) Co-authored-by: rachana-egov * DeliverySummary Route added to main app * seperated closedhousehold search Bug fixes - HCMPRE-112, 110, 113 * updated all the points of this ticket HCMPRE-120 (#466) Co-authored-by: rachana-egov * Bug Fixes, dev version release of packages * HCMPRE-119:: IRS Demo fixes (#468) * HCMPRE-119:: IRS Demo fixes * Removed unused code * updated closed button action to push closedhousehold tasks filter with last fix * updated validation for closed household name and fix error message size (#470) Co-authored-by: rachana-egov * Irs demo fix patch (#469) * HCMPRE-119:: IRS Demo fixes * Removed unused code * Edit Household if no project beneficiary fix * reverted hiding of digit search bar when closed filter is applied * status update based on last task status in household_overview.dart mapped administered success in beneficiary_card.dart moved getstatus to utils.dart * fixed offset increasing twice * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes (#471) * HCMPRE-121:: Enter manual code fix and Search Beneficiary fixes * Added date formats to constants * fixed offset increasing twice closed household distance fix emitting scanner state loading * dev version bump-up for registration and scanner * version updates for packages * View Household button added in delete individual success page, Search project beneficiary fix * added close button to close the filter and disabled the clear button … (#475) * added close button to close the filter and disabled the clear button unless something is selected * added validation for closed household head name same as individual * updated the condition for validation of closehousehold head --------- Co-authored-by: rachana-egov * View Household button added in delete individual success page, Search project beneficiary fix (#474) * Search beneficiary fix * Search beneficiary fix * Bloc dispose fix * Bloc dispose fix * Updated task based search for household * HCMPRE-177:: Metric Chart Integration and digit_dss package setup * HCMPRE-177:: Added Refresh Indicator for refreshing the dashboard * HCMPRE-177:: Table chart integration and Refresh logic update * Added code comments for digit_dss package * Added enums and constants * Resolved code comments and updated versions for packages * HCMPRE177:: Moved dashboard UI Config to MDMS * HCMPRE177:: Added dss_import script for digit_dss package * Resolved code comments * Updated dashboard Config * Added dashboard config search to try catch block * Resolved conflicts * published data_model and registration_delivery * Added Read me file and updated pubspec.yaml * Fetch and send attendees uuids of registers to dss filters * Added dss filters --------- Co-authored-by: Naveen Renati Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * Task update rather than creating new, updated filter popup loading (#493) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * Resolved code comments * HCMPRE220:: Household overview state update on pushing to Registration Wrapper * update task state if task is already present * updated selection box to update on initial selection change and updated delivery comment code * remove changes from beneficiary * task update * HCMPRE-220:: SMC Not registered flow reload fix,and closed household Not delivered status fix * added loader for filter search * Added name of user to additional details in stock and delivery record * updated delivery intervention * check summary page condition for edit flow * fixed task update for delivery intervention * fixed household detail page --------- Co-authored-by: rachana-egov Co-authored-by: Naveen Renati Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * updated status and registration_delivery_enums.dart (#494) * updated status and registration_delivery_enums.dart updated check for check-list check in household_overview.dart * Todo for individual check in beneficiary_registration.dart * Uploaded pre release for inventory-management and digit-dss (#495) * removed the page count from filter, updated status filter pop up (#496) Co-authored-by: rachana-egov * updated demo changes (#498) Co-authored-by: rachana-egov * added lat and long inside additional field when user submit the checklist (#526) Co-authored-by: rachana-egov * HCMPRE-221 data segration (#501) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * created new table for localization TODO: separate packages localization delegates to individual package and move the localization model to data_model package for common usage Delete localization related isar files once tested * init Boundary code wise localization.dart * create localization local repo modified module separation from query to exclude and include specified module * modified module exclude in boundary page * modified localization call for boundary selection bug where first value is localized in dropdown * removed un-required localization bloc calls * updated index value to selected language on home * Uploaded pre release for inventory-management and digit-dss * Updated delivery enums for Not delivered status * Updated status model in task to taskStatus * Updated registration delivery package * Reverted Task Model status key change * Update pubspec with latest version of packages * Summary page Type of resource locale key updated * Resolved comments * Resolved comments and unused variables * Resolved comments and unused variables * Updated version * Updated individual_global_search.dart for search * added data segration * check to enable edit delivery * added project filter * Registration delivery- Attendance management fixes (#497) * Removed captured location dialog on attendance submit * Removed stpper if deliveries length is greater than 1 * Updated digit_components and digit_data_model packages in attendance management * Updated digit_components and digit_data_model packages in attendance management * Localization loader and dialog localization fix (#505) * added dialog till localization is not loaded * fixed localization not coming issue * added a util funtion to show language loading --------- Co-authored-by: rachana-egov * updated search added project id in beneficiary search removed commented code * User uuids filter fixes for attendees local search in an attendance register (#512) * User uuids filters fixes for attendees search in a register * Removed default dashboard card from home * Sync fix --------- Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * Added Task address mapping on refused delivery (#514) * replace and push homepage from boundary page sync dialog * updated register search query to exclude attendee and staff in limit query updated attendance and registration_delivery package * registration_delivery package update * * Added error toast for network failure (#525) * No result card added if no charts available * Updated end date for dss charts to 23:59 instead of 11:59 (#527) * task create fix - removed condition check of resources during create updated changelog of registration, closed, digit_data_model, inventory, registration_delivery --dry-run fixes * Updated stable packages for scanner, attendance and dss (#528) * updated packages to latest version digit_components version update --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Naveen Renati Co-authored-by: Ramkrishna-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * Added Privacy Policy (#499) * added data privacy component * added privacy component * updated localization * updated the dialog to use localized value * updated privacy config inside mdms * updated privacy model * removed local privacy config now coming from mdms * Delete packages/digit_components/lib/widgets/atoms/privacy_component.dart as component is part of main application * fixed github build issue * added a configuration to enable or disable this privacy policy component * fix the issue when privacy policy component is not there * fix the issue when privacy policy component is not there * fixed github comments --------- Co-authored-by: rachana-egov * HCMPRE-332:: Mobile dashboard added check for lastSyncTime to convert to date format (#540) * HCMPRE-332:: Mobile dashboard added check for lastSyncTime to convert to date format * added a enum for lastSyncedTime --------- Co-authored-by: rachana-egov * Hcmpre 263 - Sync write transaction for ISAR - fix, Localization fall back (#538) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * created new table for localization TODO: separate packages localization delegates to individual package and move the localization model to data_model package for common usage Delete localization related isar files once tested * init Boundary code wise localization.dart * create localization local repo modified module separation from query to exclude and include specified module * modified module exclude in boundary page * modified localization call for boundary selection bug where first value is localized in dropdown * removed un-required localization bloc calls * updated index value to selected language on home * Uploaded pre release for inventory-management and digit-dss * Updated delivery enums for Not delivered status * Updated status model in task to taskStatus * Updated registration delivery package * Reverted Task Model status key change * Update pubspec with latest version of packages * Summary page Type of resource locale key updated * Resolved comments * Resolved comments and unused variables * Resolved comments and unused variables * Updated version * Updated individual_global_search.dart for search * added data segration * check to enable edit delivery * added project filter * Registration delivery- Attendance management fixes (#497) * Removed captured location dialog on attendance submit * Removed stpper if deliveries length is greater than 1 * Updated digit_components and digit_data_model packages in attendance management * Updated digit_components and digit_data_model packages in attendance management * Localization loader and dialog localization fix (#505) * added dialog till localization is not loaded * fixed localization not coming issue * added a util funtion to show language loading --------- Co-authored-by: rachana-egov * updated search added project id in beneficiary search removed commented code * User uuids filter fixes for attendees local search in an attendance register (#512) * User uuids filters fixes for attendees search in a register * Removed default dashboard card from home * Sync fix --------- Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * Added Task address mapping on refused delivery (#514) * replace and push homepage from boundary page sync dialog * updated register search query to exclude attendee and staff in limit query updated attendance and registration_delivery package * registration_delivery package update * * Added error toast for network failure (#525) * No result card added if no charts available * Updated end date for dss charts to 23:59 instead of 11:59 (#527) * task create fix - removed condition check of resources during create updated changelog of registration, closed, digit_data_model, inventory, registration_delivery --dry-run fixes * Updated stable packages for scanner, attendance and dss (#528) * updated packages to latest version digit_components version update * added fallback ui dialog when localization call fails. * added localization code * merge from dev * fix for isar transaction lock issue * moved boundary localization path to constants. Updated dialog in language_selection.dart page * isar lock fix * updated data_model version for isar fix. updated a check in language_selection.dart for dialog --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov Co-authored-by: naveen-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * Impel changes - background-services, beneficiary_checklist (#548) * Update closed_household_details.dart (#482) * Fixed pagination refresh issue (#481) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments --------- Co-authored-by: rachana-egov * implemented count for filter search, added todo for combination search count * Fixed count TODO: search with task status filter * Fixed search with task status filter Removed delay in delivery_summary_page.dart * added code comments * HCMPRE-165 issues (#484) * Implement search pagination (#476) * implemented pagination for search * added one more check to check if last response is equal to current response then also break the loop * removed changes from data repository and added pagination only project facility and facility --------- Co-authored-by: rachana-egov * localization update, input validation for numeric, disabled delivery intervention for closed household task (#479) Co-authored-by: rachana-egov * fixed pagination refresh issue * resolved the comments * HCMPRE-162:: Reload issue fix for closed household and not registered * HCMPRE-165: issues fixes * updated reasons for refusals --------- Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov * Updated publock * Added a check to avoid multiple leftJoin for projectBeneficiary - fix for multiple left join error * created new table for localization TODO: separate packages localization delegates to individual package and move the localization model to data_model package for common usage Delete localization related isar files once tested * init Boundary code wise localization.dart * create localization local repo modified module separation from query to exclude and include specified module * modified module exclude in boundary page * modified localization call for boundary selection bug where first value is localized in dropdown * removed un-required localization bloc calls * updated index value to selected language on home * Uploaded pre release for inventory-management and digit-dss * Updated delivery enums for Not delivered status * Updated status model in task to taskStatus * Updated registration delivery package * Reverted Task Model status key change * Update pubspec with latest version of packages * Summary page Type of resource locale key updated * Resolved comments * Resolved comments and unused variables * Resolved comments and unused variables * Updated version * Updated individual_global_search.dart for search * added data segration * check to enable edit delivery * added project filter * Registration delivery- Attendance management fixes (#497) * Removed captured location dialog on attendance submit * Removed stpper if deliveries length is greater than 1 * Updated digit_components and digit_data_model packages in attendance management * Updated digit_components and digit_data_model packages in attendance management * Localization loader and dialog localization fix (#505) * added dialog till localization is not loaded * fixed localization not coming issue * added a util funtion to show language loading --------- Co-authored-by: rachana-egov * updated search added project id in beneficiary search removed commented code * User uuids filter fixes for attendees local search in an attendance register (#512) * User uuids filters fixes for attendees search in a register * Removed default dashboard card from home * Sync fix --------- Co-authored-by: Naveen Renati <154230258+naveenr-egov@users.noreply.github.com> * Added Task address mapping on refused delivery (#514) * replace and push homepage from boundary page sync dialog * updated register search query to exclude attendee and staff in limit query updated attendance and registration_delivery package * registration_delivery package update * * Added error toast for network failure (#525) * No result card added if no charts available * Updated end date for dss charts to 23:59 instead of 11:59 (#527) * task create fix - removed condition check of resources during create updated changelog of registration, closed, digit_data_model, inventory, registration_delivery --dry-run fixes * Updated stable packages for scanner, attendance and dss (#528) * updated packages to latest version digit_components version update * added fallback ui dialog when localization call fails. * added localization code * merge from dev * fix for isar transaction lock issue * moved boundary localization path to constants. Updated dialog in language_selection.dart page * isar lock fix * pulled changes from impel related to background service added missing audit details and client audit details for beneficiary_checklist.dart --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov Co-authored-by: naveen-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> * resolved code rabbit comments (#549) --------- Co-authored-by: rachana-egov <137176770+rachana-egov@users.noreply.github.com> Co-authored-by: rachana-egov Co-authored-by: Ramkrishna-egov <85437265+Ramkrishna-egov@users.noreply.github.com> Co-authored-by: Naveen J <83631045+naveen-egov@users.noreply.github.com> Co-authored-by: Ramkrishna-egov Co-authored-by: naveen-egov --- .../android/app/src/main/AndroidManifest.xml | 69 +- .../assets/icons/svg/closed_household.svg | 10 + .../lib/app.dart | 125 +- .../app_initialization.dart | 72 +- .../app_initialization.freezed.dart | 131 +- .../blocs/localization/app_localization.dart | 26 +- .../app_localizations_delegate.dart | 7 +- .../lib/blocs/localization/localization.dart | 75 +- .../localization/localization.freezed.dart | 43 +- .../lib/blocs/project/project.dart | 145 +- .../project_beneficiaries_downsync.dart | 1 + .../lib/blocs/sync/sync.dart | 8 +- .../no_sql/schema/app_configuration.dart | 61 + .../no_sql/schema/app_configuration.g.dart | 4712 +++++++++++++++-- .../lib/data/network_manager.dart | 6 +- .../data/repositories/local/localization.dart | 107 + .../repositories/remote/localization.dart | 59 +- .../lib/data/repositories/remote/mdms.dart | 67 +- .../lib/data/repositories/sync/sync_down.dart | 1 + .../models/app_config/app_config_model.dart | 23 +- .../app_config/app_config_model.freezed.dart | 359 +- .../models/app_config/app_config_model.g.dart | 34 + .../models/entities/mdms_master_enums.dart | 10 + .../entities/mdms_master_enums.mapper.dart | 20 + .../privacy_notice/privacy_notice_model.dart | 50 + .../privacy_notice_model.freezed.dart | 796 +++ .../privacy_notice_model.g.dart | 79 + .../lib/pages/authenticated.dart | 5 +- .../lib/pages/boundary_selection.dart | 605 ++- .../checklist/checklist_boundary_view.dart | 3 +- .../lib/pages/checklist/checklist_view.dart | 147 +- .../registration/complaint_type.dart | 7 +- .../lib/pages/home.dart | 114 +- .../lib/pages/language_selection.dart | 133 +- .../lib/pages/login.dart | 43 +- .../lib/pages/profile.dart | 12 +- .../lib/pages/project_facility_selection.dart | 1 - .../beneficiary/beneficaries_report.dart | 165 +- .../lib/router/app_router.dart | 49 +- .../lib/router/app_router.gr.dart | 2 + .../lib/utils/background_service.dart | 139 +- .../lib/utils/constants.dart | 20 +- .../lib/utils/extensions/context_utility.dart | 16 + .../lib/utils/extensions/extensions.dart | 1 + .../lib/utils/i18_key_constants.dart | 34 +- .../lib/utils/localization_delegates.dart | 58 +- .../lib/utils/utils.dart | 84 +- .../lib/widgets/home/home_item_card.dart | 6 +- .../privacy_notice/privacy_component.dart | 169 + .../privacy_notice/privacy_notice_dialog.dart | 142 + .../privacy_notice_expand_component.dart | 285 + .../showcase/config/home_showcase.dart | 10 +- .../lib/widgets/sidebar/side_bar.dart | 2 +- .../pubspec.lock | 56 +- .../pubspec.yaml | 19 +- packages/attendance_management/CHANGELOG.md | 13 + .../sql_store/tables/attendance.dart | 0 .../local/attendance_register.dart | 66 +- .../lib/pages/mark_attendance.dart | 161 +- .../lib/utils/i18_key_constants.dart | 4 + packages/attendance_management/pubspec.lock | 8 +- packages/attendance_management/pubspec.yaml | 6 +- packages/closed_household/.gitignore | 29 + packages/closed_household/.metadata | 10 + packages/closed_household/CHANGELOG.md | 24 + packages/closed_household/LICENSE | 21 + packages/closed_household/README.md | 49 + .../closed_household/analysis_options.yaml | 4 + .../assets/icons/app_icon.png | Bin 0 -> 10790 bytes .../assets/icons/svg/mychecklist.svg | 7 + .../assets/icons/svg/no_result.svg | 101 + .../assets/images/powered_by_digit.png | Bin 0 -> 5524 bytes packages/closed_household/build.yaml | 10 + .../lib/blocs/app_localization.dart | 50 + .../lib/blocs/closed_household.dart | 343 ++ .../lib/blocs/closed_household.freezed.dart | 831 +++ ...losed_household_localization_delegate.dart | 32 + .../lib/closed_household.dart | 14 + .../closed_household_acknowledgement.dart | 47 + .../lib/pages/closed_household_details.dart | 205 + .../lib/pages/closed_household_summary.dart | 188 + .../lib/pages/closed_household_wrapper.dart | 50 + .../lib/router/closed_household_router.dart | 31 + .../router/closed_household_router.gm.dart | 195 + .../closed_household/lib/utils/constants.dart | 7 + .../lib/utils/extensions/context_utility.dart | 28 + .../lib/utils/extensions/extensions.dart | 67 + .../lib/utils/i18_key_constants.dart | 169 + .../closed_household/lib/utils/utils.dart | 69 + .../widgets/back_navigation_help_header.dart | 85 + .../lib/widgets/localized.dart | 33 + .../config/closed_household_details.dart | 31 + .../showcase/config/showcase_constants.dart | 7 + .../lib/widgets/showcase/showcase_button.dart | 73 + .../widgets/showcase/showcase_wrappers.dart | 65 + packages/closed_household/pubspec.yaml | 62 + .../test/closed_household_test.dart | 4 + packages/digit_components/CHANGELOG.md | 145 +- packages/digit_components/example/ios/Podfile | 44 + .../digit_components/example/pubspec.lock | 2 +- .../lib/digit_components.dart | 3 +- .../digit_components/lib/utils/utils.dart | 41 + .../lib/widgets/atoms/details_card.dart | 127 + .../lib/widgets/atoms/digit_icon_button.dart | 13 +- .../atoms/digit_integer_form_picker.dart | 62 +- .../atoms/digit_reactive_search_dropdown.dart | 4 +- .../lib/widgets/atoms/selection_card.dart | 216 + .../lib/widgets/atoms/text_block.dart | 83 + .../lib/widgets/digit_dialog.dart | 11 +- .../lib/widgets/digit_search_bar.dart | 8 +- .../lib/widgets/digit_sync_dialog.dart | 14 +- .../lib/widgets/labeled_field.dart | 12 +- .../lib/widgets/molecules/digit_table.dart | 2 +- packages/digit_components/pubspec.yaml | 2 +- packages/digit_data_model/CHANGELOG.md | 55 +- .../lib/data/data_repository.dart | 68 +- .../data/local_store/sql_store/sql_store.dart | 2 + .../local_store/sql_store/sql_store.g.dart | 278 +- .../sql_store/tables/localization.dart | 11 + .../data/repositories/local/individual.dart | 2 + .../lib/data/repositories/oplog/oplog.dart | 84 +- .../data/repositories/remote/boundary.dart | 3 +- .../data/repositories/remote/facility.dart | 109 + .../repositories/remote/project_facility.dart | 109 + .../lib/models/entities/project.dart | 2 +- packages/digit_data_model/pubspec.lock | 8 +- packages/digit_data_model/pubspec.yaml | 2 +- packages/digit_dss/.gitignore | 29 + packages/digit_dss/.metadata | 10 + packages/digit_dss/CHANGELOG.md | 15 + packages/digit_dss/LICENSE | 21 + packages/digit_dss/README.md | 44 + packages/digit_dss/analysis_options.yaml | 4 + .../digit_dss/lib/blocs/app_localization.dart | 51 + packages/digit_dss/lib/blocs/dashboard.dart | 307 ++ .../lib/blocs/dashboard.freezed.dart | 1152 ++++ .../dashboard_localization_delegate.dart | 34 + .../schema/dashboard_config_schema.dart | 29 + .../schema/dashboard_config_schema.g.dart | 1121 ++++ .../no_sql/schema/dashboard_response.dart | 76 + .../no_sql/schema/dashboard_response.g.dart | 4018 ++++++++++++++ .../digit_dss/lib/data/remote/dashboard.dart | 152 + packages/digit_dss/lib/digit_dss.dart | 24 + packages/digit_dss/lib/digit_dss.init.dart | 24 + .../lib/models/entities/chart_data.dart | 30 + .../models/entities/chart_data.mapper.dart | 213 + .../lib/models/entities/dashboard_config.dart | 46 + .../entities/dashboard_config.freezed.dart | 585 ++ .../models/entities/dashboard_config.g.dart | 57 + .../models/entities/dashboard_request.dart | 56 + .../entities/dashboard_request.mapper.dart | 575 ++ .../entities/dashboard_response_model.dart | 44 + .../dashboard_response_model.mapper.dart | 370 ++ .../lib/models/entities/dss_enums.dart | 36 + .../lib/models/entities/dss_enums.mapper.dart | 101 + .../lib/models/entities/insight.dart | 26 + .../lib/models/entities/insight.mapper.dart | 175 + .../digit_dss/lib/models/entities/plots.dart | 28 + .../lib/models/entities/plots.mapper.dart | 189 + .../lib/pages/dashboard/dashboard.dart | 184 + .../lib/router/dashboard_router.dart | 17 + .../lib/router/dashboard_router.gm.dart | 38 + .../lib/utils/i18_key_constants.dart | 68 + packages/digit_dss/lib/utils/utils.dart | 200 + .../widgets/back_navigation_help_header.dart | 80 + .../dashboard/dashboard_metric_card.dart | 191 + packages/digit_dss/lib/widgets/localized.dart | 35 + .../digit_dss/lib/widgets/no_result_card.dart | 34 + packages/digit_dss/pubspec.yaml | 85 + packages/digit_dss/test/digit_dss_test.dart | 1 + packages/digit_scanner/CHANGELOG.md | 50 +- packages/digit_scanner/example/ios/Podfile | 44 + packages/digit_scanner/example/pubspec.lock | 13 +- packages/digit_scanner/lib/blocs/scanner.dart | 4 +- .../digit_scanner/lib/pages/qr_scanner.dart | 172 +- packages/digit_scanner/pubspec.lock | 33 +- packages/digit_scanner/pubspec.yaml | 5 +- packages/inventory_management/CHANGELOG.md | 78 +- .../lib/inventory_management.dart | 3 +- .../lib/inventory_management.init.dart | 26 +- .../lib/models/entities/inventory_enums.dart | 24 + .../entities/inventory_enums.mapper.dart | 79 + .../lib/pages/acknowledgement.dart | 4 +- .../lib/pages/facility_selection.dart | 4 +- .../lib/pages/manage_stocks.dart | 4 +- .../lib/pages/record_stock/stock_details.dart | 529 +- .../pages/record_stock/warehouse_details.dart | 6 +- .../lib/pages/reports/report_details.dart | 7 +- .../lib/pages/reports/report_selection.dart | 4 +- .../stock_reconciliation.dart | 4 +- .../lib/utils/i18_key_constants.dart | 4 + .../inventory_management/lib/utils/utils.dart | 17 +- .../widgets/reports/readonly_pluto_grid.dart | 4 +- packages/inventory_management/pubspec.lock | 12 +- packages/inventory_management/pubspec.yaml | 8 +- packages/referral_reconciliation/pubspec.lock | 9 +- packages/registration_delivery/CHANGELOG.md | 125 +- .../beneficiary_registration.dart | 344 +- .../beneficiary_registration.freezed.dart | 3069 ++++++++--- .../deliver_intervention.dart | 75 +- .../deliver_intervention.freezed.dart | 200 +- .../household_overview.dart | 12 +- .../household_global_seach.dart | 350 ++ .../individual_global_search.dart | 344 ++ .../search_households/proximity_search.dart | 171 - .../search_bloc_common_wrapper.dart | 43 +- .../search_households/search_by_head.dart | 247 - .../search_households/search_households.dart | 52 +- .../search_households.freezed.dart | 822 ++- .../search_households/tag_by_search.dart | 5 +- .../data/repositories/local/household.dart | 6 +- .../local/household_global_search.dart | 514 ++ .../local/individual_global_search.dart | 482 ++ .../local/project_beneficiary.dart | 1 - .../lib/data/repositories/local/referral.dart | 1 - .../local/registration_delivery_address.dart | 7 +- .../lib/data/repositories/local/task.dart | 92 +- .../entities/additional_fields_type.dart | 10 + .../additional_fields_type.mapper.dart | 20 + .../entities/registration_delivery_enums.dart | 14 + .../registration_delivery_enums.mapper.dart | 60 + .../lib/models/entities/status.dart | 40 +- .../lib/models/entities/status.mapper.dart | 28 +- .../beneficiary/beneficiary_checklist.dart | 526 ++ .../beneficiary/beneficiary_details.dart | 29 +- .../beneficiary/beneficiary_wrapper.dart | 13 +- .../beneficiary/deliver_intervention.dart | 1107 ++-- .../beneficiary/delivery_summary_page.dart | 370 ++ .../pages/beneficiary/dose_administered.dart | 40 +- .../pages/beneficiary/household_overview.dart | 1218 ++--- .../record_past_delivery_details.dart | 6 +- .../pages/beneficiary/refer_beneficiary.dart | 7 +- .../pages/beneficiary/refused_delivery.dart | 331 ++ .../lib/pages/beneficiary/side_effects.dart | 4 +- .../widgets/household_acknowledgement.dart | 6 +- .../beneficiary/widgets/past_delivery.dart | 16 +- .../widgets/record_delivery_cycle.dart | 4 +- .../widgets/splash_acknowledgement.dart | 4 +- .../beneficiary_acknowledgement.dart | 116 +- .../beneficiary_registration_wrapper.dart | 166 +- .../house_details.dart | 343 ++ .../household_details.dart | 607 ++- .../household_location.dart | 600 ++- .../individual_details.dart | 858 ++- .../lib/pages/reason_for_deletion.dart | 44 +- .../pages/registration_delivery_wrapper.dart | 211 +- .../lib/pages/search_beneficiary.dart | 425 +- .../lib/pages/summary_page.dart | 404 ++ .../lib/registration_delivery.dart | 28 +- .../lib/registration_delivery.init.dart | 30 +- .../router/registration_delivery_router.dart | 24 +- .../registration_delivery_router.gm.dart | 732 ++- .../lib/utils/constants.dart | 12 + .../lib/utils/global_search_parameters.dart | 25 + .../lib/utils/i18_key_constants.dart | 116 + .../lib/utils/utils.dart | 128 +- .../widgets/beneficiary/beneficiary_card.dart | 38 +- .../resource_beneficiary_card.dart | 46 +- .../beneficiary/view_beneficiary_card.dart | 150 +- .../lib/widgets/member_card/member_card.dart | 517 +- .../progress_bar/beneficiary_progress.dart | 4 +- .../showcase/config/house_details.dart | 23 + .../showcase/config/household_details.dart | 11 + .../showcase/config/household_location.dart | 5 + .../showcase/config/refused_delivery.dart | 28 + .../showcase/config/showcase_constants.dart | 4 + .../lib/widgets/showcase/showcase_button.dart | 4 +- .../widgets/showcase/showcase_wrappers.dart | 4 +- .../widgets/status_filter/status_filter.dart | 196 + packages/registration_delivery/pubspec.lock | 68 +- packages/registration_delivery/pubspec.yaml | 9 +- .../test/beneficiary_registration_test.dart | 5 + tools/closed_household_package_imports.dart | 356 ++ tools/digit_dss_imports.dart | 473 ++ tools/registration_delivery_imports.dart | 11 + 275 files changed, 36896 insertions(+), 6606 deletions(-) create mode 100644 apps/health_campaign_field_worker_app/assets/icons/svg/closed_household.svg create mode 100644 apps/health_campaign_field_worker_app/lib/data/repositories/local/localization.dart create mode 100644 apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.dart create mode 100644 apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.freezed.dart create mode 100644 apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.g.dart create mode 100644 apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_component.dart create mode 100644 apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_dialog.dart create mode 100644 apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_expand_component.dart delete mode 100644 packages/attendance_management/lib/data/local_store/sql_store/tables/attendance.dart create mode 100644 packages/closed_household/.gitignore create mode 100644 packages/closed_household/.metadata create mode 100644 packages/closed_household/CHANGELOG.md create mode 100644 packages/closed_household/LICENSE create mode 100644 packages/closed_household/README.md create mode 100644 packages/closed_household/analysis_options.yaml create mode 100644 packages/closed_household/assets/icons/app_icon.png create mode 100644 packages/closed_household/assets/icons/svg/mychecklist.svg create mode 100644 packages/closed_household/assets/icons/svg/no_result.svg create mode 100644 packages/closed_household/assets/images/powered_by_digit.png create mode 100644 packages/closed_household/build.yaml create mode 100644 packages/closed_household/lib/blocs/app_localization.dart create mode 100644 packages/closed_household/lib/blocs/closed_household.dart create mode 100644 packages/closed_household/lib/blocs/closed_household.freezed.dart create mode 100644 packages/closed_household/lib/blocs/closed_household_localization_delegate.dart create mode 100644 packages/closed_household/lib/closed_household.dart create mode 100644 packages/closed_household/lib/pages/closed_household_acknowledgement.dart create mode 100644 packages/closed_household/lib/pages/closed_household_details.dart create mode 100644 packages/closed_household/lib/pages/closed_household_summary.dart create mode 100644 packages/closed_household/lib/pages/closed_household_wrapper.dart create mode 100644 packages/closed_household/lib/router/closed_household_router.dart create mode 100644 packages/closed_household/lib/router/closed_household_router.gm.dart create mode 100644 packages/closed_household/lib/utils/constants.dart create mode 100644 packages/closed_household/lib/utils/extensions/context_utility.dart create mode 100644 packages/closed_household/lib/utils/extensions/extensions.dart create mode 100644 packages/closed_household/lib/utils/i18_key_constants.dart create mode 100644 packages/closed_household/lib/utils/utils.dart create mode 100644 packages/closed_household/lib/widgets/back_navigation_help_header.dart create mode 100644 packages/closed_household/lib/widgets/localized.dart create mode 100644 packages/closed_household/lib/widgets/showcase/config/closed_household_details.dart create mode 100644 packages/closed_household/lib/widgets/showcase/config/showcase_constants.dart create mode 100644 packages/closed_household/lib/widgets/showcase/showcase_button.dart create mode 100644 packages/closed_household/lib/widgets/showcase/showcase_wrappers.dart create mode 100644 packages/closed_household/pubspec.yaml create mode 100644 packages/closed_household/test/closed_household_test.dart create mode 100644 packages/digit_components/example/ios/Podfile create mode 100644 packages/digit_components/lib/utils/utils.dart create mode 100644 packages/digit_components/lib/widgets/atoms/details_card.dart create mode 100644 packages/digit_components/lib/widgets/atoms/selection_card.dart create mode 100644 packages/digit_components/lib/widgets/atoms/text_block.dart create mode 100644 packages/digit_data_model/lib/data/local_store/sql_store/tables/localization.dart create mode 100644 packages/digit_dss/.gitignore create mode 100644 packages/digit_dss/.metadata create mode 100644 packages/digit_dss/CHANGELOG.md create mode 100644 packages/digit_dss/LICENSE create mode 100644 packages/digit_dss/README.md create mode 100644 packages/digit_dss/analysis_options.yaml create mode 100644 packages/digit_dss/lib/blocs/app_localization.dart create mode 100644 packages/digit_dss/lib/blocs/dashboard.dart create mode 100644 packages/digit_dss/lib/blocs/dashboard.freezed.dart create mode 100644 packages/digit_dss/lib/blocs/dashboard_localization_delegate.dart create mode 100644 packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.dart create mode 100644 packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.g.dart create mode 100644 packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.dart create mode 100644 packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.g.dart create mode 100644 packages/digit_dss/lib/data/remote/dashboard.dart create mode 100644 packages/digit_dss/lib/digit_dss.dart create mode 100644 packages/digit_dss/lib/digit_dss.init.dart create mode 100644 packages/digit_dss/lib/models/entities/chart_data.dart create mode 100644 packages/digit_dss/lib/models/entities/chart_data.mapper.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_config.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_config.freezed.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_config.g.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_request.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_request.mapper.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_response_model.dart create mode 100644 packages/digit_dss/lib/models/entities/dashboard_response_model.mapper.dart create mode 100644 packages/digit_dss/lib/models/entities/dss_enums.dart create mode 100644 packages/digit_dss/lib/models/entities/dss_enums.mapper.dart create mode 100644 packages/digit_dss/lib/models/entities/insight.dart create mode 100644 packages/digit_dss/lib/models/entities/insight.mapper.dart create mode 100644 packages/digit_dss/lib/models/entities/plots.dart create mode 100644 packages/digit_dss/lib/models/entities/plots.mapper.dart create mode 100644 packages/digit_dss/lib/pages/dashboard/dashboard.dart create mode 100644 packages/digit_dss/lib/router/dashboard_router.dart create mode 100644 packages/digit_dss/lib/router/dashboard_router.gm.dart create mode 100644 packages/digit_dss/lib/utils/i18_key_constants.dart create mode 100644 packages/digit_dss/lib/utils/utils.dart create mode 100644 packages/digit_dss/lib/widgets/back_navigation_help_header.dart create mode 100644 packages/digit_dss/lib/widgets/dashboard/dashboard_metric_card.dart create mode 100644 packages/digit_dss/lib/widgets/localized.dart create mode 100644 packages/digit_dss/lib/widgets/no_result_card.dart create mode 100644 packages/digit_dss/pubspec.yaml create mode 100644 packages/digit_dss/test/digit_dss_test.dart create mode 100644 packages/digit_scanner/example/ios/Podfile create mode 100644 packages/inventory_management/lib/models/entities/inventory_enums.dart create mode 100644 packages/inventory_management/lib/models/entities/inventory_enums.mapper.dart create mode 100644 packages/registration_delivery/lib/blocs/search_households/household_global_seach.dart create mode 100644 packages/registration_delivery/lib/blocs/search_households/individual_global_search.dart delete mode 100644 packages/registration_delivery/lib/blocs/search_households/proximity_search.dart delete mode 100644 packages/registration_delivery/lib/blocs/search_households/search_by_head.dart create mode 100644 packages/registration_delivery/lib/data/repositories/local/household_global_search.dart create mode 100644 packages/registration_delivery/lib/data/repositories/local/individual_global_search.dart create mode 100644 packages/registration_delivery/lib/models/entities/registration_delivery_enums.dart create mode 100644 packages/registration_delivery/lib/models/entities/registration_delivery_enums.mapper.dart create mode 100644 packages/registration_delivery/lib/pages/beneficiary/beneficiary_checklist.dart create mode 100644 packages/registration_delivery/lib/pages/beneficiary/delivery_summary_page.dart create mode 100644 packages/registration_delivery/lib/pages/beneficiary/refused_delivery.dart create mode 100644 packages/registration_delivery/lib/pages/beneficiary_registration/house_details.dart create mode 100644 packages/registration_delivery/lib/pages/summary_page.dart create mode 100644 packages/registration_delivery/lib/utils/global_search_parameters.dart create mode 100644 packages/registration_delivery/lib/widgets/showcase/config/house_details.dart create mode 100644 packages/registration_delivery/lib/widgets/showcase/config/refused_delivery.dart create mode 100644 packages/registration_delivery/lib/widgets/status_filter/status_filter.dart create mode 100644 tools/closed_household_package_imports.dart create mode 100644 tools/digit_dss_imports.dart diff --git a/apps/health_campaign_field_worker_app/android/app/src/main/AndroidManifest.xml b/apps/health_campaign_field_worker_app/android/app/src/main/AndroidManifest.xml index 0adfdeff4..6bdfc6e86 100644 --- a/apps/health_campaign_field_worker_app/android/app/src/main/AndroidManifest.xml +++ b/apps/health_campaign_field_worker_app/android/app/src/main/AndroidManifest.xml @@ -1,45 +1,47 @@ - - - - - - - - - + + + + + + + + + + + - - + + - - - - - + + + + + - - - + + + android:icon="@mipmap/ic_launcher" + android:label="HCM"> android:allowBackup="false" android:fullBackupOnly="false" android:fullBackupContent="false" + android:turnScreenOn="true" + android:windowSoftInputMode="adjustResize"> + android:name="io.flutter.embedding.android.NormalTheme" + android:resource="@style/NormalTheme" /> - - + + - + diff --git a/apps/health_campaign_field_worker_app/assets/icons/svg/closed_household.svg b/apps/health_campaign_field_worker_app/assets/icons/svg/closed_household.svg new file mode 100644 index 000000000..98b73eed4 --- /dev/null +++ b/apps/health_campaign_field_worker_app/assets/icons/svg/closed_household.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/apps/health_campaign_field_worker_app/lib/app.dart b/apps/health_campaign_field_worker_app/lib/app.dart index 8c576af11..7d90ae5da 100644 --- a/apps/health_campaign_field_worker_app/lib/app.dart +++ b/apps/health_campaign_field_worker_app/lib/app.dart @@ -1,6 +1,9 @@ import 'package:attendance_management/attendance_management.dart'; +import 'package:closed_household/blocs/closed_household.dart'; +import 'package:closed_household/closed_household.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/digit_dss.dart'; import 'package:digit_scanner/blocs/scanner.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; @@ -8,6 +11,13 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:inventory_management/inventory_management.dart'; import 'package:isar/isar.dart'; import 'package:location/location.dart'; +import 'package:registration_delivery/data/repositories/local/household_global_search.dart'; +import 'package:registration_delivery/data/repositories/local/individual_global_search.dart'; +import 'package:registration_delivery/data/repositories/oplog/oplog.dart'; +import 'package:registration_delivery/models/entities/household.dart'; +import 'package:registration_delivery/models/entities/household_member.dart'; +import 'package:registration_delivery/models/entities/project_beneficiary.dart'; +import 'package:registration_delivery/models/entities/task.dart'; import 'blocs/app_initialization/app_initialization.dart'; import 'blocs/auth/auth.dart'; @@ -46,17 +56,37 @@ class MainApplication extends StatefulWidget { class MainApplicationState extends State with WidgetsBindingObserver { + @override + void initState() { + LocalizationParams().setModule('boundary', true); + super.initState(); + requestDisableBatteryOptimization(); + } + @override Widget build(BuildContext context) { return MultiRepositoryProvider( providers: [ RepositoryProvider.value(value: widget.sql), RepositoryProvider.value(value: widget.isar), + RepositoryProvider( + create: (context) => IndividualGlobalSearchRepository( + widget.sql, + IndividualOpLogManager(widget.isar), + ), + ), + RepositoryProvider( + create: (context) => HouseHoldGlobalSearchRepository( + widget.sql, + HouseholdOpLogManager(widget.isar), + ), + ), ], child: BlocProvider( create: (context) => AppInitializationBloc( isar: widget.isar, mdmsRepository: MdmsRepository(widget.client), + dashboardRemoteRepository: DashboardRemoteRepository(widget.client), )..add(const AppInitializationSetupEvent()), child: NetworkManagerProviderWrapper( isar: widget.isar, @@ -133,6 +163,10 @@ class MainApplicationState extends State final localizationModulesList = appConfig.backendInterface; var firstLanguage; firstLanguage = appConfig.languages?.lastOrNull?.value; + final selectedLocale = + AppSharedPreferences().getSelectedLocale ?? + firstLanguage; + LocalizationParams().setLocale(Locale(selectedLocale)); final languages = appConfig.languages; return MultiBlocProvider( @@ -141,39 +175,35 @@ class MainApplicationState extends State create: (localizationModulesList != null && firstLanguage != null) ? (context) => LocalizationBloc( - const LocalizationState(), - LocalizationRepository( - widget.client, - widget.isar, - ), - widget.isar, - )..add( - LocalizationEvent.onLoadLocalization( - module: localizationModulesList - .interfaces - .where((element) => - element.type == - Modules.localizationModule) - .map((e) => e.name.toString()) - .join(',') - .toString(), - tenantId: appConfig.tenantId.toString(), - locale: firstLanguage, - path: Constants.localizationApiPath, - ), - ) - : (context) => LocalizationBloc( - const LocalizationState(), - LocalizationRepository( - widget.client, - widget.isar, - ), - widget.isar, + const LocalizationState(), + LocalizationRepository( + widget.client, widget.sql), + widget.sql) + ..add( + LocalizationEvent.onLoadLocalization( + module: localizationModulesList.interfaces + .where((element) => + element.type == + Modules.localizationModule) + .map((e) => e.name.toString()) + .join(',') + .toString(), + tenantId: appConfig.tenantId.toString(), + locale: firstLanguage, + path: Constants.localizationApiPath, ), + ) + : (context) => LocalizationBloc( + const LocalizationState(), + LocalizationRepository( + widget.client, widget.sql), + widget.sql), ), BlocProvider( create: (ctx) => ProjectBloc( mdmsRepository: MdmsRepository(widget.client), + dashboardRemoteRepository: + DashboardRemoteRepository(widget.client), facilityLocalRepository: ctx.read< LocalRepository>(), @@ -250,6 +280,18 @@ class MainApplicationState extends State context: context, ), ), + BlocProvider( + create: (ctx) => DashboardBloc( + const DashboardState.initialState(), + isar: widget.isar, + dashboardRemoteRepo: + DashboardRemoteRepository(widget.client), + attendanceDataRepository: context.repository< + AttendanceRegisterModel, + AttendanceRegisterSearchModel>(), + individualDataRepository: context.repository< + IndividualModel, IndividualSearchModel>(), + )), BlocProvider( create: (context) => FacilityBloc( facilityDataRepository: context.repository< @@ -276,6 +318,26 @@ class MainApplicationState extends State ProjectFacilitySearchModel>(), ), ), + BlocProvider( + create: (_) { + return ClosedHouseholdBloc( + const ClosedHouseholdState(), + householdMemberRepository: context.repository< + HouseholdMemberModel, + HouseholdMemberSearchModel>(), + householdRepository: context.repository< + HouseholdModel, HouseholdSearchModel>(), + individualRepository: context.repository< + IndividualModel, IndividualSearchModel>(), + projectBeneficiaryRepository: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(), + taskRepository: context + .repository(), + ); + }, + lazy: false, + ), ], child: BlocBuilder( builder: (context, langState) { @@ -317,9 +379,12 @@ class MainApplicationState extends State }) : [firstLanguage], localizationsDelegates: getAppLocalizationDelegates( - isar: widget.isar, + sql: widget.sql, appConfig: appConfig, - selectedLocale: selectedLocale, + selectedLocale: Locale( + selectedLocale!.split("_").first, + selectedLocale.split("_").last, + ), ), locale: languages != null ? Locale( diff --git a/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.dart b/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.dart index 531e69143..4530ae776 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.dart @@ -1,7 +1,10 @@ import 'dart:async'; +import 'dart:convert'; import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/digit_dss.dart'; +import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:isar/isar.dart'; @@ -24,10 +27,12 @@ typedef AppInitializationEmitter = Emitter; class AppInitializationBloc extends Bloc { final MdmsRepository mdmsRepository; + final DashboardRemoteRepository dashboardRemoteRepository; final Isar isar; AppInitializationBloc({ required this.mdmsRepository, + required this.dashboardRemoteRepository, required this.isar, }) : super(const AppUninitialized()) { on(_onAppInitializeSetup); @@ -49,6 +54,7 @@ class AppInitializationBloc emit(AppInitialized( appConfiguration: config.appConfigs.firstOrNull!, serviceRegistryList: config.serviceRegistryList, + dashboardConfigSchema: config.dashboardConfigSchema, )); } on AppInitializationException catch (_) { emit(const AppUninitialized()); @@ -85,6 +91,8 @@ class AppInitializationBloc MasterEnums.appConfig.toValue(), MasterEnums.symptomTypes.toValue(), MasterEnums.referralReasons.toValue(), + MasterEnums.houseStructureTypes.toValue(), + MasterEnums.refusalReasons.toValue(), MasterEnums.bandWidthBatchSize.toValue(), MasterEnums.downSyncBandwidthBatchSize.toValue(), MasterEnums.hhDelReasons.toValue(), @@ -97,13 +105,15 @@ class AppInitializationBloc MasterEnums.callSupport.toValue(), MasterEnums.transportTypes.toValue(), MasterEnums.firebaseConfig.toValue(), + MasterEnums.searchHouseHoldFilters.toValue(), ]), ), MdmsModuleDetailModel( moduleName: ModuleEnums.commonMasters.toValue(), masterDetails: getMasterDetailsModel([ MasterEnums.stateInfo.toValue(), - MasterEnums.genderType.toValue() + MasterEnums.genderType.toValue(), + MasterEnums.privacyPolicy.toValue(), ]), ), MdmsModuleDetailModel( @@ -115,7 +125,6 @@ class AppInitializationBloc ), ).toJson(), ); - final pgrServiceDefinitions = await mdmsRepository.searchPGRServiceDefinitions( envConfig.variables.mdmsApiPath, @@ -140,6 +149,43 @@ class AppInitializationBloc pgrServiceDefinitions, isar, ); + try { + final dashboardConfigWrapper = + await dashboardRemoteRepository.searchDashboardConfig( + envConfig.variables.mdmsApiPath, + MdmsRequestModel( + mdmsCriteria: MdmsCriteriaModel( + tenantId: envConfig.variables.tenantId, + moduleDetails: [ + MdmsModuleDetailModel( + moduleName: ModuleEnums.hcm.toValue(), + masterDetails: [ + MdmsMasterDetailModel( + MasterEnums.dashboardConfig.toValue(), + ), + ], + ), + ], + ), + ).toJson(), + ); + final dashboardConfigs = DashboardConfigPrimaryWrapper.fromJson( + jsonDecode(dashboardConfigWrapper)['MdmsRes'] + [ModuleEnums.hcm.toValue()]) + .dashboardConfigWrapper; + + if (dashboardConfigs.isNotEmpty) { + await dashboardRemoteRepository.writeToDashboardConfigDB( + DashboardConfigPrimaryWrapper.fromJson( + jsonDecode(dashboardConfigWrapper)['MdmsRes'] + [ModuleEnums.hcm.toValue()]) + .dashboardConfigWrapper + .first, + isar); + } + } catch (e) { + debugPrint(e.toString()); + } add( AppInitializationSetupEvent( @@ -148,6 +194,7 @@ class AppInitializationBloc ); emit(const AppUninitialized()); } catch (e) { + debugPrint('AppInitializationBloc: $e'); /*Checks for if app initialization failed due to no internet or no retries left */ emit(const AppInitializationState.failed()); } @@ -159,6 +206,12 @@ class AppInitializationBloc ) async { final serviceRegistryList = await isar.serviceRegistrys.where().findAll(); final configs = await isar.appConfigurations.where().findAll(); + final dashboardConfigs = await isar.dashboardConfigSchemas + .where() + .filter() + .chartsIsNotNull() + .chartsIsNotEmpty() + .findAll(); if (serviceRegistryList.isEmpty) { throw Exception('`serviceRegistryList` cannot be empty'); @@ -170,6 +223,7 @@ class AppInitializationBloc return MdmsConfig( appConfigs: configs, serviceRegistryList: serviceRegistryList, + dashboardConfigSchema: dashboardConfigs.firstOrNull, ); } } @@ -193,6 +247,7 @@ class AppInitializationState with _$AppInitializationState { const factory AppInitializationState.initialized({ required AppConfiguration appConfiguration, @Default([]) List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema, }) = AppInitialized; Map> get entityActionMapping { @@ -200,7 +255,7 @@ class AppInitializationState with _$AppInitializationState { uninitialized: () => {}, loading: () => {}, failed: () => {}, - initialized: (appConfiguration, serviceRegistryList) => + initialized: (appConfiguration, serviceRegistryList, _) => serviceRegistryList .map((e) => e.actions.map((e) { ApiOperation? operation; @@ -246,7 +301,7 @@ class AppInitializationState with _$AppInitializationState { uninitialized: () => 'Uninitialized', loading: () => 'Loading', failed: () => 'Failed', - initialized: (appConfiguration, serviceRegistryList) => + initialized: (appConfiguration, serviceRegistryList, _) => 'tenantId: ${appConfiguration.tenantId}\n' 'serviceCount: ${serviceRegistryList.length}', ); @@ -256,11 +311,12 @@ class AppInitializationState with _$AppInitializationState { class MdmsConfig { final List appConfigs; final List serviceRegistryList; + final DashboardConfigSchema? dashboardConfigSchema; - const MdmsConfig({ - required this.appConfigs, - required this.serviceRegistryList, - }); + const MdmsConfig( + {required this.appConfigs, + required this.serviceRegistryList, + this.dashboardConfigSchema}); } class AppInitializationException implements Exception { diff --git a/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.freezed.dart b/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.freezed.dart index 68e67727e..6fbad1976 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.freezed.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/app_initialization/app_initialization.freezed.dart @@ -234,8 +234,10 @@ mixin _$AppInitializationState { required TResult Function() uninitialized, required TResult Function() loading, required TResult Function() failed, - required TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList) + required TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema) initialized, }) => throw _privateConstructorUsedError; @@ -244,8 +246,10 @@ mixin _$AppInitializationState { TResult? Function()? uninitialized, TResult? Function()? loading, TResult? Function()? failed, - TResult? Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult? Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, }) => throw _privateConstructorUsedError; @@ -254,8 +258,10 @@ mixin _$AppInitializationState { TResult Function()? uninitialized, TResult Function()? loading, TResult Function()? failed, - TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, required TResult orElse(), }) => @@ -342,8 +348,10 @@ class _$AppUninitializedImpl extends AppUninitialized { required TResult Function() uninitialized, required TResult Function() loading, required TResult Function() failed, - required TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList) + required TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema) initialized, }) { return uninitialized(); @@ -355,8 +363,10 @@ class _$AppUninitializedImpl extends AppUninitialized { TResult? Function()? uninitialized, TResult? Function()? loading, TResult? Function()? failed, - TResult? Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult? Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, }) { return uninitialized?.call(); @@ -368,8 +378,10 @@ class _$AppUninitializedImpl extends AppUninitialized { TResult Function()? uninitialized, TResult Function()? loading, TResult Function()? failed, - TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, required TResult orElse(), }) { @@ -458,8 +470,10 @@ class _$AppInitializingImpl extends AppInitializing { required TResult Function() uninitialized, required TResult Function() loading, required TResult Function() failed, - required TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList) + required TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema) initialized, }) { return loading(); @@ -471,8 +485,10 @@ class _$AppInitializingImpl extends AppInitializing { TResult? Function()? uninitialized, TResult? Function()? loading, TResult? Function()? failed, - TResult? Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult? Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, }) { return loading?.call(); @@ -484,8 +500,10 @@ class _$AppInitializingImpl extends AppInitializing { TResult Function()? uninitialized, TResult Function()? loading, TResult Function()? failed, - TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, required TResult orElse(), }) { @@ -578,8 +596,10 @@ class _$AppInitializationFailedImpl extends AppInitializationFailed { required TResult Function() uninitialized, required TResult Function() loading, required TResult Function() failed, - required TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList) + required TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema) initialized, }) { return failed(); @@ -591,8 +611,10 @@ class _$AppInitializationFailedImpl extends AppInitializationFailed { TResult? Function()? uninitialized, TResult? Function()? loading, TResult? Function()? failed, - TResult? Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult? Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, }) { return failed?.call(); @@ -604,8 +626,10 @@ class _$AppInitializationFailedImpl extends AppInitializationFailed { TResult Function()? uninitialized, TResult Function()? loading, TResult Function()? failed, - TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, required TResult orElse(), }) { @@ -666,7 +690,8 @@ abstract class _$$AppInitializedImplCopyWith<$Res> { @useResult $Res call( {AppConfiguration appConfiguration, - List serviceRegistryList}); + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema}); } /// @nodoc @@ -682,6 +707,7 @@ class __$$AppInitializedImplCopyWithImpl<$Res> $Res call({ Object? appConfiguration = null, Object? serviceRegistryList = null, + Object? dashboardConfigSchema = freezed, }) { return _then(_$AppInitializedImpl( appConfiguration: null == appConfiguration @@ -692,6 +718,10 @@ class __$$AppInitializedImplCopyWithImpl<$Res> ? _value._serviceRegistryList : serviceRegistryList // ignore: cast_nullable_to_non_nullable as List, + dashboardConfigSchema: freezed == dashboardConfigSchema + ? _value.dashboardConfigSchema + : dashboardConfigSchema // ignore: cast_nullable_to_non_nullable + as DashboardConfigSchema?, )); } } @@ -701,7 +731,8 @@ class __$$AppInitializedImplCopyWithImpl<$Res> class _$AppInitializedImpl extends AppInitialized { const _$AppInitializedImpl( {required this.appConfiguration, - final List serviceRegistryList = const []}) + final List serviceRegistryList = const [], + this.dashboardConfigSchema}) : _serviceRegistryList = serviceRegistryList, super._(); @@ -717,6 +748,9 @@ class _$AppInitializedImpl extends AppInitialized { return EqualUnmodifiableListView(_serviceRegistryList); } + @override + final DashboardConfigSchema? dashboardConfigSchema; + @override bool operator ==(Object other) { return identical(this, other) || @@ -725,12 +759,17 @@ class _$AppInitializedImpl extends AppInitialized { (identical(other.appConfiguration, appConfiguration) || other.appConfiguration == appConfiguration) && const DeepCollectionEquality() - .equals(other._serviceRegistryList, _serviceRegistryList)); + .equals(other._serviceRegistryList, _serviceRegistryList) && + (identical(other.dashboardConfigSchema, dashboardConfigSchema) || + other.dashboardConfigSchema == dashboardConfigSchema)); } @override - int get hashCode => Object.hash(runtimeType, appConfiguration, - const DeepCollectionEquality().hash(_serviceRegistryList)); + int get hashCode => Object.hash( + runtimeType, + appConfiguration, + const DeepCollectionEquality().hash(_serviceRegistryList), + dashboardConfigSchema); @JsonKey(ignore: true) @override @@ -745,11 +784,14 @@ class _$AppInitializedImpl extends AppInitialized { required TResult Function() uninitialized, required TResult Function() loading, required TResult Function() failed, - required TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList) + required TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema) initialized, }) { - return initialized(appConfiguration, serviceRegistryList); + return initialized( + appConfiguration, serviceRegistryList, dashboardConfigSchema); } @override @@ -758,11 +800,14 @@ class _$AppInitializedImpl extends AppInitialized { TResult? Function()? uninitialized, TResult? Function()? loading, TResult? Function()? failed, - TResult? Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult? Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, }) { - return initialized?.call(appConfiguration, serviceRegistryList); + return initialized?.call( + appConfiguration, serviceRegistryList, dashboardConfigSchema); } @override @@ -771,13 +816,16 @@ class _$AppInitializedImpl extends AppInitialized { TResult Function()? uninitialized, TResult Function()? loading, TResult Function()? failed, - TResult Function(AppConfiguration appConfiguration, - List serviceRegistryList)? + TResult Function( + AppConfiguration appConfiguration, + List serviceRegistryList, + DashboardConfigSchema? dashboardConfigSchema)? initialized, required TResult orElse(), }) { if (initialized != null) { - return initialized(appConfiguration, serviceRegistryList); + return initialized( + appConfiguration, serviceRegistryList, dashboardConfigSchema); } return orElse(); } @@ -822,12 +870,15 @@ class _$AppInitializedImpl extends AppInitialized { abstract class AppInitialized extends AppInitializationState { const factory AppInitialized( - {required final AppConfiguration appConfiguration, - final List serviceRegistryList}) = _$AppInitializedImpl; + {required final AppConfiguration appConfiguration, + final List serviceRegistryList, + final DashboardConfigSchema? dashboardConfigSchema}) = + _$AppInitializedImpl; const AppInitialized._() : super._(); AppConfiguration get appConfiguration; List get serviceRegistryList; + DashboardConfigSchema? get dashboardConfigSchema; @JsonKey(ignore: true) _$$AppInitializedImplCopyWith<_$AppInitializedImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localization.dart b/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localization.dart index a39066ea1..b11d925fe 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localization.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localization.dart @@ -1,14 +1,15 @@ +import 'package:digit_data_model/data/local_store/sql_store/sql_store.dart'; import 'package:flutter/material.dart'; -import 'package:isar/isar.dart'; import '../../data/local_store/no_sql/schema/app_configuration.dart'; import '../../data/local_store/no_sql/schema/localization.dart'; +import '../../data/repositories/local/localization.dart'; import 'app_localizations_delegate.dart'; class AppLocalizations { final Locale locale; - final Isar isar; + final LocalSqlDataStore sql; - AppLocalizations(this.locale, this.isar); + AppLocalizations(this.locale, this.sql); static AppLocalizations of(BuildContext context) { return Localizations.of(context, AppLocalizations)!; @@ -17,22 +18,15 @@ class AppLocalizations { static final List _localizedStrings = []; static LocalizationsDelegate getDelegate( - AppConfiguration config, - Isar isar, - ) => - AppLocalizationsDelegate(config, isar); + AppConfiguration config, LocalSqlDataStore sql) => + AppLocalizationsDelegate(config, sql); Future load() async { _localizedStrings.clear(); - final List localizationList = await isar - .localizationWrappers - .filter() - .localeEqualTo('${locale.languageCode}_${locale.countryCode}') - .findAll(); - - if (localizationList.isNotEmpty) { - _localizedStrings.addAll(localizationList.first.localization!); - } + + final listOfLocalizations = await LocalizationLocalRepository().returnLocalizationFromSQL(sql); + + _localizedStrings.addAll(listOfLocalizations); return true; } diff --git a/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localizations_delegate.dart b/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localizations_delegate.dart index 352adb17c..7eaf5b020 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localizations_delegate.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/localization/app_localizations_delegate.dart @@ -1,4 +1,5 @@ import 'package:collection/collection.dart'; +import 'package:digit_data_model/data/local_store/sql_store/sql_store.dart'; import 'package:flutter/material.dart'; import 'package:isar/isar.dart'; import '../../data/local_store/no_sql/schema/app_configuration.dart'; @@ -6,9 +7,9 @@ import 'app_localization.dart'; class AppLocalizationsDelegate extends LocalizationsDelegate { final AppConfiguration _appConfig; - final Isar isar; + final LocalSqlDataStore sql; - const AppLocalizationsDelegate(this._appConfig, this.isar); + const AppLocalizationsDelegate(this._appConfig, this.sql); @override bool isSupported(Locale locale) { @@ -27,7 +28,7 @@ class AppLocalizationsDelegate extends LocalizationsDelegate { Future load( Locale locale, ) async { - AppLocalizations appLocalizations = AppLocalizations(locale, isar); + AppLocalizations appLocalizations = AppLocalizations(locale, sql); await appLocalizations.load(); return appLocalizations; diff --git a/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.dart b/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.dart index 11e11b124..5784ce14d 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.dart @@ -1,10 +1,12 @@ import 'dart:async'; +import 'package:digit_data_model/data/local_store/sql_store/sql_store.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; -import 'package:isar/isar.dart'; import '../../data/local_store/app_shared_preferences.dart'; +import '../../data/repositories/local/localization.dart'; import '../../data/repositories/remote/localization.dart'; +import '../../utils/utils.dart'; import 'app_localization.dart'; part 'localization.freezed.dart'; @@ -13,12 +15,12 @@ typedef LocalizationEmitter = Emitter; class LocalizationBloc extends Bloc { final LocalizationRepository localizationRepository; - final Isar isar; + final LocalSqlDataStore sql; LocalizationBloc( super.initialState, this.localizationRepository, - this.isar, + this.sql, ) { on(_onLoadLocalization); on(_onUpdateLocalizationIndex); @@ -31,12 +33,63 @@ class LocalizationBloc extends Bloc { emit(state.copyWith(loading: true)); try { - await localizationRepository.loadLocalization( - path: event.path, - locale: event.locale, - module: event.module, - tenantId: event.tenantId, - ); + final boundaryModuleCheck = + event.module.contains(Constants.boundaryLocalizationPath); + final allModules = event.module.split(','); + var boundaryModule; + + if (boundaryModuleCheck) { + final boundaryModuleIndex = + allModules.indexOf(Constants.boundaryLocalizationPath); + boundaryModule = allModules[boundaryModuleIndex]; + allModules.removeAt(boundaryModuleIndex); + } + + try { + var localizationList; + + var localResults = await LocalizationLocalRepository() + .fetchLocalization( + sql: sql, locale: event.locale, module: allModules.join(',')); + if (localResults.isEmpty) { + var results = await localizationRepository.loadLocalization( + path: event.path, + locale: event.locale, + module: allModules.join(','), + tenantId: event.tenantId, + ); + localizationList = LocalizationLocalRepository().create(results, sql); + if (boundaryModule != null) { + try { + var localizationList; + var localResults = await LocalizationLocalRepository() + .fetchLocalization( + sql: sql, locale: event.locale, module: boundaryModule); + if (localResults.isEmpty) { + var results = await localizationRepository.loadLocalization( + path: event.path, + locale: event.locale, + module: boundaryModule, + tenantId: event.tenantId, + ); + + localizationList = + LocalizationLocalRepository().create(results, sql); + } else { + localizationList = localResults; + } + } catch (error) { + debugPrint('error in boundary module localization $error'); + emit(state.copyWith(loading: false, retryModule: boundaryModule)); + } + } + } else { + localizationList = localResults; + } + } catch (error) { + debugPrint('error in other modules localization $error'); + emit(state.copyWith(loading: false, retryModule: allModules.join(','))); + } final List codes = event.locale.split('_'); await _loadLocale(codes); @@ -58,7 +111,8 @@ class LocalizationBloc extends Bloc { } FutureOr _loadLocale(List codes) async { - await AppLocalizations(Locale(codes.first, codes.last), isar).load(); + LocalizationParams().setLocale(Locale(codes.first, codes.last)); + await AppLocalizations(Locale(codes.first, codes.last), sql).load(); } } @@ -83,5 +137,6 @@ class LocalizationState with _$LocalizationState { @Default(false) bool loading, @Default(0) int index, @Default(false) bool isLocalizationLoadCompleted, + String? retryModule, }) = _LocalizationState; } diff --git a/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.freezed.dart b/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.freezed.dart index 928e83c4b..520ed63f0 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.freezed.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/localization/localization.freezed.dart @@ -430,6 +430,7 @@ mixin _$LocalizationState { bool get loading => throw _privateConstructorUsedError; int get index => throw _privateConstructorUsedError; bool get isLocalizationLoadCompleted => throw _privateConstructorUsedError; + String? get retryModule => throw _privateConstructorUsedError; @JsonKey(ignore: true) $LocalizationStateCopyWith get copyWith => @@ -442,7 +443,11 @@ abstract class $LocalizationStateCopyWith<$Res> { LocalizationState value, $Res Function(LocalizationState) then) = _$LocalizationStateCopyWithImpl<$Res, LocalizationState>; @useResult - $Res call({bool loading, int index, bool isLocalizationLoadCompleted}); + $Res call( + {bool loading, + int index, + bool isLocalizationLoadCompleted, + String? retryModule}); } /// @nodoc @@ -461,6 +466,7 @@ class _$LocalizationStateCopyWithImpl<$Res, $Val extends LocalizationState> Object? loading = null, Object? index = null, Object? isLocalizationLoadCompleted = null, + Object? retryModule = freezed, }) { return _then(_value.copyWith( loading: null == loading @@ -475,6 +481,10 @@ class _$LocalizationStateCopyWithImpl<$Res, $Val extends LocalizationState> ? _value.isLocalizationLoadCompleted : isLocalizationLoadCompleted // ignore: cast_nullable_to_non_nullable as bool, + retryModule: freezed == retryModule + ? _value.retryModule + : retryModule // ignore: cast_nullable_to_non_nullable + as String?, ) as $Val); } } @@ -487,7 +497,11 @@ abstract class _$$LocalizationStateImplCopyWith<$Res> __$$LocalizationStateImplCopyWithImpl<$Res>; @override @useResult - $Res call({bool loading, int index, bool isLocalizationLoadCompleted}); + $Res call( + {bool loading, + int index, + bool isLocalizationLoadCompleted, + String? retryModule}); } /// @nodoc @@ -504,6 +518,7 @@ class __$$LocalizationStateImplCopyWithImpl<$Res> Object? loading = null, Object? index = null, Object? isLocalizationLoadCompleted = null, + Object? retryModule = freezed, }) { return _then(_$LocalizationStateImpl( loading: null == loading @@ -518,6 +533,10 @@ class __$$LocalizationStateImplCopyWithImpl<$Res> ? _value.isLocalizationLoadCompleted : isLocalizationLoadCompleted // ignore: cast_nullable_to_non_nullable as bool, + retryModule: freezed == retryModule + ? _value.retryModule + : retryModule // ignore: cast_nullable_to_non_nullable + as String?, )); } } @@ -528,7 +547,8 @@ class _$LocalizationStateImpl implements _LocalizationState { const _$LocalizationStateImpl( {this.loading = false, this.index = 0, - this.isLocalizationLoadCompleted = false}); + this.isLocalizationLoadCompleted = false, + this.retryModule}); @override @JsonKey() @@ -539,10 +559,12 @@ class _$LocalizationStateImpl implements _LocalizationState { @override @JsonKey() final bool isLocalizationLoadCompleted; + @override + final String? retryModule; @override String toString() { - return 'LocalizationState(loading: $loading, index: $index, isLocalizationLoadCompleted: $isLocalizationLoadCompleted)'; + return 'LocalizationState(loading: $loading, index: $index, isLocalizationLoadCompleted: $isLocalizationLoadCompleted, retryModule: $retryModule)'; } @override @@ -555,12 +577,14 @@ class _$LocalizationStateImpl implements _LocalizationState { (identical(other.isLocalizationLoadCompleted, isLocalizationLoadCompleted) || other.isLocalizationLoadCompleted == - isLocalizationLoadCompleted)); + isLocalizationLoadCompleted) && + (identical(other.retryModule, retryModule) || + other.retryModule == retryModule)); } @override - int get hashCode => - Object.hash(runtimeType, loading, index, isLocalizationLoadCompleted); + int get hashCode => Object.hash( + runtimeType, loading, index, isLocalizationLoadCompleted, retryModule); @JsonKey(ignore: true) @override @@ -574,7 +598,8 @@ abstract class _LocalizationState implements LocalizationState { const factory _LocalizationState( {final bool loading, final int index, - final bool isLocalizationLoadCompleted}) = _$LocalizationStateImpl; + final bool isLocalizationLoadCompleted, + final String? retryModule}) = _$LocalizationStateImpl; @override bool get loading; @@ -583,6 +608,8 @@ abstract class _LocalizationState implements LocalizationState { @override bool get isLocalizationLoadCompleted; @override + String? get retryModule; + @override @JsonKey(ignore: true) _$$LocalizationStateImplCopyWith<_$LocalizationStateImpl> get copyWith => throw _privateConstructorUsedError; diff --git a/apps/health_campaign_field_worker_app/lib/blocs/project/project.dart b/apps/health_campaign_field_worker_app/lib/blocs/project/project.dart index 55d0dbe0e..18e420dea 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/project/project.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/project/project.dart @@ -6,6 +6,7 @@ import 'package:attendance_management/attendance_management.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/digit_dss.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -16,6 +17,7 @@ import 'package:recase/recase.dart'; import '../../../models/app_config/app_config_model.dart' as app_configuration; import '../../data/local_store/no_sql/schema/app_configuration.dart'; import '../../data/local_store/no_sql/schema/row_versions.dart'; +import '../../data/local_store/no_sql/schema/service_registry.dart'; import '../../data/local_store/secure_store/secure_store.dart'; import '../../data/repositories/remote/mdms.dart'; import '../../models/app_config/app_config_model.dart'; @@ -96,6 +98,7 @@ class ProjectBloc extends Bloc { productVariantRemoteRepository; final LocalRepository productVariantLocalRepository; + final DashboardRemoteRepository dashboardRemoteRepository; BuildContext context; ProjectBloc({ @@ -126,6 +129,7 @@ class ProjectBloc extends Bloc { required this.individualRemoteRepository, required this.attendanceLogLocalRepository, required this.attendanceLogRemoteRepository, + required this.dashboardRemoteRepository, required this.context, }) : localSecureStore = localSecureStore ?? LocalSecureStore.instance, super(const ProjectState()) { @@ -217,39 +221,41 @@ class ProjectBloc extends Bloc { userUuid: [projectStaff.userId.toString()], ), ); - final attendanceRegisters = await attendanceRemoteRepository.search( - AttendanceRegisterSearchModel( - staffId: individual.first.id, - referenceId: projectStaff.projectId, - ), - ); - await attendanceLocalRepository.bulkCreate(attendanceRegisters); - - for (final register in attendanceRegisters) { - if (register.attendees != null && - (register.attendees ?? []).isNotEmpty) { - try { - final individuals = await individualRemoteRepository.search( - IndividualSearchModel( - id: register.attendees! - .map((e) => e.individualId!) - .toList(), - ), - ); - await individualLocalRepository.bulkCreate(individuals); - final logs = await attendanceLogRemoteRepository.search( - AttendanceLogSearchModel( - registerId: register.id, - ), - ); - await attendanceLogLocalRepository.bulkCreate(logs); - } catch (_) { - emit(state.copyWith( - loading: false, - syncError: ProjectSyncErrorType.project, - )); - - return; + if (individual.isNotEmpty) { + final attendanceRegisters = await attendanceRemoteRepository.search( + AttendanceRegisterSearchModel( + staffId: individual.first.id, + referenceId: projectStaff.projectId, + ), + ); + await attendanceLocalRepository.bulkCreate(attendanceRegisters); + + for (final register in attendanceRegisters) { + if (register.attendees != null && + (register.attendees ?? []).isNotEmpty) { + try { + final individuals = await individualRemoteRepository.search( + IndividualSearchModel( + id: register.attendees! + .map((e) => e.individualId!) + .toList(), + ), + ); + await individualLocalRepository.bulkCreate(individuals); + final logs = await attendanceLogRemoteRepository.search( + AttendanceLogSearchModel( + registerId: register.id, + ), + ); + await attendanceLogLocalRepository.bulkCreate(logs); + } catch (_) { + emit(state.copyWith( + loading: false, + syncError: ProjectSyncErrorType.project, + )); + + return; + } } } } @@ -364,9 +370,7 @@ class ProjectBloc extends Bloc { await projectFacilityLocalRepository.bulkCreate(projectFacilities); final facilities = await facilityRemoteRepository.search( - FacilitySearchModel( - id: null, - ), + FacilitySearchModel(tenantId: envConfig.variables.tenantId), ); await facilityLocalRepository.bulkCreate(facilities); @@ -436,6 +440,69 @@ class ProjectBloc extends Bloc { List boundaries; try { + try { + final startDate = DateTime( + DateTime.now().year, DateTime.now().month, DateTime.now().day) + .toLocal() + .millisecondsSinceEpoch; + final endDate = DateTime(DateTime.now().year, DateTime.now().month, + DateTime.now().day, 23, 59) + .toLocal() + .millisecondsSinceEpoch; + final serviceRegistry = await isar.serviceRegistrys.where().findAll(); + final dashboardConfig = await isar.dashboardConfigSchemas + .where() + .filter() + .chartsIsNotNull() + .chartsIsNotEmpty() + .findAll(); + final dashboardActionPath = Constants.getEndPoint( + serviceRegistry: serviceRegistry, + service: DashboardResponseModel.schemaName.toUpperCase(), + action: ApiOperation.search.toValue(), + entityName: DashboardResponseModel.schemaName); + if (dashboardConfig.isNotEmpty && + dashboardConfig.first.enableDashboard == true && + dashboardConfig.first.charts != null) { + final loggedInIndividualId = await localSecureStore.userIndividualId; + final registers = await attendanceLocalRepository.search( + AttendanceRegisterSearchModel( + staffId: loggedInIndividualId, + referenceId: event.model.id, + ), + ); + List attendeesIndividualIds = []; + registers.forEach((r) { + r.attendees?.where((a) => a.individualId != null).forEach((att) { + attendeesIndividualIds.add(att.individualId.toString()); + }); + }); + final individuals = + await individualLocalRepository.search(IndividualSearchModel( + id: attendeesIndividualIds, + )); + final userUUIDList = individuals + .where((ind) => ind.userUuid != null) + .map((i) => i.userUuid.toString()) + .toList(); + await processDashboardConfig( + dashboardConfig.first.charts ?? [], + startDate, + endDate, + isar, + DateTime.now(), + dashboardRemoteRepository, + dashboardActionPath.trim().isNotEmpty + ? dashboardActionPath + : '/dashboard-analytics/dashboard/getChartV2', //[TODO: To be added to MDMS Service registry + envConfig.variables.tenantId, + event.model.id, + userUUIDList, + ); + } + } catch (e) { + debugPrint(e.toString()); + } final configResult = await mdmsRepository.searchAppConfig( envConfig.variables.mdmsApiPath, MdmsRequestModel( @@ -488,10 +555,10 @@ class ProjectBloc extends Bloc { rowVersion.version = element.version; rowVersionList.add(rowVersion); } - await isar.writeTxn(() async { - await isar.rowVersionLists.clear(); + isar.writeTxnSync(() { + isar.rowVersionLists.clear(); - await isar.rowVersionLists.putAll(rowVersionList); + isar.rowVersionLists.putAllSync(rowVersionList); }); } else { boundaries = await boundaryLocalRepository.search( diff --git a/apps/health_campaign_field_worker_app/lib/blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart b/apps/health_campaign_field_worker_app/lib/blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart index 757804b09..a443250b1 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart @@ -140,6 +140,7 @@ class BeneficiaryDownSyncBloc event.batchSize, )); } else { + await LocalSecureStore.instance.setManualSyncTrigger(false); emit(const BeneficiaryDownSyncState.resetState()); emit(const BeneficiaryDownSyncState.totalCountCheckFailed()); } diff --git a/apps/health_campaign_field_worker_app/lib/blocs/sync/sync.dart b/apps/health_campaign_field_worker_app/lib/blocs/sync/sync.dart index fccc5cf44..ea6826cbe 100644 --- a/apps/health_campaign_field_worker_app/lib/blocs/sync/sync.dart +++ b/apps/health_campaign_field_worker_app/lib/blocs/sync/sync.dart @@ -38,17 +38,17 @@ class SyncBloc extends Bloc { int? length = event.count; emit(const SyncState.loading()); try { - length ??= getSyncCount(await isar.opLogs + length ??= getSyncCount(isar.opLogs .filter() .createdByEqualTo(event.createdBy) .syncedUpEqualTo(false) - .findAll()) + - getSyncCount(await isar.opLogs + .findAllSync()) + + getSyncCount(isar.opLogs .filter() .createdByEqualTo(event.createdBy) .syncedUpEqualTo(true) .syncedDownEqualTo(false) - .findAll()); + .findAllSync()); } catch (_) { rethrow; } finally { diff --git a/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.dart b/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.dart index bd697b538..ff59f2077 100644 --- a/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.dart +++ b/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.dart @@ -1,5 +1,8 @@ +import 'package:digit_dss/digit_dss.dart'; import 'package:isar/isar.dart'; +import '../../../../models/privacy_notice/privacy_notice_model.dart'; + part 'app_configuration.g.dart'; @Collection() @@ -72,7 +75,13 @@ class AppConfiguration { late List? symptomsTypes; + @Name('SEARCH_HOUSEHOLD_FILTERS') + late List? searchHouseHoldFilters; + late List? referralReasons; + late List? houseStructureTypes; + late List? refusalReasons; + late PrivacyPolicy? privacyPolicyConfig; } @embedded @@ -163,6 +172,13 @@ class HouseholdDeletionReasonOptions { late String code; } +@embedded +class SearchHouseHoldFilters { + late String name; + late String code; + late bool active; +} + @embedded class HouseholdMemberDeletionReasonOptions { late String name; @@ -197,3 +213,48 @@ class ReferralReasons { late String name; late bool active; } + +@embedded +class HouseStructureTypes { + late String code; + late String name; + late bool active; +} + +@embedded +class RefusalReasons { + late String code; + late String name; + late bool active; +} + +@embedded +class PrivacyPolicy { + late String header; + late String module; + late bool? active; + late List? contents; +} + +@embedded +class Content { + late String? header; + late List? descriptions; +} + +@embedded +class Description { + late String? text; + late String? type; + late bool? isBold; + late List? subDescriptions; +} + +@embedded +class SubDescription { + late String? text; + late String? type; + late bool? isBold; + late bool? isSpaceRequired; +} + diff --git a/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.g.dart b/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.g.dart index bb695f257..d2e76c13c 100644 --- a/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.g.dart +++ b/apps/health_campaign_field_worker_app/lib/data/local_store/no_sql/schema/app_configuration.g.dart @@ -116,35 +116,59 @@ const AppConfigurationSchema = CollectionSchema( name: r'PROXIMITY_SEARCH_RANGE', type: IsarType.double, ), - r'SYNC_METHOD': PropertySchema( + r'SEARCH_HOUSEHOLD_FILTERS': PropertySchema( id: 17, + name: r'SEARCH_HOUSEHOLD_FILTERS', + type: IsarType.objectList, + target: r'SearchHouseHoldFilters', + ), + r'SYNC_METHOD': PropertySchema( + id: 18, name: r'SYNC_METHOD', type: IsarType.string, ), r'SYNC_TRIGGER': PropertySchema( - id: 18, + id: 19, name: r'SYNC_TRIGGER', type: IsarType.string, ), r'TENANT_ID': PropertySchema( - id: 19, + id: 20, name: r'TENANT_ID', type: IsarType.string, ), r'TRANSPORT_TYPES': PropertySchema( - id: 20, + id: 21, name: r'TRANSPORT_TYPES', type: IsarType.objectList, target: r'TransportTypes', ), + r'houseStructureTypes': PropertySchema( + id: 22, + name: r'houseStructureTypes', + type: IsarType.objectList, + target: r'HouseStructureTypes', + ), + r'privacyPolicyConfig': PropertySchema( + id: 23, + name: r'privacyPolicyConfig', + type: IsarType.object, + target: r'PrivacyPolicy', + ), r'referralReasons': PropertySchema( - id: 21, + id: 24, name: r'referralReasons', type: IsarType.objectList, target: r'ReferralReasons', ), + r'refusalReasons': PropertySchema( + id: 25, + name: r'refusalReasons', + type: IsarType.objectList, + target: r'RefusalReasons', + ), r'symptomsTypes': PropertySchema( - id: 22, + id: 26, name: r'symptomsTypes', type: IsarType.objectList, target: r'SymptomsTypes', @@ -176,7 +200,14 @@ const AppConfigurationSchema = CollectionSchema( r'CallSupportList': CallSupportListSchema, r'FirebaseConfig': FirebaseConfigSchema, r'SymptomsTypes': SymptomsTypesSchema, - r'ReferralReasons': ReferralReasonsSchema + r'SearchHouseHoldFilters': SearchHouseHoldFiltersSchema, + r'ReferralReasons': ReferralReasonsSchema, + r'HouseStructureTypes': HouseStructureTypesSchema, + r'RefusalReasons': RefusalReasonsSchema, + r'PrivacyPolicy': PrivacyPolicySchema, + r'Content': ContentSchema, + r'Description': DescriptionSchema, + r'SubDescription': SubDescriptionSchema }, getId: _appConfigurationGetId, getLinks: _appConfigurationGetLinks, @@ -380,6 +411,20 @@ int _appConfigurationEstimateSize( bytesCount += 3 + value.length * 3; } } + { + final list = object.searchHouseHoldFilters; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[SearchHouseHoldFilters]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += SearchHouseHoldFiltersSchema.estimateSize( + value, offsets, allOffsets); + } + } + } + } { final value = object.syncMethod; if (value != null) { @@ -412,6 +457,28 @@ int _appConfigurationEstimateSize( } } } + { + final list = object.houseStructureTypes; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[HouseStructureTypes]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += HouseStructureTypesSchema.estimateSize( + value, offsets, allOffsets); + } + } + } + } + { + final value = object.privacyPolicyConfig; + if (value != null) { + bytesCount += 3 + + PrivacyPolicySchema.estimateSize( + value, allOffsets[PrivacyPolicy]!, allOffsets); + } + } { final list = object.referralReasons; if (list != null) { @@ -426,6 +493,20 @@ int _appConfigurationEstimateSize( } } } + { + final list = object.refusalReasons; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[RefusalReasons]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += + RefusalReasonsSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } { final list = object.symptomsTypes; if (list != null) { @@ -536,23 +617,47 @@ void _appConfigurationSerialize( writer.writeString(offsets[14], object.networkDetection); writer.writeString(offsets[15], object.persistenceMode); writer.writeDouble(offsets[16], object.maxRadius); - writer.writeString(offsets[17], object.syncMethod); - writer.writeString(offsets[18], object.syncTrigger); - writer.writeString(offsets[19], object.tenantId); + writer.writeObjectList( + offsets[17], + allOffsets, + SearchHouseHoldFiltersSchema.serialize, + object.searchHouseHoldFilters, + ); + writer.writeString(offsets[18], object.syncMethod); + writer.writeString(offsets[19], object.syncTrigger); + writer.writeString(offsets[20], object.tenantId); writer.writeObjectList( - offsets[20], + offsets[21], allOffsets, TransportTypesSchema.serialize, object.transportTypes, ); + writer.writeObjectList( + offsets[22], + allOffsets, + HouseStructureTypesSchema.serialize, + object.houseStructureTypes, + ); + writer.writeObject( + offsets[23], + allOffsets, + PrivacyPolicySchema.serialize, + object.privacyPolicyConfig, + ); writer.writeObjectList( - offsets[21], + offsets[24], allOffsets, ReferralReasonsSchema.serialize, object.referralReasons, ); + writer.writeObjectList( + offsets[25], + allOffsets, + RefusalReasonsSchema.serialize, + object.refusalReasons, + ); writer.writeObjectList( - offsets[22], + offsets[26], allOffsets, SymptomsTypesSchema.serialize, object.symptomsTypes, @@ -653,24 +758,47 @@ AppConfiguration _appConfigurationDeserialize( object.networkDetection = reader.readStringOrNull(offsets[14]); object.persistenceMode = reader.readStringOrNull(offsets[15]); object.maxRadius = reader.readDoubleOrNull(offsets[16]); - object.syncMethod = reader.readStringOrNull(offsets[17]); - object.syncTrigger = reader.readStringOrNull(offsets[18]); - object.tenantId = reader.readStringOrNull(offsets[19]); + object.searchHouseHoldFilters = reader.readObjectList( + offsets[17], + SearchHouseHoldFiltersSchema.deserialize, + allOffsets, + SearchHouseHoldFilters(), + ); + object.syncMethod = reader.readStringOrNull(offsets[18]); + object.syncTrigger = reader.readStringOrNull(offsets[19]); + object.tenantId = reader.readStringOrNull(offsets[20]); object.transportTypes = reader.readObjectList( - offsets[20], + offsets[21], TransportTypesSchema.deserialize, allOffsets, TransportTypes(), ); + object.houseStructureTypes = reader.readObjectList( + offsets[22], + HouseStructureTypesSchema.deserialize, + allOffsets, + HouseStructureTypes(), + ); object.id = id; + object.privacyPolicyConfig = reader.readObjectOrNull( + offsets[23], + PrivacyPolicySchema.deserialize, + allOffsets, + ); object.referralReasons = reader.readObjectList( - offsets[21], + offsets[24], ReferralReasonsSchema.deserialize, allOffsets, ReferralReasons(), ); + object.refusalReasons = reader.readObjectList( + offsets[25], + RefusalReasonsSchema.deserialize, + allOffsets, + RefusalReasons(), + ); object.symptomsTypes = reader.readObjectList( - offsets[22], + offsets[26], SymptomsTypesSchema.deserialize, allOffsets, SymptomsTypes(), @@ -787,26 +915,53 @@ P _appConfigurationDeserializeProp

( case 16: return (reader.readDoubleOrNull(offset)) as P; case 17: - return (reader.readStringOrNull(offset)) as P; + return (reader.readObjectList( + offset, + SearchHouseHoldFiltersSchema.deserialize, + allOffsets, + SearchHouseHoldFilters(), + )) as P; case 18: return (reader.readStringOrNull(offset)) as P; case 19: return (reader.readStringOrNull(offset)) as P; case 20: + return (reader.readStringOrNull(offset)) as P; + case 21: return (reader.readObjectList( offset, TransportTypesSchema.deserialize, allOffsets, TransportTypes(), )) as P; - case 21: + case 22: + return (reader.readObjectList( + offset, + HouseStructureTypesSchema.deserialize, + allOffsets, + HouseStructureTypes(), + )) as P; + case 23: + return (reader.readObjectOrNull( + offset, + PrivacyPolicySchema.deserialize, + allOffsets, + )) as P; + case 24: return (reader.readObjectList( offset, ReferralReasonsSchema.deserialize, allOffsets, ReferralReasons(), )) as P; - case 22: + case 25: + return (reader.readObjectList( + offset, + RefusalReasonsSchema.deserialize, + allOffsets, + RefusalReasons(), + )) as P; + case 26: return (reader.readObjectList( offset, SymptomsTypesSchema.deserialize, @@ -2535,6 +2690,113 @@ extension AppConfigurationQueryFilter }); } + QueryBuilder + searchHouseHoldFiltersIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'SEARCH_HOUSEHOLD_FILTERS', + )); + }); + } + + QueryBuilder + searchHouseHoldFiltersIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'SEARCH_HOUSEHOLD_FILTERS', + )); + }); + } + + QueryBuilder + searchHouseHoldFiltersLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder + searchHouseHoldFiltersIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + searchHouseHoldFiltersIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + searchHouseHoldFiltersLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + searchHouseHoldFiltersLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + searchHouseHoldFiltersLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'SEARCH_HOUSEHOLD_FILTERS', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + QueryBuilder syncMethodIsNull() { return QueryBuilder.apply(this, (query) { @@ -3105,84 +3367,28 @@ extension AppConfigurationQueryFilter } QueryBuilder - idEqualTo(Id value) { - return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(FilterCondition.equalTo( - property: r'id', - value: value, - )); - }); - } - - QueryBuilder - idGreaterThan( - Id value, { - bool include = false, - }) { - return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(FilterCondition.greaterThan( - include: include, - property: r'id', - value: value, - )); - }); - } - - QueryBuilder - idLessThan( - Id value, { - bool include = false, - }) { - return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(FilterCondition.lessThan( - include: include, - property: r'id', - value: value, - )); - }); - } - - QueryBuilder - idBetween( - Id lower, - Id upper, { - bool includeLower = true, - bool includeUpper = true, - }) { - return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(FilterCondition.between( - property: r'id', - lower: lower, - includeLower: includeLower, - upper: upper, - includeUpper: includeUpper, - )); - }); - } - - QueryBuilder - referralReasonsIsNull() { + houseStructureTypesIsNull() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(const FilterCondition.isNull( - property: r'referralReasons', + property: r'houseStructureTypes', )); }); } QueryBuilder - referralReasonsIsNotNull() { + houseStructureTypesIsNotNull() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(const FilterCondition.isNotNull( - property: r'referralReasons', + property: r'houseStructureTypes', )); }); } QueryBuilder - referralReasonsLengthEqualTo(int length) { + houseStructureTypesLengthEqualTo(int length) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', length, true, length, @@ -3192,10 +3398,10 @@ extension AppConfigurationQueryFilter } QueryBuilder - referralReasonsIsEmpty() { + houseStructureTypesIsEmpty() { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', 0, true, 0, @@ -3205,10 +3411,10 @@ extension AppConfigurationQueryFilter } QueryBuilder - referralReasonsIsNotEmpty() { + houseStructureTypesIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', 0, false, 999999, @@ -3218,13 +3424,13 @@ extension AppConfigurationQueryFilter } QueryBuilder - referralReasonsLengthLessThan( + houseStructureTypesLengthLessThan( int length, { bool include = false, }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', 0, true, length, @@ -3234,13 +3440,13 @@ extension AppConfigurationQueryFilter } QueryBuilder - referralReasonsLengthGreaterThan( + houseStructureTypesLengthGreaterThan( int length, { bool include = false, }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', length, include, 999999, @@ -3250,7 +3456,7 @@ extension AppConfigurationQueryFilter } QueryBuilder - referralReasonsLengthBetween( + houseStructureTypesLengthBetween( int lower, int upper, { bool includeLower = true, @@ -3258,7 +3464,7 @@ extension AppConfigurationQueryFilter }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'referralReasons', + r'houseStructureTypes', lower, includeLower, upper, @@ -3268,28 +3474,102 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesIsNull() { + idEqualTo(Id value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idGreaterThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idLessThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idBetween( + Id lower, + Id upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'id', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + )); + }); + } + + QueryBuilder + privacyPolicyConfigIsNull() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(const FilterCondition.isNull( - property: r'symptomsTypes', + property: r'privacyPolicyConfig', )); }); } QueryBuilder - symptomsTypesIsNotNull() { + privacyPolicyConfigIsNotNull() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(const FilterCondition.isNotNull( - property: r'symptomsTypes', + property: r'privacyPolicyConfig', )); }); } QueryBuilder - symptomsTypesLengthEqualTo(int length) { + referralReasonsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'referralReasons', + )); + }); + } + + QueryBuilder + referralReasonsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'referralReasons', + )); + }); + } + + QueryBuilder + referralReasonsLengthEqualTo(int length) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', length, true, length, @@ -3299,10 +3579,10 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesIsEmpty() { + referralReasonsIsEmpty() { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', 0, true, 0, @@ -3312,10 +3592,10 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesIsNotEmpty() { + referralReasonsIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', 0, false, 999999, @@ -3325,13 +3605,13 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesLengthLessThan( + referralReasonsLengthLessThan( int length, { bool include = false, }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', 0, true, length, @@ -3341,13 +3621,13 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesLengthGreaterThan( + referralReasonsLengthGreaterThan( int length, { bool include = false, }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', length, include, 999999, @@ -3357,7 +3637,7 @@ extension AppConfigurationQueryFilter } QueryBuilder - symptomsTypesLengthBetween( + referralReasonsLengthBetween( int lower, int upper, { bool includeLower = true, @@ -3365,7 +3645,7 @@ extension AppConfigurationQueryFilter }) { return QueryBuilder.apply(this, (query) { return query.listLength( - r'symptomsTypes', + r'referralReasons', lower, includeLower, upper, @@ -3373,124 +3653,366 @@ extension AppConfigurationQueryFilter ); }); } -} -extension AppConfigurationQueryObject - on QueryBuilder { QueryBuilder - backendInterface(FilterQuery q) { + refusalReasonsIsNull() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'BACKEND_INTERFACE'); + return query.addFilterCondition(const FilterCondition.isNull( + property: r'refusalReasons', + )); }); } QueryBuilder - backgroundServiceConfig(FilterQuery q) { + refusalReasonsIsNotNull() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'BACKGROUND_SERVICE_CONFIG'); + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'refusalReasons', + )); }); } QueryBuilder - bandwidthBatchSizeElement(FilterQuery q) { + refusalReasonsLengthEqualTo(int length) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'BANDWIDTH_BATCH_SIZE'); + return query.listLength( + r'refusalReasons', + length, + true, + length, + true, + ); }); } QueryBuilder - callSupportOptionsElement(FilterQuery q) { + refusalReasonsIsEmpty() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'CALL_SUPPORT'); + return query.listLength( + r'refusalReasons', + 0, + true, + 0, + true, + ); }); } QueryBuilder - checklistTypesElement(FilterQuery q) { + refusalReasonsIsNotEmpty() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'CHECKLIST_TYPES'); + return query.listLength( + r'refusalReasons', + 0, + false, + 999999, + true, + ); }); } QueryBuilder - complaintTypesElement(FilterQuery q) { + refusalReasonsLengthLessThan( + int length, { + bool include = false, + }) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'COMPLAINT_TYPES'); + return query.listLength( + r'refusalReasons', + 0, + true, + length, + include, + ); }); } QueryBuilder - deliveryCommentOptionsElement(FilterQuery q) { + refusalReasonsLengthGreaterThan( + int length, { + bool include = false, + }) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'DELIVERY_COMMENT_OPTIONS_POPULATOR'); + return query.listLength( + r'refusalReasons', + length, + include, + 999999, + true, + ); }); } QueryBuilder - downSyncBandwidthBatchSizeElement(FilterQuery q) { + refusalReasonsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'DOWNSYNC-BANDWIDTH_BATCH_SIZE'); + return query.listLength( + r'refusalReasons', + lower, + includeLower, + upper, + includeUpper, + ); }); } QueryBuilder - firebaseConfig(FilterQuery q) { + symptomsTypesIsNull() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'FIREBASE_CONFIG'); + return query.addFilterCondition(const FilterCondition.isNull( + property: r'symptomsTypes', + )); }); } QueryBuilder - genderOptionsElement(FilterQuery q) { + symptomsTypesIsNotNull() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'GENDER_OPTIONS_POPULATOR'); + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'symptomsTypes', + )); }); } QueryBuilder - householdDeletionReasonOptionsElement( - FilterQuery q) { + symptomsTypesLengthEqualTo(int length) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'HOUSEHOLD_DELETION_REASON_OPTIONS'); + return query.listLength( + r'symptomsTypes', + length, + true, + length, + true, + ); }); } QueryBuilder - householdMemberDeletionReasonOptionsElement( - FilterQuery q) { + symptomsTypesIsEmpty() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'HOUSEHOLD_MEMBER_DELETION_REASON_OPTIONS'); + return query.listLength( + r'symptomsTypes', + 0, + true, + 0, + true, + ); }); } QueryBuilder - idTypeOptionsElement(FilterQuery q) { + symptomsTypesIsNotEmpty() { return QueryBuilder.apply(this, (query) { - return query.object(q, r'ID_TYPE_OPTIONS_POPULATOR'); + return query.listLength( + r'symptomsTypes', + 0, + false, + 999999, + true, + ); }); } QueryBuilder - languagesElement(FilterQuery q) { + symptomsTypesLengthLessThan( + int length, { + bool include = false, + }) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'LANGUAGES'); + return query.listLength( + r'symptomsTypes', + 0, + true, + length, + include, + ); }); } QueryBuilder - transportTypesElement(FilterQuery q) { + symptomsTypesLengthGreaterThan( + int length, { + bool include = false, + }) { return QueryBuilder.apply(this, (query) { - return query.object(q, r'TRANSPORT_TYPES'); + return query.listLength( + r'symptomsTypes', + length, + include, + 999999, + true, + ); }); } QueryBuilder - referralReasonsElement(FilterQuery q) { + symptomsTypesLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'symptomsTypes', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } +} + +extension AppConfigurationQueryObject + on QueryBuilder { + QueryBuilder + backendInterface(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'BACKEND_INTERFACE'); + }); + } + + QueryBuilder + backgroundServiceConfig(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'BACKGROUND_SERVICE_CONFIG'); + }); + } + + QueryBuilder + bandwidthBatchSizeElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'BANDWIDTH_BATCH_SIZE'); + }); + } + + QueryBuilder + callSupportOptionsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'CALL_SUPPORT'); + }); + } + + QueryBuilder + checklistTypesElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'CHECKLIST_TYPES'); + }); + } + + QueryBuilder + complaintTypesElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'COMPLAINT_TYPES'); + }); + } + + QueryBuilder + deliveryCommentOptionsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'DELIVERY_COMMENT_OPTIONS_POPULATOR'); + }); + } + + QueryBuilder + downSyncBandwidthBatchSizeElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'DOWNSYNC-BANDWIDTH_BATCH_SIZE'); + }); + } + + QueryBuilder + firebaseConfig(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'FIREBASE_CONFIG'); + }); + } + + QueryBuilder + genderOptionsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'GENDER_OPTIONS_POPULATOR'); + }); + } + + QueryBuilder + householdDeletionReasonOptionsElement( + FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'HOUSEHOLD_DELETION_REASON_OPTIONS'); + }); + } + + QueryBuilder + householdMemberDeletionReasonOptionsElement( + FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'HOUSEHOLD_MEMBER_DELETION_REASON_OPTIONS'); + }); + } + + QueryBuilder + idTypeOptionsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'ID_TYPE_OPTIONS_POPULATOR'); + }); + } + + QueryBuilder + languagesElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'LANGUAGES'); + }); + } + + QueryBuilder + searchHouseHoldFiltersElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'SEARCH_HOUSEHOLD_FILTERS'); + }); + } + + QueryBuilder + transportTypesElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'TRANSPORT_TYPES'); + }); + } + + QueryBuilder + houseStructureTypesElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'houseStructureTypes'); + }); + } + + QueryBuilder + privacyPolicyConfig(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'privacyPolicyConfig'); + }); + } + + QueryBuilder + referralReasonsElement(FilterQuery q) { return QueryBuilder.apply(this, (query) { return query.object(q, r'referralReasons'); }); } + QueryBuilder + refusalReasonsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'refusalReasons'); + }); + } + QueryBuilder symptomsTypesElement(FilterQuery q) { return QueryBuilder.apply(this, (query) { @@ -3863,6 +4385,13 @@ extension AppConfigurationQueryProperty }); } + QueryBuilder?, + QQueryOperations> searchHouseHoldFiltersProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'SEARCH_HOUSEHOLD_FILTERS'); + }); + } + QueryBuilder syncMethodProperty() { return QueryBuilder.apply(this, (query) { @@ -3890,6 +4419,20 @@ extension AppConfigurationQueryProperty }); } + QueryBuilder?, QQueryOperations> + houseStructureTypesProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'houseStructureTypes'); + }); + } + + QueryBuilder + privacyPolicyConfigProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'privacyPolicyConfig'); + }); + } + QueryBuilder?, QQueryOperations> referralReasonsProperty() { return QueryBuilder.apply(this, (query) { @@ -3897,6 +4440,13 @@ extension AppConfigurationQueryProperty }); } + QueryBuilder?, QQueryOperations> + refusalReasonsProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'refusalReasons'); + }); + } + QueryBuilder?, QQueryOperations> symptomsTypesProperty() { return QueryBuilder.apply(this, (query) { @@ -7980,29 +8530,34 @@ extension HouseholdDeletionReasonOptionsQueryObject on QueryBuilder< // coverage:ignore-file // ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types -const HouseholdMemberDeletionReasonOptionsSchema = Schema( - name: r'HouseholdMemberDeletionReasonOptions', - id: 752674668946516871, +const SearchHouseHoldFiltersSchema = Schema( + name: r'SearchHouseHoldFilters', + id: -6619823232754786758, properties: { - r'code': PropertySchema( + r'active': PropertySchema( id: 0, + name: r'active', + type: IsarType.bool, + ), + r'code': PropertySchema( + id: 1, name: r'code', type: IsarType.string, ), r'name': PropertySchema( - id: 1, + id: 2, name: r'name', type: IsarType.string, ) }, - estimateSize: _householdMemberDeletionReasonOptionsEstimateSize, - serialize: _householdMemberDeletionReasonOptionsSerialize, - deserialize: _householdMemberDeletionReasonOptionsDeserialize, - deserializeProp: _householdMemberDeletionReasonOptionsDeserializeProp, + estimateSize: _searchHouseHoldFiltersEstimateSize, + serialize: _searchHouseHoldFiltersSerialize, + deserialize: _searchHouseHoldFiltersDeserialize, + deserializeProp: _searchHouseHoldFiltersDeserializeProp, ); -int _householdMemberDeletionReasonOptionsEstimateSize( - HouseholdMemberDeletionReasonOptions object, +int _searchHouseHoldFiltersEstimateSize( + SearchHouseHoldFilters object, List offsets, Map> allOffsets, ) { @@ -8012,30 +8567,31 @@ int _householdMemberDeletionReasonOptionsEstimateSize( return bytesCount; } -void _householdMemberDeletionReasonOptionsSerialize( - HouseholdMemberDeletionReasonOptions object, +void _searchHouseHoldFiltersSerialize( + SearchHouseHoldFilters object, IsarWriter writer, List offsets, Map> allOffsets, ) { - writer.writeString(offsets[0], object.code); - writer.writeString(offsets[1], object.name); + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.code); + writer.writeString(offsets[2], object.name); } -HouseholdMemberDeletionReasonOptions - _householdMemberDeletionReasonOptionsDeserialize( +SearchHouseHoldFilters _searchHouseHoldFiltersDeserialize( Id id, IsarReader reader, List offsets, Map> allOffsets, ) { - final object = HouseholdMemberDeletionReasonOptions(); - object.code = reader.readString(offsets[0]); - object.name = reader.readString(offsets[1]); + final object = SearchHouseHoldFilters(); + object.active = reader.readBool(offsets[0]); + object.code = reader.readString(offsets[1]); + object.name = reader.readString(offsets[2]); return object; } -P _householdMemberDeletionReasonOptionsDeserializeProp

( +P _searchHouseHoldFiltersDeserializeProp

( IsarReader reader, int propertyId, int offset, @@ -8043,20 +8599,30 @@ P _householdMemberDeletionReasonOptionsDeserializeProp

( ) { switch (propertyId) { case 0: - return (reader.readString(offset)) as P; + return (reader.readBool(offset)) as P; case 1: return (reader.readString(offset)) as P; + case 2: + return (reader.readString(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } } -extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, - QFilterCondition> { - QueryBuilder codeEqualTo( +extension SearchHouseHoldFiltersQueryFilter on QueryBuilder< + SearchHouseHoldFilters, SearchHouseHoldFilters, QFilterCondition> { + QueryBuilder activeEqualTo(bool value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder codeEqualTo( String value, { bool caseSensitive = true, }) { @@ -8069,9 +8635,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder codeGreaterThan( String value, { bool include = false, @@ -8087,8 +8651,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder codeLessThan( + QueryBuilder codeLessThan( String value, { bool include = false, bool caseSensitive = true, @@ -8103,8 +8667,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder codeBetween( + QueryBuilder codeBetween( String lower, String upper, { bool includeLower = true, @@ -8123,9 +8687,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder codeStartsWith( String value, { bool caseSensitive = true, @@ -8139,8 +8701,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder codeEndsWith( + QueryBuilder codeEndsWith( String value, { bool caseSensitive = true, }) { @@ -8153,8 +8715,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder + QueryBuilder codeContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( @@ -8165,8 +8727,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder + QueryBuilder codeMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( @@ -8177,9 +8739,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder codeIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( @@ -8189,9 +8749,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder codeIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( @@ -8201,8 +8759,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder nameEqualTo( + QueryBuilder nameEqualTo( String value, { bool caseSensitive = true, }) { @@ -8215,9 +8773,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder nameGreaterThan( String value, { bool include = false, @@ -8233,8 +8789,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder nameLessThan( + QueryBuilder nameLessThan( String value, { bool include = false, bool caseSensitive = true, @@ -8249,8 +8805,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder nameBetween( + QueryBuilder nameBetween( String lower, String upper, { bool includeLower = true, @@ -8269,9 +8825,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder nameStartsWith( String value, { bool caseSensitive = true, @@ -8285,8 +8839,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder nameEndsWith( + QueryBuilder nameEndsWith( String value, { bool caseSensitive = true, }) { @@ -8299,8 +8853,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder + QueryBuilder nameContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( @@ -8311,8 +8865,8 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder + QueryBuilder nameMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( @@ -8323,9 +8877,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder nameIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( @@ -8335,9 +8887,7 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< }); } - QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, + QueryBuilder nameIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( @@ -8348,17 +8898,15 @@ extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< } } -extension HouseholdMemberDeletionReasonOptionsQueryObject on QueryBuilder< - HouseholdMemberDeletionReasonOptions, - HouseholdMemberDeletionReasonOptions, - QFilterCondition> {} +extension SearchHouseHoldFiltersQueryObject on QueryBuilder< + SearchHouseHoldFilters, SearchHouseHoldFilters, QFilterCondition> {} // coverage:ignore-file // ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types -const CallSupportListSchema = Schema( - name: r'CallSupportList', - id: 5777143171447971980, +const HouseholdMemberDeletionReasonOptionsSchema = Schema( + name: r'HouseholdMemberDeletionReasonOptions', + id: 752674668946516871, properties: { r'code': PropertySchema( id: 0, @@ -8371,14 +8919,14 @@ const CallSupportListSchema = Schema( type: IsarType.string, ) }, - estimateSize: _callSupportListEstimateSize, - serialize: _callSupportListSerialize, - deserialize: _callSupportListDeserialize, - deserializeProp: _callSupportListDeserializeProp, + estimateSize: _householdMemberDeletionReasonOptionsEstimateSize, + serialize: _householdMemberDeletionReasonOptionsSerialize, + deserialize: _householdMemberDeletionReasonOptionsDeserialize, + deserializeProp: _householdMemberDeletionReasonOptionsDeserializeProp, ); -int _callSupportListEstimateSize( - CallSupportList object, +int _householdMemberDeletionReasonOptionsEstimateSize( + HouseholdMemberDeletionReasonOptions object, List offsets, Map> allOffsets, ) { @@ -8388,8 +8936,8 @@ int _callSupportListEstimateSize( return bytesCount; } -void _callSupportListSerialize( - CallSupportList object, +void _householdMemberDeletionReasonOptionsSerialize( + HouseholdMemberDeletionReasonOptions object, IsarWriter writer, List offsets, Map> allOffsets, @@ -8398,19 +8946,20 @@ void _callSupportListSerialize( writer.writeString(offsets[1], object.name); } -CallSupportList _callSupportListDeserialize( +HouseholdMemberDeletionReasonOptions + _householdMemberDeletionReasonOptionsDeserialize( Id id, IsarReader reader, List offsets, Map> allOffsets, ) { - final object = CallSupportList(); + final object = HouseholdMemberDeletionReasonOptions(); object.code = reader.readString(offsets[0]); object.name = reader.readString(offsets[1]); return object; } -P _callSupportListDeserializeProp

( +P _householdMemberDeletionReasonOptionsDeserializeProp

( IsarReader reader, int propertyId, int offset, @@ -8426,10 +8975,12 @@ P _callSupportListDeserializeProp

( } } -extension CallSupportListQueryFilter - on QueryBuilder { - QueryBuilder - codeEqualTo( +extension HouseholdMemberDeletionReasonOptionsQueryFilter on QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QFilterCondition> { + QueryBuilder codeEqualTo( String value, { bool caseSensitive = true, }) { @@ -8442,8 +8993,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeGreaterThan( + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> codeGreaterThan( String value, { bool include = false, bool caseSensitive = true, @@ -8458,8 +9011,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeLessThan( + QueryBuilder codeLessThan( String value, { bool include = false, bool caseSensitive = true, @@ -8474,8 +9027,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeBetween( + QueryBuilder codeBetween( String lower, String upper, { bool includeLower = true, @@ -8494,8 +9047,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeStartsWith( + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> codeStartsWith( String value, { bool caseSensitive = true, }) { @@ -8508,8 +9063,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeEndsWith( + QueryBuilder codeEndsWith( String value, { bool caseSensitive = true, }) { @@ -8522,7 +9077,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder + QueryBuilder codeContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( @@ -8533,7 +9089,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder + QueryBuilder codeMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( @@ -8544,8 +9101,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeIsEmpty() { + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> codeIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( property: r'code', @@ -8554,8 +9113,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - codeIsNotEmpty() { + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> codeIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( property: r'code', @@ -8564,8 +9125,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameEqualTo( + QueryBuilder nameEqualTo( String value, { bool caseSensitive = true, }) { @@ -8578,8 +9139,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameGreaterThan( + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> nameGreaterThan( String value, { bool include = false, bool caseSensitive = true, @@ -8594,8 +9157,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameLessThan( + QueryBuilder nameLessThan( String value, { bool include = false, bool caseSensitive = true, @@ -8610,8 +9173,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameBetween( + QueryBuilder nameBetween( String lower, String upper, { bool includeLower = true, @@ -8630,8 +9193,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameStartsWith( + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> nameStartsWith( String value, { bool caseSensitive = true, }) { @@ -8644,8 +9209,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameEndsWith( + QueryBuilder nameEndsWith( String value, { bool caseSensitive = true, }) { @@ -8658,7 +9223,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder + QueryBuilder nameContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( @@ -8669,7 +9235,8 @@ extension CallSupportListQueryFilter }); } - QueryBuilder + QueryBuilder nameMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( @@ -8680,8 +9247,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameIsEmpty() { + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> nameIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( property: r'name', @@ -8690,8 +9259,10 @@ extension CallSupportListQueryFilter }); } - QueryBuilder - nameIsNotEmpty() { + QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QAfterFilterCondition> nameIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( property: r'name', @@ -8701,65 +9272,69 @@ extension CallSupportListQueryFilter } } -extension CallSupportListQueryObject - on QueryBuilder {} +extension HouseholdMemberDeletionReasonOptionsQueryObject on QueryBuilder< + HouseholdMemberDeletionReasonOptions, + HouseholdMemberDeletionReasonOptions, + QFilterCondition> {} // coverage:ignore-file // ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types -const FirebaseConfigSchema = Schema( - name: r'FirebaseConfig', - id: -2852964328238474241, +const CallSupportListSchema = Schema( + name: r'CallSupportList', + id: 5777143171447971980, properties: { - r'enableAnalytics': PropertySchema( + r'code': PropertySchema( id: 0, - name: r'enableAnalytics', - type: IsarType.bool, + name: r'code', + type: IsarType.string, ), - r'enableCrashlytics': PropertySchema( + r'name': PropertySchema( id: 1, - name: r'enableCrashlytics', - type: IsarType.bool, + name: r'name', + type: IsarType.string, ) }, - estimateSize: _firebaseConfigEstimateSize, - serialize: _firebaseConfigSerialize, - deserialize: _firebaseConfigDeserialize, - deserializeProp: _firebaseConfigDeserializeProp, + estimateSize: _callSupportListEstimateSize, + serialize: _callSupportListSerialize, + deserialize: _callSupportListDeserialize, + deserializeProp: _callSupportListDeserializeProp, ); -int _firebaseConfigEstimateSize( - FirebaseConfig object, +int _callSupportListEstimateSize( + CallSupportList object, List offsets, Map> allOffsets, ) { var bytesCount = offsets.last; + bytesCount += 3 + object.code.length * 3; + bytesCount += 3 + object.name.length * 3; return bytesCount; } -void _firebaseConfigSerialize( - FirebaseConfig object, +void _callSupportListSerialize( + CallSupportList object, IsarWriter writer, List offsets, Map> allOffsets, ) { - writer.writeBool(offsets[0], object.enableAnalytics); - writer.writeBool(offsets[1], object.enableCrashlytics); + writer.writeString(offsets[0], object.code); + writer.writeString(offsets[1], object.name); } -FirebaseConfig _firebaseConfigDeserialize( +CallSupportList _callSupportListDeserialize( Id id, IsarReader reader, List offsets, Map> allOffsets, ) { - final object = FirebaseConfig(); - object.enableAnalytics = reader.readBoolOrNull(offsets[0]); - object.enableCrashlytics = reader.readBoolOrNull(offsets[1]); + final object = CallSupportList(); + object.code = reader.readString(offsets[0]); + object.name = reader.readString(offsets[1]); return object; } -P _firebaseConfigDeserializeProp

( +P _callSupportListDeserializeProp

( IsarReader reader, int propertyId, int offset, @@ -8767,141 +9342,2921 @@ P _firebaseConfigDeserializeProp

( ) { switch (propertyId) { case 0: - return (reader.readBoolOrNull(offset)) as P; + return (reader.readString(offset)) as P; case 1: - return (reader.readBoolOrNull(offset)) as P; + return (reader.readString(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } } -extension FirebaseConfigQueryFilter - on QueryBuilder { - QueryBuilder - enableAnalyticsIsNull() { +extension CallSupportListQueryFilter + on QueryBuilder { + QueryBuilder + codeEqualTo( + String value, { + bool caseSensitive = true, + }) { return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(const FilterCondition.isNull( - property: r'enableAnalytics', + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: value, + caseSensitive: caseSensitive, )); }); } - QueryBuilder - enableAnalyticsIsNotNull() { + QueryBuilder + codeGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(const FilterCondition.isNotNull( - property: r'enableAnalytics', + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, )); }); } - QueryBuilder - enableAnalyticsEqualTo(bool? value) { + QueryBuilder + codeLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(FilterCondition.equalTo( - property: r'enableAnalytics', + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'code', value: value, + caseSensitive: caseSensitive, )); }); } - QueryBuilder - enableCrashlyticsIsNull() { - return QueryBuilder.apply(this, (query) { - return query.addFilterCondition(const FilterCondition.isNull( - property: r'enableCrashlytics', - )); + QueryBuilder + codeBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'code', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'code', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + codeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + nameEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } +} + +extension CallSupportListQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const FirebaseConfigSchema = Schema( + name: r'FirebaseConfig', + id: -2852964328238474241, + properties: { + r'enableAnalytics': PropertySchema( + id: 0, + name: r'enableAnalytics', + type: IsarType.bool, + ), + r'enableCrashlytics': PropertySchema( + id: 1, + name: r'enableCrashlytics', + type: IsarType.bool, + ) + }, + estimateSize: _firebaseConfigEstimateSize, + serialize: _firebaseConfigSerialize, + deserialize: _firebaseConfigDeserialize, + deserializeProp: _firebaseConfigDeserializeProp, +); + +int _firebaseConfigEstimateSize( + FirebaseConfig object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + return bytesCount; +} + +void _firebaseConfigSerialize( + FirebaseConfig object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.enableAnalytics); + writer.writeBool(offsets[1], object.enableCrashlytics); +} + +FirebaseConfig _firebaseConfigDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = FirebaseConfig(); + object.enableAnalytics = reader.readBoolOrNull(offsets[0]); + object.enableCrashlytics = reader.readBoolOrNull(offsets[1]); + return object; +} + +P _firebaseConfigDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBoolOrNull(offset)) as P; + case 1: + return (reader.readBoolOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension FirebaseConfigQueryFilter + on QueryBuilder { + QueryBuilder + enableAnalyticsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'enableAnalytics', + )); + }); + } + + QueryBuilder + enableAnalyticsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'enableAnalytics', + )); + }); + } + + QueryBuilder + enableAnalyticsEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'enableAnalytics', + value: value, + )); + }); + } + + QueryBuilder + enableCrashlyticsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'enableCrashlytics', + )); + }); + } + + QueryBuilder + enableCrashlyticsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'enableCrashlytics', + )); + }); + } + + QueryBuilder + enableCrashlyticsEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'enableCrashlytics', + value: value, + )); + }); + } +} + +extension FirebaseConfigQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const SymptomsTypesSchema = Schema( + name: r'SymptomsTypes', + id: 1335382729654316565, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'code': PropertySchema( + id: 1, + name: r'code', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ) + }, + estimateSize: _symptomsTypesEstimateSize, + serialize: _symptomsTypesSerialize, + deserialize: _symptomsTypesDeserialize, + deserializeProp: _symptomsTypesDeserializeProp, +); + +int _symptomsTypesEstimateSize( + SymptomsTypes object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + bytesCount += 3 + object.code.length * 3; + bytesCount += 3 + object.name.length * 3; + return bytesCount; +} + +void _symptomsTypesSerialize( + SymptomsTypes object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.code); + writer.writeString(offsets[2], object.name); +} + +SymptomsTypes _symptomsTypesDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = SymptomsTypes(); + object.active = reader.readBool(offsets[0]); + object.code = reader.readString(offsets[1]); + object.name = reader.readString(offsets[2]); + return object; +} + +P _symptomsTypesDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBool(offset)) as P; + case 1: + return (reader.readString(offset)) as P; + case 2: + return (reader.readString(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension SymptomsTypesQueryFilter + on QueryBuilder { + QueryBuilder + activeEqualTo(bool value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder codeEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder codeBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'code', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder codeMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'code', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + codeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder nameEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } +} + +extension SymptomsTypesQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const ReferralReasonsSchema = Schema( + name: r'ReferralReasons', + id: 3398817133439165056, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'code': PropertySchema( + id: 1, + name: r'code', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ) + }, + estimateSize: _referralReasonsEstimateSize, + serialize: _referralReasonsSerialize, + deserialize: _referralReasonsDeserialize, + deserializeProp: _referralReasonsDeserializeProp, +); + +int _referralReasonsEstimateSize( + ReferralReasons object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + bytesCount += 3 + object.code.length * 3; + bytesCount += 3 + object.name.length * 3; + return bytesCount; +} + +void _referralReasonsSerialize( + ReferralReasons object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.code); + writer.writeString(offsets[2], object.name); +} + +ReferralReasons _referralReasonsDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = ReferralReasons(); + object.active = reader.readBool(offsets[0]); + object.code = reader.readString(offsets[1]); + object.name = reader.readString(offsets[2]); + return object; +} + +P _referralReasonsDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBool(offset)) as P; + case 1: + return (reader.readString(offset)) as P; + case 2: + return (reader.readString(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension ReferralReasonsQueryFilter + on QueryBuilder { + QueryBuilder + activeEqualTo(bool value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder + codeEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'code', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'code', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + codeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + nameEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } +} + +extension ReferralReasonsQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const HouseStructureTypesSchema = Schema( + name: r'HouseStructureTypes', + id: 7578394145153864404, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'code': PropertySchema( + id: 1, + name: r'code', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ) + }, + estimateSize: _houseStructureTypesEstimateSize, + serialize: _houseStructureTypesSerialize, + deserialize: _houseStructureTypesDeserialize, + deserializeProp: _houseStructureTypesDeserializeProp, +); + +int _houseStructureTypesEstimateSize( + HouseStructureTypes object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + bytesCount += 3 + object.code.length * 3; + bytesCount += 3 + object.name.length * 3; + return bytesCount; +} + +void _houseStructureTypesSerialize( + HouseStructureTypes object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.code); + writer.writeString(offsets[2], object.name); +} + +HouseStructureTypes _houseStructureTypesDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = HouseStructureTypes(); + object.active = reader.readBool(offsets[0]); + object.code = reader.readString(offsets[1]); + object.name = reader.readString(offsets[2]); + return object; +} + +P _houseStructureTypesDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBool(offset)) as P; + case 1: + return (reader.readString(offset)) as P; + case 2: + return (reader.readString(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension HouseStructureTypesQueryFilter on QueryBuilder { + QueryBuilder + activeEqualTo(bool value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder + codeEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'code', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'code', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + codeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + nameEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } +} + +extension HouseStructureTypesQueryObject on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const RefusalReasonsSchema = Schema( + name: r'RefusalReasons', + id: 1547295305086494581, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'code': PropertySchema( + id: 1, + name: r'code', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ) + }, + estimateSize: _refusalReasonsEstimateSize, + serialize: _refusalReasonsSerialize, + deserialize: _refusalReasonsDeserialize, + deserializeProp: _refusalReasonsDeserializeProp, +); + +int _refusalReasonsEstimateSize( + RefusalReasons object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + bytesCount += 3 + object.code.length * 3; + bytesCount += 3 + object.name.length * 3; + return bytesCount; +} + +void _refusalReasonsSerialize( + RefusalReasons object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.code); + writer.writeString(offsets[2], object.name); +} + +RefusalReasons _refusalReasonsDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = RefusalReasons(); + object.active = reader.readBool(offsets[0]); + object.code = reader.readString(offsets[1]); + object.name = reader.readString(offsets[2]); + return object; +} + +P _refusalReasonsDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBool(offset)) as P; + case 1: + return (reader.readString(offset)) as P; + case 2: + return (reader.readString(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension RefusalReasonsQueryFilter + on QueryBuilder { + QueryBuilder + activeEqualTo(bool value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder + codeEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'code', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'code', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'code', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + codeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + codeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'code', + value: '', + )); + }); + } + + QueryBuilder + nameEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } +} + +extension RefusalReasonsQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const PrivacyPolicySchema = Schema( + name: r'PrivacyPolicy', + id: 4448755274946548969, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'contents': PropertySchema( + id: 1, + name: r'contents', + type: IsarType.objectList, + target: r'Content', + ), + r'header': PropertySchema( + id: 2, + name: r'header', + type: IsarType.string, + ), + r'module': PropertySchema( + id: 3, + name: r'module', + type: IsarType.string, + ) + }, + estimateSize: _privacyPolicyEstimateSize, + serialize: _privacyPolicySerialize, + deserialize: _privacyPolicyDeserialize, + deserializeProp: _privacyPolicyDeserializeProp, +); + +int _privacyPolicyEstimateSize( + PrivacyPolicy object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final list = object.contents; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[Content]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += ContentSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } + bytesCount += 3 + object.header.length * 3; + bytesCount += 3 + object.module.length * 3; + return bytesCount; +} + +void _privacyPolicySerialize( + PrivacyPolicy object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeObjectList( + offsets[1], + allOffsets, + ContentSchema.serialize, + object.contents, + ); + writer.writeString(offsets[2], object.header); + writer.writeString(offsets[3], object.module); +} + +PrivacyPolicy _privacyPolicyDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = PrivacyPolicy(); + object.active = reader.readBoolOrNull(offsets[0]); + object.contents = reader.readObjectList( + offsets[1], + ContentSchema.deserialize, + allOffsets, + Content(), + ); + object.header = reader.readString(offsets[2]); + object.module = reader.readString(offsets[3]); + return object; +} + +P _privacyPolicyDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBoolOrNull(offset)) as P; + case 1: + return (reader.readObjectList( + offset, + ContentSchema.deserialize, + allOffsets, + Content(), + )) as P; + case 2: + return (reader.readString(offset)) as P; + case 3: + return (reader.readString(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension PrivacyPolicyQueryFilter + on QueryBuilder { + QueryBuilder + activeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'active', + )); + }); + } + + QueryBuilder + activeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'active', + )); + }); + } + + QueryBuilder + activeEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder + contentsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'contents', + )); + }); + } + + QueryBuilder + contentsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'contents', + )); + }); + } + + QueryBuilder + contentsLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder + contentsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + contentsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + contentsLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + contentsLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + contentsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'contents', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + + QueryBuilder + headerEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'header', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'header', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'header', + value: '', + )); + }); + } + + QueryBuilder + headerIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'header', + value: '', + )); + }); + } + + QueryBuilder + moduleEqualTo( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleGreaterThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleLessThan( + String value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleBetween( + String lower, + String upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'module', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'module', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'module', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + moduleIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'module', + value: '', + )); + }); + } + + QueryBuilder + moduleIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'module', + value: '', + )); + }); + } +} + +extension PrivacyPolicyQueryObject + on QueryBuilder { + QueryBuilder + contentsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'contents'); + }); + } +} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const ContentSchema = Schema( + name: r'Content', + id: 2749874844035024652, + properties: { + r'descriptions': PropertySchema( + id: 0, + name: r'descriptions', + type: IsarType.objectList, + target: r'Description', + ), + r'header': PropertySchema( + id: 1, + name: r'header', + type: IsarType.string, + ) + }, + estimateSize: _contentEstimateSize, + serialize: _contentSerialize, + deserialize: _contentDeserialize, + deserializeProp: _contentDeserializeProp, +); + +int _contentEstimateSize( + Content object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final list = object.descriptions; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[Description]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += + DescriptionSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } + { + final value = object.header; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + return bytesCount; +} + +void _contentSerialize( + Content object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeObjectList( + offsets[0], + allOffsets, + DescriptionSchema.serialize, + object.descriptions, + ); + writer.writeString(offsets[1], object.header); +} + +Content _contentDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = Content(); + object.descriptions = reader.readObjectList( + offsets[0], + DescriptionSchema.deserialize, + allOffsets, + Description(), + ); + object.header = reader.readStringOrNull(offsets[1]); + return object; +} + +P _contentDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readObjectList( + offset, + DescriptionSchema.deserialize, + allOffsets, + Description(), + )) as P; + case 1: + return (reader.readStringOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension ContentQueryFilter + on QueryBuilder { + QueryBuilder descriptionsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'descriptions', + )); }); } - QueryBuilder - enableCrashlyticsIsNotNull() { + QueryBuilder + descriptionsIsNotNull() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(const FilterCondition.isNotNull( - property: r'enableCrashlytics', + property: r'descriptions', )); }); } - QueryBuilder - enableCrashlyticsEqualTo(bool? value) { + QueryBuilder + descriptionsLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder descriptionsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + descriptionsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + descriptionsLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + descriptionsLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + descriptionsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'descriptions', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + + QueryBuilder headerIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'header', + )); + }); + } + + QueryBuilder headerIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'header', + )); + }); + } + + QueryBuilder headerEqualTo( + String? value, { + bool caseSensitive = true, + }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'enableCrashlytics', + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'header', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'header', value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'header', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'header', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder headerIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'header', + value: '', + )); + }); + } + + QueryBuilder headerIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'header', + value: '', )); }); } } -extension FirebaseConfigQueryObject - on QueryBuilder {} +extension ContentQueryObject + on QueryBuilder { + QueryBuilder descriptionsElement( + FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'descriptions'); + }); + } +} // coverage:ignore-file // ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types -const SymptomsTypesSchema = Schema( - name: r'SymptomsTypes', - id: 1335382729654316565, +const DescriptionSchema = Schema( + name: r'Description', + id: 405142296649109475, properties: { - r'active': PropertySchema( + r'isBold': PropertySchema( id: 0, - name: r'active', + name: r'isBold', type: IsarType.bool, ), - r'code': PropertySchema( + r'subDescriptions': PropertySchema( id: 1, - name: r'code', - type: IsarType.string, + name: r'subDescriptions', + type: IsarType.objectList, + target: r'SubDescription', ), - r'name': PropertySchema( + r'text': PropertySchema( id: 2, - name: r'name', + name: r'text', + type: IsarType.string, + ), + r'type': PropertySchema( + id: 3, + name: r'type', type: IsarType.string, ) }, - estimateSize: _symptomsTypesEstimateSize, - serialize: _symptomsTypesSerialize, - deserialize: _symptomsTypesDeserialize, - deserializeProp: _symptomsTypesDeserializeProp, + estimateSize: _descriptionEstimateSize, + serialize: _descriptionSerialize, + deserialize: _descriptionDeserialize, + deserializeProp: _descriptionDeserializeProp, ); -int _symptomsTypesEstimateSize( - SymptomsTypes object, +int _descriptionEstimateSize( + Description object, List offsets, Map> allOffsets, ) { var bytesCount = offsets.last; - bytesCount += 3 + object.code.length * 3; - bytesCount += 3 + object.name.length * 3; + { + final list = object.subDescriptions; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[SubDescription]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += + SubDescriptionSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } + { + final value = object.text; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.type; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } return bytesCount; } -void _symptomsTypesSerialize( - SymptomsTypes object, +void _descriptionSerialize( + Description object, IsarWriter writer, List offsets, Map> allOffsets, ) { - writer.writeBool(offsets[0], object.active); - writer.writeString(offsets[1], object.code); - writer.writeString(offsets[2], object.name); + writer.writeBool(offsets[0], object.isBold); + writer.writeObjectList( + offsets[1], + allOffsets, + SubDescriptionSchema.serialize, + object.subDescriptions, + ); + writer.writeString(offsets[2], object.text); + writer.writeString(offsets[3], object.type); } -SymptomsTypes _symptomsTypesDeserialize( +Description _descriptionDeserialize( Id id, IsarReader reader, List offsets, Map> allOffsets, ) { - final object = SymptomsTypes(); - object.active = reader.readBool(offsets[0]); - object.code = reader.readString(offsets[1]); - object.name = reader.readString(offsets[2]); + final object = Description(); + object.isBold = reader.readBoolOrNull(offsets[0]); + object.subDescriptions = reader.readObjectList( + offsets[1], + SubDescriptionSchema.deserialize, + allOffsets, + SubDescription(), + ); + object.text = reader.readStringOrNull(offsets[2]); + object.type = reader.readStringOrNull(offsets[3]); return object; } -P _symptomsTypesDeserializeProp

( +P _descriptionDeserializeProp

( IsarReader reader, int propertyId, int offset, @@ -8909,83 +12264,229 @@ P _symptomsTypesDeserializeProp

( ) { switch (propertyId) { case 0: - return (reader.readBool(offset)) as P; + return (reader.readBoolOrNull(offset)) as P; case 1: - return (reader.readString(offset)) as P; + return (reader.readObjectList( + offset, + SubDescriptionSchema.deserialize, + allOffsets, + SubDescription(), + )) as P; case 2: - return (reader.readString(offset)) as P; + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readStringOrNull(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } } -extension SymptomsTypesQueryFilter - on QueryBuilder { - QueryBuilder - activeEqualTo(bool value) { +extension DescriptionQueryFilter + on QueryBuilder { + QueryBuilder isBoldIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'isBold', + )); + }); + } + + QueryBuilder + isBoldIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'isBold', + )); + }); + } + + QueryBuilder isBoldEqualTo( + bool? value) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'active', + property: r'isBold', value: value, )); }); } - QueryBuilder codeEqualTo( - String value, { + QueryBuilder + subDescriptionsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'subDescriptions', + )); + }); + } + + QueryBuilder + subDescriptionsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'subDescriptions', + )); + }); + } + + QueryBuilder + subDescriptionsLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder + subDescriptionsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + subDescriptionsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + subDescriptionsLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + subDescriptionsLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + subDescriptionsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'subDescriptions', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + + QueryBuilder textIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'text', + )); + }); + } + + QueryBuilder + textIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'text', + )); + }); + } + + QueryBuilder textEqualTo( + String? value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeGreaterThan( - String value, { + QueryBuilder textGreaterThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( include: include, - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeLessThan( - String value, { + QueryBuilder textLessThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.lessThan( include: include, - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder codeBetween( - String lower, - String upper, { + QueryBuilder textBetween( + String? lower, + String? upper, { bool includeLower = true, bool includeUpper = true, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.between( - property: r'code', + property: r'text', lower: lower, includeLower: includeLower, upper: upper, @@ -8995,132 +12496,145 @@ extension SymptomsTypesQueryFilter }); } - QueryBuilder - codeStartsWith( + QueryBuilder textStartsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.startsWith( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeEndsWith( + QueryBuilder textEndsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.endsWith( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeContains(String value, {bool caseSensitive = true}) { + QueryBuilder textContains( + String value, + {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder codeMatches( + QueryBuilder textMatches( String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( - property: r'code', + property: r'text', wildcard: pattern, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeIsEmpty() { + QueryBuilder textIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'code', + property: r'text', value: '', )); }); } - QueryBuilder - codeIsNotEmpty() { + QueryBuilder + textIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( - property: r'code', + property: r'text', value: '', )); }); } - QueryBuilder nameEqualTo( - String value, { + QueryBuilder typeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'type', + )); + }); + } + + QueryBuilder + typeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'type', + )); + }); + } + + QueryBuilder typeEqualTo( + String? value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); - } - - QueryBuilder - nameGreaterThan( - String value, { + } + + QueryBuilder typeGreaterThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( include: include, - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameLessThan( - String value, { + QueryBuilder typeLessThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.lessThan( include: include, - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder nameBetween( - String lower, - String upper, { + QueryBuilder typeBetween( + String? lower, + String? upper, { bool includeLower = true, bool includeUpper = true, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.between( - property: r'name', + property: r'type', lower: lower, includeLower: includeLower, upper: upper, @@ -9130,146 +12644,168 @@ extension SymptomsTypesQueryFilter }); } - QueryBuilder - nameStartsWith( + QueryBuilder typeStartsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.startsWith( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameEndsWith( + QueryBuilder typeEndsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.endsWith( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameContains(String value, {bool caseSensitive = true}) { + QueryBuilder typeContains( + String value, + {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder nameMatches( + QueryBuilder typeMatches( String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( - property: r'name', + property: r'type', wildcard: pattern, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameIsEmpty() { + QueryBuilder typeIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'name', + property: r'type', value: '', )); }); } - QueryBuilder - nameIsNotEmpty() { + QueryBuilder + typeIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( - property: r'name', + property: r'type', value: '', )); }); } } -extension SymptomsTypesQueryObject - on QueryBuilder {} +extension DescriptionQueryObject + on QueryBuilder { + QueryBuilder + subDescriptionsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'subDescriptions'); + }); + } +} // coverage:ignore-file // ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types -const ReferralReasonsSchema = Schema( - name: r'ReferralReasons', - id: 3398817133439165056, +const SubDescriptionSchema = Schema( + name: r'SubDescription', + id: -605965919312517132, properties: { - r'active': PropertySchema( + r'isBold': PropertySchema( id: 0, - name: r'active', + name: r'isBold', type: IsarType.bool, ), - r'code': PropertySchema( + r'isSpaceRequired': PropertySchema( id: 1, - name: r'code', - type: IsarType.string, + name: r'isSpaceRequired', + type: IsarType.bool, ), - r'name': PropertySchema( + r'text': PropertySchema( id: 2, - name: r'name', + name: r'text', + type: IsarType.string, + ), + r'type': PropertySchema( + id: 3, + name: r'type', type: IsarType.string, ) }, - estimateSize: _referralReasonsEstimateSize, - serialize: _referralReasonsSerialize, - deserialize: _referralReasonsDeserialize, - deserializeProp: _referralReasonsDeserializeProp, + estimateSize: _subDescriptionEstimateSize, + serialize: _subDescriptionSerialize, + deserialize: _subDescriptionDeserialize, + deserializeProp: _subDescriptionDeserializeProp, ); -int _referralReasonsEstimateSize( - ReferralReasons object, +int _subDescriptionEstimateSize( + SubDescription object, List offsets, Map> allOffsets, ) { var bytesCount = offsets.last; - bytesCount += 3 + object.code.length * 3; - bytesCount += 3 + object.name.length * 3; + { + final value = object.text; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.type; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } return bytesCount; } -void _referralReasonsSerialize( - ReferralReasons object, +void _subDescriptionSerialize( + SubDescription object, IsarWriter writer, List offsets, Map> allOffsets, ) { - writer.writeBool(offsets[0], object.active); - writer.writeString(offsets[1], object.code); - writer.writeString(offsets[2], object.name); + writer.writeBool(offsets[0], object.isBold); + writer.writeBool(offsets[1], object.isSpaceRequired); + writer.writeString(offsets[2], object.text); + writer.writeString(offsets[3], object.type); } -ReferralReasons _referralReasonsDeserialize( +SubDescription _subDescriptionDeserialize( Id id, IsarReader reader, List offsets, Map> allOffsets, ) { - final object = ReferralReasons(); - object.active = reader.readBool(offsets[0]); - object.code = reader.readString(offsets[1]); - object.name = reader.readString(offsets[2]); + final object = SubDescription(); + object.isBold = reader.readBoolOrNull(offsets[0]); + object.isSpaceRequired = reader.readBoolOrNull(offsets[1]); + object.text = reader.readStringOrNull(offsets[2]); + object.type = reader.readStringOrNull(offsets[3]); return object; } -P _referralReasonsDeserializeProp

( +P _subDescriptionDeserializeProp

( IsarReader reader, int propertyId, int offset, @@ -9277,85 +12813,151 @@ P _referralReasonsDeserializeProp

( ) { switch (propertyId) { case 0: - return (reader.readBool(offset)) as P; + return (reader.readBoolOrNull(offset)) as P; case 1: - return (reader.readString(offset)) as P; + return (reader.readBoolOrNull(offset)) as P; case 2: - return (reader.readString(offset)) as P; + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readStringOrNull(offset)) as P; default: throw IsarError('Unknown property with id $propertyId'); } } -extension ReferralReasonsQueryFilter - on QueryBuilder { - QueryBuilder - activeEqualTo(bool value) { +extension SubDescriptionQueryFilter + on QueryBuilder { + QueryBuilder + isBoldIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'isBold', + )); + }); + } + + QueryBuilder + isBoldIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'isBold', + )); + }); + } + + QueryBuilder + isBoldEqualTo(bool? value) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'active', + property: r'isBold', value: value, )); }); } - QueryBuilder - codeEqualTo( - String value, { + QueryBuilder + isSpaceRequiredIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'isSpaceRequired', + )); + }); + } + + QueryBuilder + isSpaceRequiredIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'isSpaceRequired', + )); + }); + } + + QueryBuilder + isSpaceRequiredEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'isSpaceRequired', + value: value, + )); + }); + } + + QueryBuilder + textIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'text', + )); + }); + } + + QueryBuilder + textIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'text', + )); + }); + } + + QueryBuilder + textEqualTo( + String? value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeGreaterThan( - String value, { + QueryBuilder + textGreaterThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( include: include, - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeLessThan( - String value, { + QueryBuilder + textLessThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.lessThan( include: include, - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeBetween( - String lower, - String upper, { + QueryBuilder + textBetween( + String? lower, + String? upper, { bool includeLower = true, bool includeUpper = true, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.between( - property: r'code', + property: r'text', lower: lower, includeLower: includeLower, upper: upper, @@ -9365,133 +12967,151 @@ extension ReferralReasonsQueryFilter }); } - QueryBuilder - codeStartsWith( + QueryBuilder + textStartsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.startsWith( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeEndsWith( + QueryBuilder + textEndsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.endsWith( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeContains(String value, {bool caseSensitive = true}) { + QueryBuilder + textContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( - property: r'code', + property: r'text', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeMatches(String pattern, {bool caseSensitive = true}) { + QueryBuilder + textMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( - property: r'code', + property: r'text', wildcard: pattern, caseSensitive: caseSensitive, )); }); } - QueryBuilder - codeIsEmpty() { + QueryBuilder + textIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'code', + property: r'text', value: '', )); }); } - QueryBuilder - codeIsNotEmpty() { + QueryBuilder + textIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( - property: r'code', + property: r'text', value: '', )); }); } - QueryBuilder - nameEqualTo( - String value, { + QueryBuilder + typeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'type', + )); + }); + } + + QueryBuilder + typeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'type', + )); + }); + } + + QueryBuilder + typeEqualTo( + String? value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameGreaterThan( - String value, { + QueryBuilder + typeGreaterThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( include: include, - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameLessThan( - String value, { + QueryBuilder + typeLessThan( + String? value, { bool include = false, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.lessThan( include: include, - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameBetween( - String lower, - String upper, { + QueryBuilder + typeBetween( + String? lower, + String? upper, { bool includeLower = true, bool includeUpper = true, bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.between( - property: r'name', + property: r'type', lower: lower, includeLower: includeLower, upper: upper, @@ -9501,76 +13121,76 @@ extension ReferralReasonsQueryFilter }); } - QueryBuilder - nameStartsWith( + QueryBuilder + typeStartsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.startsWith( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameEndsWith( + QueryBuilder + typeEndsWith( String value, { bool caseSensitive = true, }) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.endsWith( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameContains(String value, {bool caseSensitive = true}) { + QueryBuilder + typeContains(String value, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.contains( - property: r'name', + property: r'type', value: value, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameMatches(String pattern, {bool caseSensitive = true}) { + QueryBuilder + typeMatches(String pattern, {bool caseSensitive = true}) { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.matches( - property: r'name', + property: r'type', wildcard: pattern, caseSensitive: caseSensitive, )); }); } - QueryBuilder - nameIsEmpty() { + QueryBuilder + typeIsEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.equalTo( - property: r'name', + property: r'type', value: '', )); }); } - QueryBuilder - nameIsNotEmpty() { + QueryBuilder + typeIsNotEmpty() { return QueryBuilder.apply(this, (query) { return query.addFilterCondition(FilterCondition.greaterThan( - property: r'name', + property: r'type', value: '', )); }); } } -extension ReferralReasonsQueryObject - on QueryBuilder {} +extension SubDescriptionQueryObject + on QueryBuilder {} diff --git a/apps/health_campaign_field_worker_app/lib/data/network_manager.dart b/apps/health_campaign_field_worker_app/lib/data/network_manager.dart index 649e8391a..54188873b 100644 --- a/apps/health_campaign_field_worker_app/lib/data/network_manager.dart +++ b/apps/health_campaign_field_worker_app/lib/data/network_manager.dart @@ -5,12 +5,10 @@ import 'package:digit_data_model/data_model.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:registration_delivery/registration_delivery.dart'; - import 'repositories/sync/remote_type.dart'; import 'package:provider/provider.dart'; import '../models/bandwidth/bandwidth_model.dart'; -import '../utils/constants.dart'; import 'local_store/secure_store/secure_store.dart'; import 'repositories/sync/sync_down.dart'; import 'repositories/sync/sync_up.dart'; @@ -233,9 +231,9 @@ abstract class SyncError implements Exception { } class SyncUpError extends SyncError { - const SyncUpError([dynamic error]) : super(error); + const SyncUpError([super.error]); } class SyncDownError extends SyncError { - const SyncDownError([dynamic error]) : super(error); + const SyncDownError([super.error]); } diff --git a/apps/health_campaign_field_worker_app/lib/data/repositories/local/localization.dart b/apps/health_campaign_field_worker_app/lib/data/repositories/local/localization.dart new file mode 100644 index 000000000..a5d873711 --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/data/repositories/local/localization.dart @@ -0,0 +1,107 @@ +import 'dart:async'; + +import 'package:digit_data_model/data/local_store/sql_store/sql_store.dart'; +import 'package:digit_data_model/utils/utils.dart'; +import 'package:drift/drift.dart'; + +import '../../../utils/utils.dart'; +import '../../local_store/no_sql/schema/localization.dart'; + +class LocalizationLocalRepository { + FutureOr> returnLocalizationFromSQL( + LocalSqlDataStore sql) async { + final selectQuery = sql.select(sql.localization).join([]); + + // List to hold the AND conditions + final andConditions = >[]; + + // Add condition for locale if provided + if (LocalizationParams().locale != null) { + final localeString = '${LocalizationParams().locale!}'; + andConditions.add(sql.localization.locale.equals(localeString)); + } + + // Add conditions for modules and codes + if (LocalizationParams().module != null && + LocalizationParams().module!.isNotEmpty) { + final moduleToExclude = LocalizationParams().module!; + + if (LocalizationParams().exclude == true) { + // Exclude modules but include records where the code matches + final moduleCondition = + sql.localization.module.contains(moduleToExclude).not(); + final codeCondition = LocalizationParams().code != null && + LocalizationParams().code!.isNotEmpty + ? sql.localization.code.isIn(LocalizationParams().code!.toList()) + : const Constant(false); // True if no code filter + + // Combine conditions: exclude module unless code matches + andConditions.add(buildAnd([moduleCondition | codeCondition])); + } else { + // Include specified modules and optionally filter by code + final moduleCondition = + sql.localization.module.contains(moduleToExclude); + final codeCondition = LocalizationParams().code != null && + LocalizationParams().code!.isNotEmpty + ? sql.localization.code.isIn(LocalizationParams().code!.toList()) + : const Constant(false); + + // Combine conditions: module matches and optionally code filter + andConditions.add(buildAnd([moduleCondition | codeCondition])); + } + } else if (LocalizationParams().code != null && + LocalizationParams().code!.isNotEmpty) { + // If no module filter, just apply code filter + andConditions + .add(sql.localization.code.isIn(LocalizationParams().code!.toList())); + } + + // Apply the combined conditions to the query + if (andConditions.isNotEmpty) { + selectQuery.where(buildAnd(andConditions)); + } + + final result = await selectQuery.get(); + + return result.map((row) { + final data = row.readTableOrNull(sql.localization); + + return Localization() + ..code = data!.code + ..locale = data.locale + ..module = data.module + ..message = data.message; + }).toList(); + } + + FutureOr> fetchLocalization( + {required LocalSqlDataStore sql, + required String locale, + required String module}) async { + final query = sql.select(sql.localization).join([]) + ..where( + buildAnd([ + sql.localization.locale.equals(locale), + sql.localization.module.contains(module), + ]), + ); + + final results = await query.get(); + + return results.map((e) { + final data = e.readTableOrNull(sql.localization); + return Localization() + ..code = data!.code + ..locale = data.locale + ..module = data.module + ..message = data.message; + }).toList(); + } + + FutureOr create( + List result, LocalSqlDataStore sql) async { + return sql.batch((batch) { + batch.insertAll(sql.localization, result); + }); + } +} diff --git a/apps/health_campaign_field_worker_app/lib/data/repositories/remote/localization.dart b/apps/health_campaign_field_worker_app/lib/data/repositories/remote/localization.dart index ca811cc7b..d4d3bee1d 100644 --- a/apps/health_campaign_field_worker_app/lib/data/repositories/remote/localization.dart +++ b/apps/health_campaign_field_worker_app/lib/data/repositories/remote/localization.dart @@ -1,19 +1,20 @@ import 'dart:async'; import 'dart:convert'; - +import 'package:digit_data_model/data_model.dart'; import 'package:dio/dio.dart'; -import 'package:isar/isar.dart'; +import 'package:drift/drift.dart'; import '../../../models/localization/localization_model.dart'; import '../../local_store/no_sql/schema/localization.dart'; +import '../local/localization.dart'; class LocalizationRepository { final Dio _client; - final Isar _isar; + final LocalSqlDataStore _sql; const LocalizationRepository( this._client, - this._isar, + this._sql, ); Future search({ @@ -30,7 +31,7 @@ class LocalizationRepository { return LocalizationModel.fromJson( json.decode(response.toString()), ); - } on DioError catch (_) { + } on DioException catch (_) { // Assuming there will be an errorMessage property in the JSON object rethrow; } @@ -42,38 +43,22 @@ class LocalizationRepository { required String module, required String tenantId, }) async { - final List localizationList = await _isar - .localizationWrappers - .filter() - .localeEqualTo(locale) - .findAll(); - - if (localizationList.isEmpty) { - final result = await search( - url: path, - queryParameters: { - "module": module, - "locale": locale, - "tenantId": tenantId, - }, - ); + var results = await search( + url: path, + queryParameters: { + "module": module, + "locale": locale, + "tenantId": tenantId, + }, + ); - final List newLocalizationList = result.messages - .map((e) => Localization() - ..message = e.message - ..code = e.code - ..locale = e.locale - ..module = e.module) - .toList(); - - final localizationWrapper = LocalizationWrapper() - ..locale = locale - ..localization = newLocalizationList; - - await _isar.writeTxn(() async { - await _isar.localizationWrappers.put(localizationWrapper); - // insert & update - }); - } + return results.messages + .map((e) => LocalizationCompanion( + code: Value(e.code), + locale: Value(e.locale), + message: Value(e.message), + module: Value(e.module), + )) + .toList(); } } diff --git a/apps/health_campaign_field_worker_app/lib/data/repositories/remote/mdms.dart b/apps/health_campaign_field_worker_app/lib/data/repositories/remote/mdms.dart index 2e318c257..748d821d1 100644 --- a/apps/health_campaign_field_worker_app/lib/data/repositories/remote/mdms.dart +++ b/apps/health_campaign_field_worker_app/lib/data/repositories/remote/mdms.dart @@ -8,6 +8,7 @@ import 'package:isar/isar.dart'; import '../../../models/app_config/app_config_model.dart' as app_configuration; import '../../../models/mdms/service_registry/pgr_service_defenitions.dart'; import '../../../models/mdms/service_registry/service_registry_model.dart'; +import '../../../models/privacy_notice/privacy_notice_model.dart'; import '../../../models/role_actions/role_actions_model.dart'; import '../../local_store/no_sql/schema/app_configuration.dart'; import '../../local_store/no_sql/schema/row_versions.dart'; @@ -113,7 +114,7 @@ class MdmsRepository { app_configuration.AppConfigPrimaryWrapperModel result, PGRServiceDefinitions pgrServiceDefinitions, Isar isar, - ) async { + ) { final appConfiguration = AppConfiguration(); final data = result.rowVersions?.rowVersionslist; @@ -216,6 +217,35 @@ class MdmsRepository { return genderOption; }).toList(); + final privacyPolicyConfig = commonMasters?.privacyPolicyConfig; + + final privacyPolicy = PrivacyPolicy() + ..header = privacyPolicyConfig?.first.header ?? '' + ..module = privacyPolicyConfig?.first.module ?? '' + ..active = privacyPolicyConfig?.first.active + ..contents = (privacyPolicyConfig?.first.contents ?? []).map((cont) { + final content = Content() + ..header = cont.header + ..descriptions = (cont.descriptions ?? []).map((d) { + final description = Description() + ..text = d.text + ..type = d.type + ..isBold = d.isBold + ..subDescriptions = (d.subDescriptions ?? []).map((sd) { + final subDescription = SubDescription() + ..text = sd.text + ..type = sd.type + ..isBold = sd.isBold + ..isSpaceRequired = sd.isSpaceRequired; + return subDescription; + }).toList(); + return description; + }).toList(); + return content; + }).toList(); + + + final List? idTypeOptions = element?.idTypeOptions.map((element) { final idOption = IdTypeOptions() @@ -277,6 +307,7 @@ class MdmsRepository { ..interfaces = interfaceList ?? []; appConfiguration.genderOptions = genderOptions; appConfiguration.idTypeOptions = idTypeOptions; + appConfiguration.privacyPolicyConfig = privacyPolicy; appConfiguration.deliveryCommentOptions = deliveryCommentOptions; appConfiguration.householdDeletionReasonOptions = householdDeletionReasonOptions; @@ -290,6 +321,15 @@ class MdmsRepository { appConfiguration.complaintTypes = complaintTypesList; appConfiguration.bandwidthBatchSize = bandwidthBatchSize; appConfiguration.downSyncBandwidthBatchSize = downSyncBandWidthBatchSize; + appConfiguration.searchHouseHoldFilters = + result.hcmWrapperModel?.searchHouseHoldFilters?.map((e) { + final searchFilters = SearchHouseHoldFilters() + ..name = e.name + ..code = e.code + ..active = e.active; + return searchFilters; + }).toList(); + appConfiguration.symptomsTypes = result.hcmWrapperModel?.symptomsTypeList?.map((e) { final symptomTypes = SymptomsTypes() @@ -309,10 +349,29 @@ class MdmsRepository { return reasonTypes; }).toList(); + appConfiguration.houseStructureTypes = + result.hcmWrapperModel?.houseStructureTypes?.map((e) { + final structureTypes = HouseStructureTypes() + ..name = e.name.toString() + ..code = e.code + ..active = e.active; + + return structureTypes; + }).toList(); + + appConfiguration.refusalReasons = + result.hcmWrapperModel?.refusalReasons?.map((e) { + final reasonTypes = RefusalReasons() + ..name = e.name.toString() + ..code = e.code + ..active = e.active; + + return reasonTypes; + }).toList(); - await isar.writeTxn(() async { - await isar.appConfigurations.put(appConfiguration); - await isar.rowVersionLists.putAll(rowVersionList); + isar.writeTxnSync(() { + isar.appConfigurations.putSync(appConfiguration); + isar.rowVersionLists.putAllSync(rowVersionList); }); } diff --git a/apps/health_campaign_field_worker_app/lib/data/repositories/sync/sync_down.dart b/apps/health_campaign_field_worker_app/lib/data/repositories/sync/sync_down.dart index b400bc564..e8f07d0e4 100644 --- a/apps/health_campaign_field_worker_app/lib/data/repositories/sync/sync_down.dart +++ b/apps/health_campaign_field_worker_app/lib/data/repositories/sync/sync_down.dart @@ -461,6 +461,7 @@ class PerformSyncDown { } break; + case DataModelType.hFReferral: responseEntities = await remote.search( HFReferralSearchModel( diff --git a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.dart b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.dart index acd587b13..a6ec53262 100644 --- a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.dart +++ b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.dart @@ -1,5 +1,7 @@ +import 'package:digit_dss/digit_dss.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import '../privacy_notice/privacy_notice_model.dart'; import '../referral_reasons/referral_reasons_model.dart'; import '../symptoms_types/symptoms_types_model.dart'; @@ -87,9 +89,15 @@ class HCMWrapperModel with _$HCMWrapperModel { @JsonKey(name: 'TRANSPORT_TYPES') required List transportTypes, @JsonKey(name: 'SYMPTOM_TYPES') List? symptomsTypeList, + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? searchHouseHoldFilters, @JsonKey(name: 'REFERRAL_REASONS') List? referralReasonList, - @JsonKey(name: 'FIREBASE_CONFIG') required List? firebaseConfig, + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? houseStructureTypes, + @JsonKey(name: 'REFUSAL_REASONS') List? refusalReasons, + @JsonKey(name: 'FIREBASE_CONFIG') + required List? firebaseConfig, }) = _HCMWrapperModel; factory HCMWrapperModel.fromJson( @@ -115,6 +123,7 @@ class CommonMastersWrapperModel with _$CommonMastersWrapperModel { const factory CommonMastersWrapperModel({ @JsonKey(name: 'GenderType') required List genderType, @JsonKey(name: 'StateInfo') required List stateInfo, + @JsonKey(name: 'PrivacyPolicy') required List privacyPolicyConfig, }) = _CommonMastersWrapperModel; factory CommonMastersWrapperModel.fromJson( @@ -320,6 +329,18 @@ class CallSupportList with _$CallSupportList { _$CallSupportListFromJson(json); } +@freezed +class SearchHouseHoldFilters with _$SearchHouseHoldFilters { + factory SearchHouseHoldFilters({ + required String name, + required String code, + required bool active, + }) = _SearchHouseHoldFilters; + + factory SearchHouseHoldFilters.fromJson(Map json) => + _$SearchHouseHoldFiltersFromJson(json); +} + @freezed class TransportTypes with _$TransportTypes { factory TransportTypes({ diff --git a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.freezed.dart b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.freezed.dart index f7e20a68c..2be2b1a00 100644 --- a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.freezed.dart +++ b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.freezed.dart @@ -952,9 +952,18 @@ mixin _$HCMWrapperModel { @JsonKey(name: 'SYMPTOM_TYPES') List? get symptomsTypeList => throw _privateConstructorUsedError; + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? get searchHouseHoldFilters => + throw _privateConstructorUsedError; @JsonKey(name: 'REFERRAL_REASONS') List? get referralReasonList => throw _privateConstructorUsedError; + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? get houseStructureTypes => + throw _privateConstructorUsedError; + @JsonKey(name: 'REFUSAL_REASONS') + List? get refusalReasons => + throw _privateConstructorUsedError; @JsonKey(name: 'FIREBASE_CONFIG') List? get firebaseConfig => throw _privateConstructorUsedError; @@ -993,8 +1002,13 @@ abstract class $HCMWrapperModelCopyWith<$Res> { @JsonKey(name: 'CALL_SUPPORT') List? callSupportOptions, @JsonKey(name: 'TRANSPORT_TYPES') List transportTypes, @JsonKey(name: 'SYMPTOM_TYPES') List? symptomsTypeList, + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? searchHouseHoldFilters, @JsonKey(name: 'REFERRAL_REASONS') List? referralReasonList, + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? houseStructureTypes, + @JsonKey(name: 'REFUSAL_REASONS') List? refusalReasons, @JsonKey(name: 'FIREBASE_CONFIG') List? firebaseConfig}); } @@ -1024,7 +1038,10 @@ class _$HCMWrapperModelCopyWithImpl<$Res, $Val extends HCMWrapperModel> Object? callSupportOptions = freezed, Object? transportTypes = null, Object? symptomsTypeList = freezed, + Object? searchHouseHoldFilters = freezed, Object? referralReasonList = freezed, + Object? houseStructureTypes = freezed, + Object? refusalReasons = freezed, Object? firebaseConfig = freezed, }) { return _then(_value.copyWith( @@ -1081,10 +1098,22 @@ class _$HCMWrapperModelCopyWithImpl<$Res, $Val extends HCMWrapperModel> ? _value.symptomsTypeList : symptomsTypeList // ignore: cast_nullable_to_non_nullable as List?, + searchHouseHoldFilters: freezed == searchHouseHoldFilters + ? _value.searchHouseHoldFilters + : searchHouseHoldFilters // ignore: cast_nullable_to_non_nullable + as List?, referralReasonList: freezed == referralReasonList ? _value.referralReasonList : referralReasonList // ignore: cast_nullable_to_non_nullable as List?, + houseStructureTypes: freezed == houseStructureTypes + ? _value.houseStructureTypes + : houseStructureTypes // ignore: cast_nullable_to_non_nullable + as List?, + refusalReasons: freezed == refusalReasons + ? _value.refusalReasons + : refusalReasons // ignore: cast_nullable_to_non_nullable + as List?, firebaseConfig: freezed == firebaseConfig ? _value.firebaseConfig : firebaseConfig // ignore: cast_nullable_to_non_nullable @@ -1123,8 +1152,13 @@ abstract class _$$HCMWrapperModelImplCopyWith<$Res> @JsonKey(name: 'CALL_SUPPORT') List? callSupportOptions, @JsonKey(name: 'TRANSPORT_TYPES') List transportTypes, @JsonKey(name: 'SYMPTOM_TYPES') List? symptomsTypeList, + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? searchHouseHoldFilters, @JsonKey(name: 'REFERRAL_REASONS') List? referralReasonList, + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? houseStructureTypes, + @JsonKey(name: 'REFUSAL_REASONS') List? refusalReasons, @JsonKey(name: 'FIREBASE_CONFIG') List? firebaseConfig}); } @@ -1152,7 +1186,10 @@ class __$$HCMWrapperModelImplCopyWithImpl<$Res> Object? callSupportOptions = freezed, Object? transportTypes = null, Object? symptomsTypeList = freezed, + Object? searchHouseHoldFilters = freezed, Object? referralReasonList = freezed, + Object? houseStructureTypes = freezed, + Object? refusalReasons = freezed, Object? firebaseConfig = freezed, }) { return _then(_$HCMWrapperModelImpl( @@ -1209,10 +1246,22 @@ class __$$HCMWrapperModelImplCopyWithImpl<$Res> ? _value._symptomsTypeList : symptomsTypeList // ignore: cast_nullable_to_non_nullable as List?, + searchHouseHoldFilters: freezed == searchHouseHoldFilters + ? _value._searchHouseHoldFilters + : searchHouseHoldFilters // ignore: cast_nullable_to_non_nullable + as List?, referralReasonList: freezed == referralReasonList ? _value._referralReasonList : referralReasonList // ignore: cast_nullable_to_non_nullable as List?, + houseStructureTypes: freezed == houseStructureTypes + ? _value._houseStructureTypes + : houseStructureTypes // ignore: cast_nullable_to_non_nullable + as List?, + refusalReasons: freezed == refusalReasons + ? _value._refusalReasons + : refusalReasons // ignore: cast_nullable_to_non_nullable + as List?, firebaseConfig: freezed == firebaseConfig ? _value._firebaseConfig : firebaseConfig // ignore: cast_nullable_to_non_nullable @@ -1251,8 +1300,14 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { required final List transportTypes, @JsonKey(name: 'SYMPTOM_TYPES') final List? symptomsTypeList, + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + final List? searchHouseHoldFilters, @JsonKey(name: 'REFERRAL_REASONS') final List? referralReasonList, + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + final List? houseStructureTypes, + @JsonKey(name: 'REFUSAL_REASONS') + final List? refusalReasons, @JsonKey(name: 'FIREBASE_CONFIG') required final List? firebaseConfig}) : _appConfig = appConfig, @@ -1269,7 +1324,10 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { _callSupportOptions = callSupportOptions, _transportTypes = transportTypes, _symptomsTypeList = symptomsTypeList, + _searchHouseHoldFilters = searchHouseHoldFilters, _referralReasonList = referralReasonList, + _houseStructureTypes = houseStructureTypes, + _refusalReasons = refusalReasons, _firebaseConfig = firebaseConfig; factory _$HCMWrapperModelImpl.fromJson(Map json) => @@ -1407,6 +1465,18 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { return EqualUnmodifiableListView(value); } + final List? _searchHouseHoldFilters; + @override + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? get searchHouseHoldFilters { + final value = _searchHouseHoldFilters; + if (value == null) return null; + if (_searchHouseHoldFilters is EqualUnmodifiableListView) + return _searchHouseHoldFilters; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + final List? _referralReasonList; @override @JsonKey(name: 'REFERRAL_REASONS') @@ -1419,6 +1489,29 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { return EqualUnmodifiableListView(value); } + final List? _houseStructureTypes; + @override + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? get houseStructureTypes { + final value = _houseStructureTypes; + if (value == null) return null; + if (_houseStructureTypes is EqualUnmodifiableListView) + return _houseStructureTypes; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + final List? _refusalReasons; + @override + @JsonKey(name: 'REFUSAL_REASONS') + List? get refusalReasons { + final value = _refusalReasons; + if (value == null) return null; + if (_refusalReasons is EqualUnmodifiableListView) return _refusalReasons; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + final List? _firebaseConfig; @override @JsonKey(name: 'FIREBASE_CONFIG') @@ -1432,7 +1525,7 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { @override String toString() { - return 'HCMWrapperModel(appConfig: $appConfig, bandWidthBatchSize: $bandWidthBatchSize, downSyncBandWidthBatchSize: $downSyncBandWidthBatchSize, householdDeletionReasonOptions: $householdDeletionReasonOptions, householdMemberDeletionReasonOptions: $householdMemberDeletionReasonOptions, backgroundServiceConfig: $backgroundServiceConfig, checklistTypes: $checklistTypes, idTypeOptions: $idTypeOptions, deliveryCommentOptions: $deliveryCommentOptions, backendInterface: $backendInterface, callSupportOptions: $callSupportOptions, transportTypes: $transportTypes, symptomsTypeList: $symptomsTypeList, referralReasonList: $referralReasonList, firebaseConfig: $firebaseConfig)'; + return 'HCMWrapperModel(appConfig: $appConfig, bandWidthBatchSize: $bandWidthBatchSize, downSyncBandWidthBatchSize: $downSyncBandWidthBatchSize, householdDeletionReasonOptions: $householdDeletionReasonOptions, householdMemberDeletionReasonOptions: $householdMemberDeletionReasonOptions, backgroundServiceConfig: $backgroundServiceConfig, checklistTypes: $checklistTypes, idTypeOptions: $idTypeOptions, deliveryCommentOptions: $deliveryCommentOptions, backendInterface: $backendInterface, callSupportOptions: $callSupportOptions, transportTypes: $transportTypes, symptomsTypeList: $symptomsTypeList, searchHouseHoldFilters: $searchHouseHoldFilters, referralReasonList: $referralReasonList, houseStructureTypes: $houseStructureTypes, refusalReasons: $refusalReasons, firebaseConfig: $firebaseConfig)'; } @override @@ -1469,8 +1562,14 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { .equals(other._transportTypes, _transportTypes) && const DeepCollectionEquality() .equals(other._symptomsTypeList, _symptomsTypeList) && + const DeepCollectionEquality().equals( + other._searchHouseHoldFilters, _searchHouseHoldFilters) && const DeepCollectionEquality() .equals(other._referralReasonList, _referralReasonList) && + const DeepCollectionEquality() + .equals(other._houseStructureTypes, _houseStructureTypes) && + const DeepCollectionEquality() + .equals(other._refusalReasons, _refusalReasons) && const DeepCollectionEquality() .equals(other._firebaseConfig, _firebaseConfig)); } @@ -1493,7 +1592,10 @@ class _$HCMWrapperModelImpl implements _HCMWrapperModel { const DeepCollectionEquality().hash(_callSupportOptions), const DeepCollectionEquality().hash(_transportTypes), const DeepCollectionEquality().hash(_symptomsTypeList), + const DeepCollectionEquality().hash(_searchHouseHoldFilters), const DeepCollectionEquality().hash(_referralReasonList), + const DeepCollectionEquality().hash(_houseStructureTypes), + const DeepCollectionEquality().hash(_refusalReasons), const DeepCollectionEquality().hash(_firebaseConfig)); @JsonKey(ignore: true) @@ -1539,8 +1641,14 @@ abstract class _HCMWrapperModel implements HCMWrapperModel { required final List transportTypes, @JsonKey(name: 'SYMPTOM_TYPES') final List? symptomsTypeList, + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + final List? searchHouseHoldFilters, @JsonKey(name: 'REFERRAL_REASONS') final List? referralReasonList, + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + final List? houseStructureTypes, + @JsonKey(name: 'REFUSAL_REASONS') + final List? refusalReasons, @JsonKey(name: 'FIREBASE_CONFIG') required final List? firebaseConfig}) = _$HCMWrapperModelImpl; @@ -1588,9 +1696,18 @@ abstract class _HCMWrapperModel implements HCMWrapperModel { @JsonKey(name: 'SYMPTOM_TYPES') List? get symptomsTypeList; @override + @JsonKey(name: 'SEARCH_HOUSEHOLD_FILTERS') + List? get searchHouseHoldFilters; + @override @JsonKey(name: 'REFERRAL_REASONS') List? get referralReasonList; @override + @JsonKey(name: 'HOUSE_STRUCTURE_TYPES') + List? get houseStructureTypes; + @override + @JsonKey(name: 'REFUSAL_REASONS') + List? get refusalReasons; + @override @JsonKey(name: 'FIREBASE_CONFIG') List? get firebaseConfig; @override @@ -1775,6 +1892,9 @@ mixin _$CommonMastersWrapperModel { List get genderType => throw _privateConstructorUsedError; @JsonKey(name: 'StateInfo') List get stateInfo => throw _privateConstructorUsedError; + @JsonKey(name: 'PrivacyPolicy') + List get privacyPolicyConfig => + throw _privateConstructorUsedError; Map toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) @@ -1790,7 +1910,9 @@ abstract class $CommonMastersWrapperModelCopyWith<$Res> { @useResult $Res call( {@JsonKey(name: 'GenderType') List genderType, - @JsonKey(name: 'StateInfo') List stateInfo}); + @JsonKey(name: 'StateInfo') List stateInfo, + @JsonKey(name: 'PrivacyPolicy') + List privacyPolicyConfig}); } /// @nodoc @@ -1809,6 +1931,7 @@ class _$CommonMastersWrapperModelCopyWithImpl<$Res, $Res call({ Object? genderType = null, Object? stateInfo = null, + Object? privacyPolicyConfig = null, }) { return _then(_value.copyWith( genderType: null == genderType @@ -1819,6 +1942,10 @@ class _$CommonMastersWrapperModelCopyWithImpl<$Res, ? _value.stateInfo : stateInfo // ignore: cast_nullable_to_non_nullable as List, + privacyPolicyConfig: null == privacyPolicyConfig + ? _value.privacyPolicyConfig + : privacyPolicyConfig // ignore: cast_nullable_to_non_nullable + as List, ) as $Val); } } @@ -1834,7 +1961,9 @@ abstract class _$$CommonMastersWrapperModelImplCopyWith<$Res> @useResult $Res call( {@JsonKey(name: 'GenderType') List genderType, - @JsonKey(name: 'StateInfo') List stateInfo}); + @JsonKey(name: 'StateInfo') List stateInfo, + @JsonKey(name: 'PrivacyPolicy') + List privacyPolicyConfig}); } /// @nodoc @@ -1852,6 +1981,7 @@ class __$$CommonMastersWrapperModelImplCopyWithImpl<$Res> $Res call({ Object? genderType = null, Object? stateInfo = null, + Object? privacyPolicyConfig = null, }) { return _then(_$CommonMastersWrapperModelImpl( genderType: null == genderType @@ -1862,6 +1992,10 @@ class __$$CommonMastersWrapperModelImplCopyWithImpl<$Res> ? _value._stateInfo : stateInfo // ignore: cast_nullable_to_non_nullable as List, + privacyPolicyConfig: null == privacyPolicyConfig + ? _value._privacyPolicyConfig + : privacyPolicyConfig // ignore: cast_nullable_to_non_nullable + as List, )); } } @@ -1872,10 +2006,12 @@ class _$CommonMastersWrapperModelImpl implements _CommonMastersWrapperModel { const _$CommonMastersWrapperModelImpl( {@JsonKey(name: 'GenderType') required final List genderType, - @JsonKey(name: 'StateInfo') - required final List stateInfo}) + @JsonKey(name: 'StateInfo') required final List stateInfo, + @JsonKey(name: 'PrivacyPolicy') + required final List privacyPolicyConfig}) : _genderType = genderType, - _stateInfo = stateInfo; + _stateInfo = stateInfo, + _privacyPolicyConfig = privacyPolicyConfig; factory _$CommonMastersWrapperModelImpl.fromJson(Map json) => _$$CommonMastersWrapperModelImplFromJson(json); @@ -1898,9 +2034,19 @@ class _$CommonMastersWrapperModelImpl implements _CommonMastersWrapperModel { return EqualUnmodifiableListView(_stateInfo); } + final List _privacyPolicyConfig; + @override + @JsonKey(name: 'PrivacyPolicy') + List get privacyPolicyConfig { + if (_privacyPolicyConfig is EqualUnmodifiableListView) + return _privacyPolicyConfig; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_privacyPolicyConfig); + } + @override String toString() { - return 'CommonMastersWrapperModel(genderType: $genderType, stateInfo: $stateInfo)'; + return 'CommonMastersWrapperModel(genderType: $genderType, stateInfo: $stateInfo, privacyPolicyConfig: $privacyPolicyConfig)'; } @override @@ -1911,7 +2057,9 @@ class _$CommonMastersWrapperModelImpl implements _CommonMastersWrapperModel { const DeepCollectionEquality() .equals(other._genderType, _genderType) && const DeepCollectionEquality() - .equals(other._stateInfo, _stateInfo)); + .equals(other._stateInfo, _stateInfo) && + const DeepCollectionEquality() + .equals(other._privacyPolicyConfig, _privacyPolicyConfig)); } @JsonKey(ignore: true) @@ -1919,7 +2067,8 @@ class _$CommonMastersWrapperModelImpl implements _CommonMastersWrapperModel { int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(_genderType), - const DeepCollectionEquality().hash(_stateInfo)); + const DeepCollectionEquality().hash(_stateInfo), + const DeepCollectionEquality().hash(_privacyPolicyConfig)); @JsonKey(ignore: true) @override @@ -1938,11 +2087,12 @@ class _$CommonMastersWrapperModelImpl implements _CommonMastersWrapperModel { abstract class _CommonMastersWrapperModel implements CommonMastersWrapperModel { const factory _CommonMastersWrapperModel( - {@JsonKey(name: 'GenderType') - required final List genderType, - @JsonKey(name: 'StateInfo') - required final List stateInfo}) = - _$CommonMastersWrapperModelImpl; + {@JsonKey(name: 'GenderType') + required final List genderType, + @JsonKey(name: 'StateInfo') required final List stateInfo, + @JsonKey(name: 'PrivacyPolicy') + required final List + privacyPolicyConfig}) = _$CommonMastersWrapperModelImpl; factory _CommonMastersWrapperModel.fromJson(Map json) = _$CommonMastersWrapperModelImpl.fromJson; @@ -1954,6 +2104,9 @@ abstract class _CommonMastersWrapperModel implements CommonMastersWrapperModel { @JsonKey(name: 'StateInfo') List get stateInfo; @override + @JsonKey(name: 'PrivacyPolicy') + List get privacyPolicyConfig; + @override @JsonKey(ignore: true) _$$CommonMastersWrapperModelImplCopyWith<_$CommonMastersWrapperModelImpl> get copyWith => throw _privateConstructorUsedError; @@ -4914,6 +5067,184 @@ abstract class _CallSupportList implements CallSupportList { throw _privateConstructorUsedError; } +SearchHouseHoldFilters _$SearchHouseHoldFiltersFromJson( + Map json) { + return _SearchHouseHoldFilters.fromJson(json); +} + +/// @nodoc +mixin _$SearchHouseHoldFilters { + String get name => throw _privateConstructorUsedError; + String get code => throw _privateConstructorUsedError; + bool get active => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $SearchHouseHoldFiltersCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SearchHouseHoldFiltersCopyWith<$Res> { + factory $SearchHouseHoldFiltersCopyWith(SearchHouseHoldFilters value, + $Res Function(SearchHouseHoldFilters) then) = + _$SearchHouseHoldFiltersCopyWithImpl<$Res, SearchHouseHoldFilters>; + @useResult + $Res call({String name, String code, bool active}); +} + +/// @nodoc +class _$SearchHouseHoldFiltersCopyWithImpl<$Res, + $Val extends SearchHouseHoldFilters> + implements $SearchHouseHoldFiltersCopyWith<$Res> { + _$SearchHouseHoldFiltersCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? code = null, + Object? active = null, + }) { + return _then(_value.copyWith( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + code: null == code + ? _value.code + : code // ignore: cast_nullable_to_non_nullable + as String, + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$SearchHouseHoldFiltersImplCopyWith<$Res> + implements $SearchHouseHoldFiltersCopyWith<$Res> { + factory _$$SearchHouseHoldFiltersImplCopyWith( + _$SearchHouseHoldFiltersImpl value, + $Res Function(_$SearchHouseHoldFiltersImpl) then) = + __$$SearchHouseHoldFiltersImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String name, String code, bool active}); +} + +/// @nodoc +class __$$SearchHouseHoldFiltersImplCopyWithImpl<$Res> + extends _$SearchHouseHoldFiltersCopyWithImpl<$Res, + _$SearchHouseHoldFiltersImpl> + implements _$$SearchHouseHoldFiltersImplCopyWith<$Res> { + __$$SearchHouseHoldFiltersImplCopyWithImpl( + _$SearchHouseHoldFiltersImpl _value, + $Res Function(_$SearchHouseHoldFiltersImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? code = null, + Object? active = null, + }) { + return _then(_$SearchHouseHoldFiltersImpl( + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + code: null == code + ? _value.code + : code // ignore: cast_nullable_to_non_nullable + as String, + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$SearchHouseHoldFiltersImpl implements _SearchHouseHoldFilters { + _$SearchHouseHoldFiltersImpl( + {required this.name, required this.code, required this.active}); + + factory _$SearchHouseHoldFiltersImpl.fromJson(Map json) => + _$$SearchHouseHoldFiltersImplFromJson(json); + + @override + final String name; + @override + final String code; + @override + final bool active; + + @override + String toString() { + return 'SearchHouseHoldFilters(name: $name, code: $code, active: $active)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SearchHouseHoldFiltersImpl && + (identical(other.name, name) || other.name == name) && + (identical(other.code, code) || other.code == code) && + (identical(other.active, active) || other.active == active)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, name, code, active); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$SearchHouseHoldFiltersImplCopyWith<_$SearchHouseHoldFiltersImpl> + get copyWith => __$$SearchHouseHoldFiltersImplCopyWithImpl< + _$SearchHouseHoldFiltersImpl>(this, _$identity); + + @override + Map toJson() { + return _$$SearchHouseHoldFiltersImplToJson( + this, + ); + } +} + +abstract class _SearchHouseHoldFilters implements SearchHouseHoldFilters { + factory _SearchHouseHoldFilters( + {required final String name, + required final String code, + required final bool active}) = _$SearchHouseHoldFiltersImpl; + + factory _SearchHouseHoldFilters.fromJson(Map json) = + _$SearchHouseHoldFiltersImpl.fromJson; + + @override + String get name; + @override + String get code; + @override + bool get active; + @override + @JsonKey(ignore: true) + _$$SearchHouseHoldFiltersImplCopyWith<_$SearchHouseHoldFiltersImpl> + get copyWith => throw _privateConstructorUsedError; +} + TransportTypes _$TransportTypesFromJson(Map json) { return _TransportTypes.fromJson(json); } diff --git a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.g.dart b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.g.dart index 736861977..04a332684 100644 --- a/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.g.dart +++ b/apps/health_campaign_field_worker_app/lib/models/app_config/app_config_model.g.dart @@ -136,9 +136,20 @@ _$HCMWrapperModelImpl _$$HCMWrapperModelImplFromJson( symptomsTypeList: (json['SYMPTOM_TYPES'] as List?) ?.map((e) => SymptomsType.fromJson(e as Map)) .toList(), + searchHouseHoldFilters: (json['SEARCH_HOUSEHOLD_FILTERS'] + as List?) + ?.map( + (e) => SearchHouseHoldFilters.fromJson(e as Map)) + .toList(), referralReasonList: (json['REFERRAL_REASONS'] as List?) ?.map((e) => ReferralReasonType.fromJson(e as Map)) .toList(), + houseStructureTypes: (json['HOUSE_STRUCTURE_TYPES'] as List?) + ?.map((e) => CommonMasterModel.fromJson(e as Map)) + .toList(), + refusalReasons: (json['REFUSAL_REASONS'] as List?) + ?.map((e) => CommonMasterModel.fromJson(e as Map)) + .toList(), firebaseConfig: (json['FIREBASE_CONFIG'] as List?) ?.map((e) => FirebaseConfig.fromJson(e as Map)) .toList(), @@ -162,7 +173,10 @@ Map _$$HCMWrapperModelImplToJson( 'CALL_SUPPORT': instance.callSupportOptions, 'TRANSPORT_TYPES': instance.transportTypes, 'SYMPTOM_TYPES': instance.symptomsTypeList, + 'SEARCH_HOUSEHOLD_FILTERS': instance.searchHouseHoldFilters, 'REFERRAL_REASONS': instance.referralReasonList, + 'HOUSE_STRUCTURE_TYPES': instance.houseStructureTypes, + 'REFUSAL_REASONS': instance.refusalReasons, 'FIREBASE_CONFIG': instance.firebaseConfig, }; @@ -189,6 +203,9 @@ _$CommonMastersWrapperModelImpl _$$CommonMastersWrapperModelImplFromJson( stateInfo: (json['StateInfo'] as List) .map((e) => StateInfoModel.fromJson(e as Map)) .toList(), + privacyPolicyConfig: (json['PrivacyPolicy'] as List) + .map((e) => PrivacyPolicyModel.fromJson(e as Map)) + .toList(), ); Map _$$CommonMastersWrapperModelImplToJson( @@ -196,6 +213,7 @@ Map _$$CommonMastersWrapperModelImplToJson( { 'GenderType': instance.genderType, 'StateInfo': instance.stateInfo, + 'PrivacyPolicy': instance.privacyPolicyConfig, }; _$CommonMasterModelImpl _$$CommonMasterModelImplFromJson( @@ -443,6 +461,22 @@ Map _$$CallSupportListImplToJson( 'code': instance.code, }; +_$SearchHouseHoldFiltersImpl _$$SearchHouseHoldFiltersImplFromJson( + Map json) => + _$SearchHouseHoldFiltersImpl( + name: json['name'] as String, + code: json['code'] as String, + active: json['active'] as bool, + ); + +Map _$$SearchHouseHoldFiltersImplToJson( + _$SearchHouseHoldFiltersImpl instance) => + { + 'name': instance.name, + 'code': instance.code, + 'active': instance.active, + }; + _$TransportTypesImpl _$$TransportTypesImplFromJson(Map json) => _$TransportTypesImpl( name: json['name'] as String, diff --git a/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.dart b/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.dart index da1d99ada..b44f040b1 100644 --- a/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.dart +++ b/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.dart @@ -11,6 +11,10 @@ enum MasterEnums { symptomTypes, @MappableValue("REFERRAL_REASONS") referralReasons, + @MappableValue("HOUSE_STRUCTURE_TYPES") + houseStructureTypes, + @MappableValue("REFUSAL_REASONS") + refusalReasons, @MappableValue("BANDWIDTH_BATCH_SIZE") bandWidthBatchSize, @MappableValue("DOWNSYNC-BANDWIDTH_BATCH_SIZE") @@ -43,4 +47,10 @@ enum MasterEnums { serviceDefinitions, @MappableValue("FIREBASE_CONFIG") firebaseConfig, + @MappableValue("SEARCH_HOUSEHOLD_FILTERS") + searchHouseHoldFilters, + @MappableValue("PRIVACY_POLICY") + privacyPolicy, + @MappableValue("dashboardConfig") + dashboardConfig, } diff --git a/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.mapper.dart b/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.mapper.dart index cc1fcc5ad..8e12d08c8 100644 --- a/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.mapper.dart +++ b/apps/health_campaign_field_worker_app/lib/models/entities/mdms_master_enums.mapper.dart @@ -31,6 +31,10 @@ class MasterEnumsMapper extends EnumMapper { return MasterEnums.symptomTypes; case "REFERRAL_REASONS": return MasterEnums.referralReasons; + case "HOUSE_STRUCTURE_TYPES": + return MasterEnums.houseStructureTypes; + case "REFUSAL_REASONS": + return MasterEnums.refusalReasons; case "BANDWIDTH_BATCH_SIZE": return MasterEnums.bandWidthBatchSize; case "DOWNSYNC-BANDWIDTH_BATCH_SIZE": @@ -63,6 +67,12 @@ class MasterEnumsMapper extends EnumMapper { return MasterEnums.serviceDefinitions; case "FIREBASE_CONFIG": return MasterEnums.firebaseConfig; + case "SEARCH_HOUSEHOLD_FILTERS": + return MasterEnums.searchHouseHoldFilters; + case "PRIVACY_POLICY": + return MasterEnums.privacyPolicy; + case "dashboardConfig": + return MasterEnums.dashboardConfig; default: throw MapperException.unknownEnumValue(value); } @@ -77,6 +87,10 @@ class MasterEnumsMapper extends EnumMapper { return "SYMPTOM_TYPES"; case MasterEnums.referralReasons: return "REFERRAL_REASONS"; + case MasterEnums.houseStructureTypes: + return "HOUSE_STRUCTURE_TYPES"; + case MasterEnums.refusalReasons: + return "REFUSAL_REASONS"; case MasterEnums.bandWidthBatchSize: return "BANDWIDTH_BATCH_SIZE"; case MasterEnums.downSyncBandwidthBatchSize: @@ -109,6 +123,12 @@ class MasterEnumsMapper extends EnumMapper { return "ServiceDefs"; case MasterEnums.firebaseConfig: return "FIREBASE_CONFIG"; + case MasterEnums.searchHouseHoldFilters: + return "SEARCH_HOUSEHOLD_FILTERS"; + case MasterEnums.privacyPolicy: + return "PRIVACY_POLICY"; + case MasterEnums.dashboardConfig: + return "dashboardConfig"; } } } diff --git a/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.dart b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.dart new file mode 100644 index 000000000..5ac1866af --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.dart @@ -0,0 +1,50 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'privacy_notice_model.freezed.dart'; +part 'privacy_notice_model.g.dart'; + +@freezed +class PrivacyPolicyModel with _$PrivacyPolicyModel { + const factory PrivacyPolicyModel({ + required String header, + required String module, + bool? active, + List? contents, + }) = _PrivacyPolicyModel; + + factory PrivacyPolicyModel.fromJson(Map json) => _$PrivacyPolicyModelFromJson(json); +} + +@freezed +class ContentModel with _$ContentModel { + const factory ContentModel({ + String? header, + List? descriptions, + }) = _ContentModel; + + factory ContentModel.fromJson(Map json) => _$ContentModelFromJson(json); +} + +@freezed +class DescriptionModel with _$DescriptionModel { + const factory DescriptionModel({ + String? text, + String? type, + bool? isBold, + List? subDescriptions, + }) = _DescriptionModel; + + factory DescriptionModel.fromJson(Map json) => _$DescriptionModelFromJson(json); +} + +@freezed +class SubDescriptionModel with _$SubDescriptionModel { + const factory SubDescriptionModel({ + String? text, + String? type, + bool? isBold, + bool? isSpaceRequired, + }) = _SubDescriptionModel; + + factory SubDescriptionModel.fromJson(Map json) => _$SubDescriptionModelFromJson(json); +} diff --git a/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.freezed.dart b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.freezed.dart new file mode 100644 index 000000000..c999b3371 --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.freezed.dart @@ -0,0 +1,796 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'privacy_notice_model.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +PrivacyPolicyModel _$PrivacyPolicyModelFromJson(Map json) { + return _PrivacyPolicyModel.fromJson(json); +} + +/// @nodoc +mixin _$PrivacyPolicyModel { + String get header => throw _privateConstructorUsedError; + String get module => throw _privateConstructorUsedError; + bool? get active => throw _privateConstructorUsedError; + List? get contents => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $PrivacyPolicyModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $PrivacyPolicyModelCopyWith<$Res> { + factory $PrivacyPolicyModelCopyWith( + PrivacyPolicyModel value, $Res Function(PrivacyPolicyModel) then) = + _$PrivacyPolicyModelCopyWithImpl<$Res, PrivacyPolicyModel>; + @useResult + $Res call( + {String header, + String module, + bool? active, + List? contents}); +} + +/// @nodoc +class _$PrivacyPolicyModelCopyWithImpl<$Res, $Val extends PrivacyPolicyModel> + implements $PrivacyPolicyModelCopyWith<$Res> { + _$PrivacyPolicyModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? header = null, + Object? module = null, + Object? active = freezed, + Object? contents = freezed, + }) { + return _then(_value.copyWith( + header: null == header + ? _value.header + : header // ignore: cast_nullable_to_non_nullable + as String, + module: null == module + ? _value.module + : module // ignore: cast_nullable_to_non_nullable + as String, + active: freezed == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool?, + contents: freezed == contents + ? _value.contents + : contents // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$PrivacyPolicyModelImplCopyWith<$Res> + implements $PrivacyPolicyModelCopyWith<$Res> { + factory _$$PrivacyPolicyModelImplCopyWith(_$PrivacyPolicyModelImpl value, + $Res Function(_$PrivacyPolicyModelImpl) then) = + __$$PrivacyPolicyModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String header, + String module, + bool? active, + List? contents}); +} + +/// @nodoc +class __$$PrivacyPolicyModelImplCopyWithImpl<$Res> + extends _$PrivacyPolicyModelCopyWithImpl<$Res, _$PrivacyPolicyModelImpl> + implements _$$PrivacyPolicyModelImplCopyWith<$Res> { + __$$PrivacyPolicyModelImplCopyWithImpl(_$PrivacyPolicyModelImpl _value, + $Res Function(_$PrivacyPolicyModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? header = null, + Object? module = null, + Object? active = freezed, + Object? contents = freezed, + }) { + return _then(_$PrivacyPolicyModelImpl( + header: null == header + ? _value.header + : header // ignore: cast_nullable_to_non_nullable + as String, + module: null == module + ? _value.module + : module // ignore: cast_nullable_to_non_nullable + as String, + active: freezed == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool?, + contents: freezed == contents + ? _value._contents + : contents // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$PrivacyPolicyModelImpl implements _PrivacyPolicyModel { + const _$PrivacyPolicyModelImpl( + {required this.header, + required this.module, + this.active, + final List? contents}) + : _contents = contents; + + factory _$PrivacyPolicyModelImpl.fromJson(Map json) => + _$$PrivacyPolicyModelImplFromJson(json); + + @override + final String header; + @override + final String module; + @override + final bool? active; + final List? _contents; + @override + List? get contents { + final value = _contents; + if (value == null) return null; + if (_contents is EqualUnmodifiableListView) return _contents; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'PrivacyPolicyModel(header: $header, module: $module, active: $active, contents: $contents)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$PrivacyPolicyModelImpl && + (identical(other.header, header) || other.header == header) && + (identical(other.module, module) || other.module == module) && + (identical(other.active, active) || other.active == active) && + const DeepCollectionEquality().equals(other._contents, _contents)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, header, module, active, + const DeepCollectionEquality().hash(_contents)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$PrivacyPolicyModelImplCopyWith<_$PrivacyPolicyModelImpl> get copyWith => + __$$PrivacyPolicyModelImplCopyWithImpl<_$PrivacyPolicyModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$PrivacyPolicyModelImplToJson( + this, + ); + } +} + +abstract class _PrivacyPolicyModel implements PrivacyPolicyModel { + const factory _PrivacyPolicyModel( + {required final String header, + required final String module, + final bool? active, + final List? contents}) = _$PrivacyPolicyModelImpl; + + factory _PrivacyPolicyModel.fromJson(Map json) = + _$PrivacyPolicyModelImpl.fromJson; + + @override + String get header; + @override + String get module; + @override + bool? get active; + @override + List? get contents; + @override + @JsonKey(ignore: true) + _$$PrivacyPolicyModelImplCopyWith<_$PrivacyPolicyModelImpl> get copyWith => + throw _privateConstructorUsedError; +} + +ContentModel _$ContentModelFromJson(Map json) { + return _ContentModel.fromJson(json); +} + +/// @nodoc +mixin _$ContentModel { + String? get header => throw _privateConstructorUsedError; + List? get descriptions => + throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $ContentModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ContentModelCopyWith<$Res> { + factory $ContentModelCopyWith( + ContentModel value, $Res Function(ContentModel) then) = + _$ContentModelCopyWithImpl<$Res, ContentModel>; + @useResult + $Res call({String? header, List? descriptions}); +} + +/// @nodoc +class _$ContentModelCopyWithImpl<$Res, $Val extends ContentModel> + implements $ContentModelCopyWith<$Res> { + _$ContentModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? header = freezed, + Object? descriptions = freezed, + }) { + return _then(_value.copyWith( + header: freezed == header + ? _value.header + : header // ignore: cast_nullable_to_non_nullable + as String?, + descriptions: freezed == descriptions + ? _value.descriptions + : descriptions // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ContentModelImplCopyWith<$Res> + implements $ContentModelCopyWith<$Res> { + factory _$$ContentModelImplCopyWith( + _$ContentModelImpl value, $Res Function(_$ContentModelImpl) then) = + __$$ContentModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String? header, List? descriptions}); +} + +/// @nodoc +class __$$ContentModelImplCopyWithImpl<$Res> + extends _$ContentModelCopyWithImpl<$Res, _$ContentModelImpl> + implements _$$ContentModelImplCopyWith<$Res> { + __$$ContentModelImplCopyWithImpl( + _$ContentModelImpl _value, $Res Function(_$ContentModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? header = freezed, + Object? descriptions = freezed, + }) { + return _then(_$ContentModelImpl( + header: freezed == header + ? _value.header + : header // ignore: cast_nullable_to_non_nullable + as String?, + descriptions: freezed == descriptions + ? _value._descriptions + : descriptions // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$ContentModelImpl implements _ContentModel { + const _$ContentModelImpl( + {this.header, final List? descriptions}) + : _descriptions = descriptions; + + factory _$ContentModelImpl.fromJson(Map json) => + _$$ContentModelImplFromJson(json); + + @override + final String? header; + final List? _descriptions; + @override + List? get descriptions { + final value = _descriptions; + if (value == null) return null; + if (_descriptions is EqualUnmodifiableListView) return _descriptions; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'ContentModel(header: $header, descriptions: $descriptions)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ContentModelImpl && + (identical(other.header, header) || other.header == header) && + const DeepCollectionEquality() + .equals(other._descriptions, _descriptions)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash( + runtimeType, header, const DeepCollectionEquality().hash(_descriptions)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ContentModelImplCopyWith<_$ContentModelImpl> get copyWith => + __$$ContentModelImplCopyWithImpl<_$ContentModelImpl>(this, _$identity); + + @override + Map toJson() { + return _$$ContentModelImplToJson( + this, + ); + } +} + +abstract class _ContentModel implements ContentModel { + const factory _ContentModel( + {final String? header, + final List? descriptions}) = _$ContentModelImpl; + + factory _ContentModel.fromJson(Map json) = + _$ContentModelImpl.fromJson; + + @override + String? get header; + @override + List? get descriptions; + @override + @JsonKey(ignore: true) + _$$ContentModelImplCopyWith<_$ContentModelImpl> get copyWith => + throw _privateConstructorUsedError; +} + +DescriptionModel _$DescriptionModelFromJson(Map json) { + return _DescriptionModel.fromJson(json); +} + +/// @nodoc +mixin _$DescriptionModel { + String? get text => throw _privateConstructorUsedError; + String? get type => throw _privateConstructorUsedError; + bool? get isBold => throw _privateConstructorUsedError; + List? get subDescriptions => + throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DescriptionModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DescriptionModelCopyWith<$Res> { + factory $DescriptionModelCopyWith( + DescriptionModel value, $Res Function(DescriptionModel) then) = + _$DescriptionModelCopyWithImpl<$Res, DescriptionModel>; + @useResult + $Res call( + {String? text, + String? type, + bool? isBold, + List? subDescriptions}); +} + +/// @nodoc +class _$DescriptionModelCopyWithImpl<$Res, $Val extends DescriptionModel> + implements $DescriptionModelCopyWith<$Res> { + _$DescriptionModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = freezed, + Object? type = freezed, + Object? isBold = freezed, + Object? subDescriptions = freezed, + }) { + return _then(_value.copyWith( + text: freezed == text + ? _value.text + : text // ignore: cast_nullable_to_non_nullable + as String?, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String?, + isBold: freezed == isBold + ? _value.isBold + : isBold // ignore: cast_nullable_to_non_nullable + as bool?, + subDescriptions: freezed == subDescriptions + ? _value.subDescriptions + : subDescriptions // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DescriptionModelImplCopyWith<$Res> + implements $DescriptionModelCopyWith<$Res> { + factory _$$DescriptionModelImplCopyWith(_$DescriptionModelImpl value, + $Res Function(_$DescriptionModelImpl) then) = + __$$DescriptionModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {String? text, + String? type, + bool? isBold, + List? subDescriptions}); +} + +/// @nodoc +class __$$DescriptionModelImplCopyWithImpl<$Res> + extends _$DescriptionModelCopyWithImpl<$Res, _$DescriptionModelImpl> + implements _$$DescriptionModelImplCopyWith<$Res> { + __$$DescriptionModelImplCopyWithImpl(_$DescriptionModelImpl _value, + $Res Function(_$DescriptionModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = freezed, + Object? type = freezed, + Object? isBold = freezed, + Object? subDescriptions = freezed, + }) { + return _then(_$DescriptionModelImpl( + text: freezed == text + ? _value.text + : text // ignore: cast_nullable_to_non_nullable + as String?, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String?, + isBold: freezed == isBold + ? _value.isBold + : isBold // ignore: cast_nullable_to_non_nullable + as bool?, + subDescriptions: freezed == subDescriptions + ? _value._subDescriptions + : subDescriptions // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DescriptionModelImpl implements _DescriptionModel { + const _$DescriptionModelImpl( + {this.text, + this.type, + this.isBold, + final List? subDescriptions}) + : _subDescriptions = subDescriptions; + + factory _$DescriptionModelImpl.fromJson(Map json) => + _$$DescriptionModelImplFromJson(json); + + @override + final String? text; + @override + final String? type; + @override + final bool? isBold; + final List? _subDescriptions; + @override + List? get subDescriptions { + final value = _subDescriptions; + if (value == null) return null; + if (_subDescriptions is EqualUnmodifiableListView) return _subDescriptions; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'DescriptionModel(text: $text, type: $type, isBold: $isBold, subDescriptions: $subDescriptions)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DescriptionModelImpl && + (identical(other.text, text) || other.text == text) && + (identical(other.type, type) || other.type == type) && + (identical(other.isBold, isBold) || other.isBold == isBold) && + const DeepCollectionEquality() + .equals(other._subDescriptions, _subDescriptions)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, text, type, isBold, + const DeepCollectionEquality().hash(_subDescriptions)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DescriptionModelImplCopyWith<_$DescriptionModelImpl> get copyWith => + __$$DescriptionModelImplCopyWithImpl<_$DescriptionModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$DescriptionModelImplToJson( + this, + ); + } +} + +abstract class _DescriptionModel implements DescriptionModel { + const factory _DescriptionModel( + {final String? text, + final String? type, + final bool? isBold, + final List? subDescriptions}) = + _$DescriptionModelImpl; + + factory _DescriptionModel.fromJson(Map json) = + _$DescriptionModelImpl.fromJson; + + @override + String? get text; + @override + String? get type; + @override + bool? get isBold; + @override + List? get subDescriptions; + @override + @JsonKey(ignore: true) + _$$DescriptionModelImplCopyWith<_$DescriptionModelImpl> get copyWith => + throw _privateConstructorUsedError; +} + +SubDescriptionModel _$SubDescriptionModelFromJson(Map json) { + return _SubDescriptionModel.fromJson(json); +} + +/// @nodoc +mixin _$SubDescriptionModel { + String? get text => throw _privateConstructorUsedError; + String? get type => throw _privateConstructorUsedError; + bool? get isBold => throw _privateConstructorUsedError; + bool? get isSpaceRequired => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $SubDescriptionModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SubDescriptionModelCopyWith<$Res> { + factory $SubDescriptionModelCopyWith( + SubDescriptionModel value, $Res Function(SubDescriptionModel) then) = + _$SubDescriptionModelCopyWithImpl<$Res, SubDescriptionModel>; + @useResult + $Res call({String? text, String? type, bool? isBold, bool? isSpaceRequired}); +} + +/// @nodoc +class _$SubDescriptionModelCopyWithImpl<$Res, $Val extends SubDescriptionModel> + implements $SubDescriptionModelCopyWith<$Res> { + _$SubDescriptionModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = freezed, + Object? type = freezed, + Object? isBold = freezed, + Object? isSpaceRequired = freezed, + }) { + return _then(_value.copyWith( + text: freezed == text + ? _value.text + : text // ignore: cast_nullable_to_non_nullable + as String?, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String?, + isBold: freezed == isBold + ? _value.isBold + : isBold // ignore: cast_nullable_to_non_nullable + as bool?, + isSpaceRequired: freezed == isSpaceRequired + ? _value.isSpaceRequired + : isSpaceRequired // ignore: cast_nullable_to_non_nullable + as bool?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$SubDescriptionModelImplCopyWith<$Res> + implements $SubDescriptionModelCopyWith<$Res> { + factory _$$SubDescriptionModelImplCopyWith(_$SubDescriptionModelImpl value, + $Res Function(_$SubDescriptionModelImpl) then) = + __$$SubDescriptionModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String? text, String? type, bool? isBold, bool? isSpaceRequired}); +} + +/// @nodoc +class __$$SubDescriptionModelImplCopyWithImpl<$Res> + extends _$SubDescriptionModelCopyWithImpl<$Res, _$SubDescriptionModelImpl> + implements _$$SubDescriptionModelImplCopyWith<$Res> { + __$$SubDescriptionModelImplCopyWithImpl(_$SubDescriptionModelImpl _value, + $Res Function(_$SubDescriptionModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = freezed, + Object? type = freezed, + Object? isBold = freezed, + Object? isSpaceRequired = freezed, + }) { + return _then(_$SubDescriptionModelImpl( + text: freezed == text + ? _value.text + : text // ignore: cast_nullable_to_non_nullable + as String?, + type: freezed == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String?, + isBold: freezed == isBold + ? _value.isBold + : isBold // ignore: cast_nullable_to_non_nullable + as bool?, + isSpaceRequired: freezed == isSpaceRequired + ? _value.isSpaceRequired + : isSpaceRequired // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$SubDescriptionModelImpl implements _SubDescriptionModel { + const _$SubDescriptionModelImpl( + {this.text, this.type, this.isBold, this.isSpaceRequired}); + + factory _$SubDescriptionModelImpl.fromJson(Map json) => + _$$SubDescriptionModelImplFromJson(json); + + @override + final String? text; + @override + final String? type; + @override + final bool? isBold; + @override + final bool? isSpaceRequired; + + @override + String toString() { + return 'SubDescriptionModel(text: $text, type: $type, isBold: $isBold, isSpaceRequired: $isSpaceRequired)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SubDescriptionModelImpl && + (identical(other.text, text) || other.text == text) && + (identical(other.type, type) || other.type == type) && + (identical(other.isBold, isBold) || other.isBold == isBold) && + (identical(other.isSpaceRequired, isSpaceRequired) || + other.isSpaceRequired == isSpaceRequired)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => + Object.hash(runtimeType, text, type, isBold, isSpaceRequired); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$SubDescriptionModelImplCopyWith<_$SubDescriptionModelImpl> get copyWith => + __$$SubDescriptionModelImplCopyWithImpl<_$SubDescriptionModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$SubDescriptionModelImplToJson( + this, + ); + } +} + +abstract class _SubDescriptionModel implements SubDescriptionModel { + const factory _SubDescriptionModel( + {final String? text, + final String? type, + final bool? isBold, + final bool? isSpaceRequired}) = _$SubDescriptionModelImpl; + + factory _SubDescriptionModel.fromJson(Map json) = + _$SubDescriptionModelImpl.fromJson; + + @override + String? get text; + @override + String? get type; + @override + bool? get isBold; + @override + bool? get isSpaceRequired; + @override + @JsonKey(ignore: true) + _$$SubDescriptionModelImplCopyWith<_$SubDescriptionModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.g.dart b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.g.dart new file mode 100644 index 000000000..a40bc1b49 --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/models/privacy_notice/privacy_notice_model.g.dart @@ -0,0 +1,79 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'privacy_notice_model.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$PrivacyPolicyModelImpl _$$PrivacyPolicyModelImplFromJson( + Map json) => + _$PrivacyPolicyModelImpl( + header: json['header'] as String, + module: json['module'] as String, + active: json['active'] as bool?, + contents: (json['contents'] as List?) + ?.map((e) => ContentModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$PrivacyPolicyModelImplToJson( + _$PrivacyPolicyModelImpl instance) => + { + 'header': instance.header, + 'module': instance.module, + 'active': instance.active, + 'contents': instance.contents, + }; + +_$ContentModelImpl _$$ContentModelImplFromJson(Map json) => + _$ContentModelImpl( + header: json['header'] as String?, + descriptions: (json['descriptions'] as List?) + ?.map((e) => DescriptionModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$ContentModelImplToJson(_$ContentModelImpl instance) => + { + 'header': instance.header, + 'descriptions': instance.descriptions, + }; + +_$DescriptionModelImpl _$$DescriptionModelImplFromJson( + Map json) => + _$DescriptionModelImpl( + text: json['text'] as String?, + type: json['type'] as String?, + isBold: json['isBold'] as bool?, + subDescriptions: (json['subDescriptions'] as List?) + ?.map((e) => SubDescriptionModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$DescriptionModelImplToJson( + _$DescriptionModelImpl instance) => + { + 'text': instance.text, + 'type': instance.type, + 'isBold': instance.isBold, + 'subDescriptions': instance.subDescriptions, + }; + +_$SubDescriptionModelImpl _$$SubDescriptionModelImplFromJson( + Map json) => + _$SubDescriptionModelImpl( + text: json['text'] as String?, + type: json['type'] as String?, + isBold: json['isBold'] as bool?, + isSpaceRequired: json['isSpaceRequired'] as bool?, + ); + +Map _$$SubDescriptionModelImplToJson( + _$SubDescriptionModelImpl instance) => + { + 'text': instance.text, + 'type': instance.type, + 'isBold': instance.isBold, + 'isSpaceRequired': instance.isSpaceRequired, + }; diff --git a/apps/health_campaign_field_worker_app/lib/pages/authenticated.dart b/apps/health_campaign_field_worker_app/lib/pages/authenticated.dart index 3cb217497..1f7baf504 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/authenticated.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/authenticated.dart @@ -55,10 +55,11 @@ class AuthenticatedPageWrapper extends StatelessWidget { if (selectedBoundary == null) { return const SizedBox.shrink(); } else { + LocalizationParams() + .setCode([selectedBoundary.code!]); final boundaryName = AppLocalizations.of(context).translate( - selectedBoundary.name ?? - selectedBoundary.code ?? + selectedBoundary.code ?? i18.projectSelection.onProjectMapped, ); diff --git a/apps/health_campaign_field_worker_app/lib/pages/boundary_selection.dart b/apps/health_campaign_field_worker_app/lib/pages/boundary_selection.dart index d7fc98e1d..a4acf7a33 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/boundary_selection.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/boundary_selection.dart @@ -12,8 +12,11 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:reactive_forms/reactive_forms.dart'; import '../blocs/app_initialization/app_initialization.dart'; +import '../blocs/localization/localization.dart'; import '../blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart'; import '../blocs/sync/sync.dart'; +import '../data/local_store/app_shared_preferences.dart'; +import '../data/local_store/no_sql/schema/app_configuration.dart'; import '../models/entities/roles_type.dart'; import '../router/app_router.dart'; import '../utils/i18_key_constants.dart' as i18; @@ -45,6 +48,7 @@ class _BoundarySelectionPageState @override void initState() { + LocalizationParams().setModule('common', false); context.read().add(SyncRefreshEvent(context.loggedInUserUuid)); context.read().add( const DownSyncResetStateEvent(), @@ -77,29 +81,45 @@ class _BoundarySelectionPageState return PopScope( canPop: shouldPop, - child: BlocBuilder( - builder: (context, state) { - final selectedBoundary = state.selectedBoundaryMap.entries - .lastWhereOrNull((element) => element.value != null); - - return Scaffold( - body: Builder( - builder: (context) { - if (state.loading) { - return const Center( - child: CircularProgressIndicator(), - ); - } - - final labelList = state.selectedBoundaryMap.keys.toList(); - - return BlocBuilder( - builder: (ctx, initState) { - return initState.maybeWhen( - orElse: () => const Offstage(), - initialized: (appConfiguration, _) => ReactiveFormBuilder( - form: () => buildForm(state), + child: BlocBuilder( + builder: (context, initState) { + return BlocBuilder( + builder: (context, state) { + final selectedBoundary = state.selectedBoundaryMap.entries + .lastWhereOrNull((element) => element.value != null); + return Scaffold( + body: Builder( + builder: (context) { + if (state.loading) { + return const Center( + child: CircularProgressIndicator(), + ); + } + + final labelList = state.selectedBoundaryMap.keys.toList(); + + return initState.maybeWhen( + orElse: () => const Offstage(), + initialized: (appConfiguration, _, __) => + BlocListener( + listener: (context, state) { + if (state.boundaryList.isNotEmpty) { + final finalCodes = + state.boundaryList.map((e) => e.code!).toList(); + LocalizationParams().setCode(finalCodes); + context.read().add( + LocalizationEvent.onUpdateLocalizationIndex( + index: appConfiguration.languages!.indexWhere( + (element) => + element.value == + AppSharedPreferences() + .getSelectedLocale), + code: AppSharedPreferences() + .getSelectedLocale!)); + } + }, + child: ReactiveFormBuilder( + form: () => buildForm(state, appConfiguration), builder: (context, form, child) => Column( children: [ Expanded( @@ -111,7 +131,6 @@ class _BoundarySelectionPageState final filteredItems = state.boundaryList.where((element) { if (element.label != label) return false; - if (labelIndex == 0) return true; final parentIndex = labelIndex - 1; @@ -142,9 +161,7 @@ class _BoundarySelectionPageState formControlName: label, valueMapper: (value) { return localizations.translate( - value.name ?? - value.code ?? - 'No Value'); + value.code ?? 'No Value'); }, onFieldTap: (value) { setState(() { @@ -153,7 +170,6 @@ class _BoundarySelectionPageState }, onSelected: (value) { if (value == null) return; - context.read().add( BoundarySearchEvent( boundaryNum: @@ -187,298 +203,321 @@ class _BoundarySelectionPageState BlocListener( listener: (context, downSyncState) { - downSyncState.maybeWhen( - orElse: () => false, - loading: (isPop) => { - if (isPop) - { - Navigator.of( - context, - rootNavigator: true, - ).popUntil( - (route) => route is! PopupRoute, + LocalizationParams() + .setModule('boundary', true); + context.read().add( + LocalizationEvent.onUpdateLocalizationIndex( + index: appConfiguration.languages! + .indexWhere((element) => + element.value == + AppSharedPreferences() + .getSelectedLocale), + code: AppSharedPreferences() + .getSelectedLocale!)); + Future.delayed(const Duration(milliseconds: 10), + () { + downSyncState.maybeWhen( + orElse: () => false, + loading: (isPop) => { + if (isPop) + { + Navigator.of( + context, + rootNavigator: true, + ).popUntil( + (route) => route is! PopupRoute, + ), + }, + DigitSyncDialog.show( + context, + type: DigitSyncDialogType.inProgress, + label: localizations.translate( + i18.beneficiaryDetails + .dataDownloadInProgress, ), - }, - DigitSyncDialog.show( - context, - type: DigitSyncDialogType.inProgress, - label: localizations.translate( - i18.beneficiaryDetails - .dataDownloadInProgress, + barrierDismissible: false, ), - barrierDismissible: false, - ), - }, - getBatchSize: ( - batchSize, - projectId, - boundaryCode, - pendingSyncCount, - boundaryName, - ) => - context - .read() - .add( - DownSyncCheckTotalCountEvent( - projectId: context.projectId, - boundaryCode: selectedBoundary! - .value!.code - .toString(), - pendingSyncCount: - pendingSyncCount, - boundaryName: selectedBoundary - .value!.name - .toString(), - batchSize: batchSize, + }, + getBatchSize: ( + batchSize, + projectId, + boundaryCode, + pendingSyncCount, + boundaryName, + ) => + context + .read() + .add( + DownSyncCheckTotalCountEvent( + projectId: context.projectId, + boundaryCode: selectedBoundary! + .value!.code + .toString(), + pendingSyncCount: + pendingSyncCount, + boundaryName: selectedBoundary + .value!.name + .toString(), + batchSize: batchSize, + ), ), - ), - pendingSync: () => showDownloadDialog( - context, - model: DownloadBeneficiary( - title: localizations.translate( - i18.syncDialog.pendingSyncLabel, - ), - projectId: context.projectId, - appConfiguartion: appConfiguration, - boundary: selectedBoundary!.value!.code - .toString(), - content: localizations.translate( - i18.syncDialog.pendingSyncContent, - ), - primaryButtonLabel: - localizations.translate( - i18.acknowledgementSuccess.goToHome, - ), - boundaryName: selectedBoundary.value!.name - .toString(), - ), - dialogType: - DigitProgressDialogType.pendingSync, - isPop: true, - ), - dataFound: (initialServerCount, batchSize) { - clickedStatus.value = false; - showDownloadDialog( + pendingSync: () => showDownloadDialog( context, model: DownloadBeneficiary( title: localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails.dataFound - : i18.beneficiaryDetails - .noDataFound, + i18.syncDialog.pendingSyncLabel, ), - appConfiguartion: appConfiguration, projectId: context.projectId, + appConfiguartion: appConfiguration, boundary: selectedBoundary!.value!.code .toString(), - batchSize: batchSize, - totalCount: initialServerCount, content: localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails - .dataFoundContent - : i18.beneficiaryDetails - .noDataFoundContent, + i18.syncDialog.pendingSyncContent, ), primaryButtonLabel: localizations.translate( - initialServerCount > 0 - ? i18.common.coreCommonDownload - : i18.common.coreCommonGoback, - ), - secondaryButtonLabel: - localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails - .proceedWithoutDownloading - : i18.acknowledgementSuccess - .goToHome, + i18.acknowledgementSuccess.goToHome, ), boundaryName: selectedBoundary .value!.name .toString(), ), dialogType: - DigitProgressDialogType.dataFound, + DigitProgressDialogType.pendingSync, isPop: true, - ); - }, - inProgress: (syncCount, totalCount) { - downloadProgress.add( - min( - (syncCount) / (totalCount), - 1, - ), - ); - if (syncCount < 1) { + ), + dataFound: (initialServerCount, batchSize) { + clickedStatus.value = false; showDownloadDialog( context, model: DownloadBeneficiary( title: localizations.translate( - i18.beneficiaryDetails - .dataDownloadInProgress, + initialServerCount > 0 + ? i18.beneficiaryDetails + .dataFound + : i18.beneficiaryDetails + .noDataFound, ), + appConfiguartion: appConfiguration, projectId: context.projectId, boundary: selectedBoundary! .value!.code .toString(), - appConfiguartion: appConfiguration, - syncCount: syncCount, - totalCount: totalCount, - prefixLabel: syncCount.toString(), - suffixLabel: totalCount.toString(), + batchSize: batchSize, + totalCount: initialServerCount, + content: localizations.translate( + initialServerCount > 0 + ? i18.beneficiaryDetails + .dataFoundContent + : i18.beneficiaryDetails + .noDataFoundContent, + ), + primaryButtonLabel: + localizations.translate( + initialServerCount > 0 + ? i18.common.coreCommonDownload + : i18.common.coreCommonGoback, + ), + secondaryButtonLabel: + localizations.translate( + initialServerCount > 0 + ? i18.beneficiaryDetails + .proceedWithoutDownloading + : i18.acknowledgementSuccess + .goToHome, + ), boundaryName: selectedBoundary .value!.name .toString(), ), dialogType: - DigitProgressDialogType.inProgress, + DigitProgressDialogType.dataFound, isPop: true, - downloadProgressController: - downloadProgress, ); - } - }, - success: (result) { - int? epochTime = result.lastSyncedTime; - - String date = - '${DigitDateUtils.getTimeFromTimestamp(epochTime!)} on ${DigitDateUtils.getDateFromTimestamp(epochTime)}'; - String dataDescription = - "${localizations.translate( - i18.beneficiaryDetails.downloadreport, - )}\n\n\n${localizations.translate( - i18.beneficiaryDetails.boundary, - )} ${result.boundaryName}\n${localizations.translate( - i18.beneficiaryDetails.status, - )} ${localizations.translate( - i18.beneficiaryDetails.downloadcompleted, - )}\n${localizations.translate( - i18.beneficiaryDetails.downloadedon, - )} $date\n${localizations.translate( - i18.beneficiaryDetails.recordsdownload, - )} ${result.totalCount}/${result.totalCount}"; - Navigator.of( - context, - rootNavigator: true, - ).popUntil( - (route) => route is! PopupRoute, - ); - context.router - .popAndPush((AcknowledgementRoute( - isDataRecordSuccess: true, - description: dataDescription, - label: localizations.translate(i18 - .acknowledgementSuccess - .dataDownloadedSuccessLabel), - descriptionTableData: { - localizations.translate( - i18.beneficiaryDetails.boundary, - ): result.boundaryName!, - localizations.translate( - i18.beneficiaryDetails.status, - ): localizations.translate( - i18.beneficiaryDetails - .downloadcompleted, + }, + inProgress: (syncCount, totalCount) { + downloadProgress.add( + min( + (syncCount) / (totalCount), + 1, ), - localizations.translate( - i18.beneficiaryDetails.downloadtime, - ): date, - localizations.translate( - i18.beneficiaryDetails - .totalrecorddownload, - ): '${result.totalCount}/${result.totalCount}', - }, - ))); - }, - failed: () => showDownloadDialog( - context, - model: DownloadBeneficiary( - title: localizations.translate( - i18.common.coreCommonDownloadFailed, - ), - appConfiguartion: appConfiguration, - projectId: context.projectId, - pendingSyncCount: pendingSyncCount, - boundary: selectedBoundary!.value!.code - .toString(), - content: localizations.translate( - i18.beneficiaryDetails.dataFoundContent, - ), - primaryButtonLabel: + ); + if (syncCount < 1) { + showDownloadDialog( + context, + model: DownloadBeneficiary( + title: localizations.translate( + i18.beneficiaryDetails + .dataDownloadInProgress, + ), + projectId: context.projectId, + boundary: selectedBoundary! + .value!.code + .toString(), + appConfiguartion: appConfiguration, + syncCount: syncCount, + totalCount: totalCount, + prefixLabel: syncCount.toString(), + suffixLabel: totalCount.toString(), + boundaryName: selectedBoundary + .value!.name + .toString(), + ), + dialogType: DigitProgressDialogType + .inProgress, + isPop: true, + downloadProgressController: + downloadProgress, + ); + } + }, + success: (result) { + int? epochTime = result.lastSyncedTime; + + String date = + '${DigitDateUtils.getTimeFromTimestamp(epochTime!)} on ${DigitDateUtils.getDateFromTimestamp(epochTime)}'; + String dataDescription = + "${localizations.translate( + i18.beneficiaryDetails.downloadreport, + )}\n\n\n${localizations.translate( + i18.beneficiaryDetails.boundary, + )} ${result.boundaryName}\n${localizations.translate( + i18.beneficiaryDetails.status, + )} ${localizations.translate( + i18.beneficiaryDetails + .downloadcompleted, + )}\n${localizations.translate( + i18.beneficiaryDetails.downloadedon, + )} $date\n${localizations.translate( + i18.beneficiaryDetails.recordsdownload, + )} ${result.totalCount}/${result.totalCount}"; + Navigator.of( + context, + rootNavigator: true, + ).popUntil( + (route) => route is! PopupRoute, + ); + context.router + .popAndPush((AcknowledgementRoute( + isDataRecordSuccess: true, + description: dataDescription, + label: localizations.translate(i18 + .acknowledgementSuccess + .dataDownloadedSuccessLabel), + descriptionTableData: { localizations.translate( - i18.syncDialog.retryButtonLabel, - ), - secondaryButtonLabel: + i18.beneficiaryDetails.boundary, + ): result.boundaryName!, localizations.translate( - i18.beneficiaryDetails - .proceedWithoutDownloading, - ), - boundaryName: selectedBoundary.value!.name - .toString(), - ), - dialogType: DigitProgressDialogType.failed, - isPop: true, - ), - totalCountCheckFailed: () => - showDownloadDialog( - context, - model: DownloadBeneficiary( - title: localizations.translate( - i18.beneficiaryDetails - .unableToCheckDataInServer, - ), - appConfiguartion: appConfiguration, - projectId: context.projectId, - pendingSyncCount: pendingSyncCount, - boundary: selectedBoundary!.value!.code - .toString(), - primaryButtonLabel: + i18.beneficiaryDetails.status, + ): localizations.translate( + i18.beneficiaryDetails + .downloadcompleted, + ), localizations.translate( - i18.syncDialog.retryButtonLabel, - ), - secondaryButtonLabel: + i18.beneficiaryDetails.downloadtime, + ): date, localizations.translate( - i18.beneficiaryDetails - .proceedWithoutDownloading, + i18.beneficiaryDetails + .totalrecorddownload, + ): '${result.totalCount}/${result.totalCount}', + }, + ))); + }, + failed: () => showDownloadDialog( + context, + model: DownloadBeneficiary( + title: localizations.translate( + i18.common.coreCommonDownloadFailed, + ), + appConfiguartion: appConfiguration, + projectId: context.projectId, + pendingSyncCount: pendingSyncCount, + boundary: selectedBoundary!.value!.code + .toString(), + content: localizations.translate( + i18.beneficiaryDetails + .dataFoundContent, + ), + primaryButtonLabel: + localizations.translate( + i18.syncDialog.retryButtonLabel, + ), + secondaryButtonLabel: + localizations.translate( + i18.beneficiaryDetails + .proceedWithoutDownloading, + ), + boundaryName: selectedBoundary + .value!.name + .toString(), ), - boundaryName: selectedBoundary.value!.name - .toString(), + dialogType: + DigitProgressDialogType.failed, + isPop: true, ), - dialogType: - DigitProgressDialogType.checkFailed, - isPop: true, - ), - insufficientStorage: () { - clickedStatus.value = false; - showDownloadDialog( + totalCountCheckFailed: () => + showDownloadDialog( context, model: DownloadBeneficiary( title: localizations.translate( i18.beneficiaryDetails - .insufficientStorage, + .unableToCheckDataInServer, ), - content: localizations.translate(i18 - .beneficiaryDetails - .insufficientStorageContent), - projectId: context.projectId, appConfiguartion: appConfiguration, + projectId: context.projectId, + pendingSyncCount: pendingSyncCount, boundary: selectedBoundary!.value!.code .toString(), primaryButtonLabel: localizations.translate( - i18.common.coreCommonOk, + i18.syncDialog.retryButtonLabel, + ), + secondaryButtonLabel: + localizations.translate( + i18.beneficiaryDetails + .proceedWithoutDownloading, ), boundaryName: selectedBoundary .value!.name .toString(), ), - dialogType: DigitProgressDialogType - .insufficientStorage, + dialogType: + DigitProgressDialogType.checkFailed, isPop: true, - ); - }, - ); + ), + insufficientStorage: () { + clickedStatus.value = false; + showDownloadDialog( + context, + model: DownloadBeneficiary( + title: localizations.translate( + i18.beneficiaryDetails + .insufficientStorage, + ), + content: localizations.translate(i18 + .beneficiaryDetails + .insufficientStorageContent), + projectId: context.projectId, + appConfiguartion: appConfiguration, + boundary: selectedBoundary! + .value!.code + .toString(), + primaryButtonLabel: + localizations.translate( + i18.common.coreCommonOk, + ), + boundaryName: selectedBoundary + .value!.name + .toString(), + ), + dialogType: DigitProgressDialogType + .insufficientStorage, + isPop: true, + ); + }, + ); + }); }, child: DigitCard( margin: const EdgeInsets.fromLTRB( @@ -568,6 +607,19 @@ class _BoundarySelectionPageState } clickedStatus.value = true; + LocalizationParams() + .setModule( + 'boundary', true); + context.read().add(LocalizationEvent.onUpdateLocalizationIndex( + index: appConfiguration + .languages! + .indexWhere((element) => + element + .value == + AppSharedPreferences() + .getSelectedLocale), + code: AppSharedPreferences() + .getSelectedLocale!)); } } }, @@ -584,31 +636,42 @@ class _BoundarySelectionPageState ], ), ), - ); - }, - ); - }, - ), - ); - }, - ), + ), + ); + }, + ), + ); + }, + ); + }), ); } void resetChildDropdowns(String parentLabel, BoundaryState state) { final labelList = state.selectedBoundaryMap.keys.toList(); final parentIndex = labelList.indexOf(parentLabel); - + if (state.boundaryList.isNotEmpty) { + LocalizationParams() + .setCode(state.boundaryList.map((e) => e.code!).toList()); + } for (int i = parentIndex + 1; i < labelList.length; i++) { final label = labelList[i]; formControls[label]?.updateValue(null); } } - FormGroup buildForm(BoundaryState state) { + FormGroup buildForm(BoundaryState state, AppConfiguration appConfiguration) { formControls = {}; final labelList = state.selectedBoundaryMap.keys.toList(); - + if (state.boundaryList.isNotEmpty) { + final finalCodes = state.boundaryList.map((e) => e.code!).toList(); + LocalizationParams().setCode(finalCodes); + context.read().add( + LocalizationEvent.onUpdateLocalizationIndex( + index: appConfiguration.languages!.indexWhere((element) => + element.value == AppSharedPreferences().getSelectedLocale), + code: AppSharedPreferences().getSelectedLocale!)); + } for (final label in labelList) { formControls[label] = FormControl( value: state.selectedBoundaryMap[label], diff --git a/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_boundary_view.dart b/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_boundary_view.dart index d20ed164a..40f2f05f4 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_boundary_view.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_boundary_view.dart @@ -72,7 +72,8 @@ class _ChecklistBoundaryViewPageState i18.householdLocation.administrationAreaFormLabel, ), controller: TextEditingController( - text: context.boundary.name, + text: localizations + .translate(context.boundary.code.toString()), ), ), ], diff --git a/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_view.dart b/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_view.dart index 132fd0b79..8556c1163 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_view.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/checklist/checklist_view.dart @@ -2,6 +2,7 @@ import 'dart:math'; import 'package:digit_components/digit_components.dart'; import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -19,6 +20,7 @@ import '../../widgets/localized.dart'; @RoutePage() class ChecklistViewPage extends LocalizedStatefulWidget { final String? referralClientRefId; + const ChecklistViewPage({ Key? key, this.referralClientRefId, @@ -135,6 +137,16 @@ class _ChecklistViewPageState extends LocalizedState { } } + // Request location from LocationBloc + context.read().add(const LocationEvent.load()); + + // Wait for the location to be obtained + final locationState = + context.read().state; + double? latitude = locationState.latitude; + double? longitude = locationState.longitude; + + final shouldSubmit = await DigitDialog.show( context, options: DigitDialogOptions( @@ -201,7 +213,19 @@ class _ChecklistViewPageState extends LocalizedState { .text .toString() : null, - )); + additionalFields: ServiceAttributesAdditionalFields( + version: 1, + fields: [ + AdditionalField( + 'latitude', latitude, + ), + AdditionalField( + 'longitude', longitude, + ), + ], + ), + ) + ); } context.read().add( @@ -440,6 +464,65 @@ class _ChecklistViewPageState extends LocalizedState { context, ), ), + ]else if (e.dataType == 'Boolean') ...[ + if (!(e.code ?? '').contains('.')) + DigitCard( + child: Column( + children: [ + Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Text( + '${localizations.translate( + '${selectedServiceDefinition?.code}.${e.code}', + )} ${e.required == true ? '*' : ''}', + style: theme.textTheme.headlineSmall, + ), + ], + ), + ), + ), + BlocBuilder( + builder: (context, state) { + return SelectionBox( + //label: e, + allowMultipleSelection: false, + width: 110, + valueMapper: (value) { + return value ? localizations.translate( + i18.common.coreCommonYes, + ) : localizations.translate( + i18.common.coreCommonNo, + ); + }, + initialSelection: controller[index].text=='true' ? [true] : controller[index].text=='false' ?[false] : [], + options: const [true, false], // TODO: need to update + onSelectionChanged: (curValue) { + if(curValue.isNotEmpty){ + context + .read() + .add( + ServiceChecklistEvent( + value: curValue.toString(), + submitTriggered: + submitTriggered, + ), + ); + controller[index].value = TextEditingValue( + text: curValue.first.toString(), + ); + } + + }, + ); + }, + ), + ], + ), + ), ], ]); }), @@ -753,6 +836,64 @@ class _ChecklistViewPageState extends LocalizedState { ), ], ); + } else if (item.dataType == 'Boolean') { + return Column( + children: [ + Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Text( + '${localizations.translate( + '${selectedServiceDefinition?.code}.${item.code}', + )} ${item.required == true ? '*' : ''}', + style: theme.textTheme.headlineSmall, + ), + ], + ), + ), + ), + BlocBuilder( + builder: (context, state) { + return SelectionBox( + //label: e, + allowMultipleSelection: false, + width: 110, + valueMapper: (value) { + return value ? 'Yes' : 'No'; + }, + initialSelection: const [false], + options: const [true, false], + onSelectionChanged: (valuec) { + print(submitTriggered); + print(controller[index].text.split('.').contains(e)); + context.read().add( + ServiceChecklistEvent( + value: valuec.toString(), + submitTriggered: submitTriggered, + ), + ); + final String ele; + var val = controller[index].text.split('.'); + if (val.contains(e)) { + val.remove(e); + ele = val.join("."); + } else { + ele = "${controller[index].text}.$e"; + } + controller[index].value = TextEditingController.fromValue( + TextEditingValue( + text: ele, + ), + ).value; + }, + ); + }, + ), + ], + ); } else { return const SizedBox.shrink(); } @@ -783,8 +924,8 @@ class _ChecklistViewPageState extends LocalizedState { : const DigitColors().white, child: _buildChecklist( matchingChildItem, - initialAttributes?.indexOf(matchingChildItem) ?? - parentIndex, // Pass parentIndex here as we're building at the same level + initialAttributes?.indexOf(matchingChildItem) ?? parentIndex, + // Pass parentIndex here as we're building at the same level selectedServiceDefinition, context, ), diff --git a/apps/health_campaign_field_worker_app/lib/pages/complaints/registration/complaint_type.dart b/apps/health_campaign_field_worker_app/lib/pages/complaints/registration/complaint_type.dart index 92156cf7f..d1f30f77c 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/complaints/registration/complaint_type.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/complaints/registration/complaint_type.dart @@ -128,8 +128,11 @@ class _ComplaintTypePageState extends LocalizedState { builder: (context, state) { return state.maybeWhen( orElse: () => const Offstage(), - initialized: - (appConfiguration, serviceRegistryList) { + initialized: ( + appConfiguration, + serviceRegistryList, + _, + ) { var complaintTypes = appConfiguration .complaintTypes ?.map((e) => e.code) diff --git a/apps/health_campaign_field_worker_app/lib/pages/home.dart b/apps/health_campaign_field_worker_app/lib/pages/home.dart index 53eff59a2..2e6ff96b8 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/home.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/home.dart @@ -2,16 +2,23 @@ import 'dart:async'; import 'package:attendance_management/attendance_management.dart'; import 'package:attendance_management/router/attendance_router.gm.dart'; +import 'package:closed_household/closed_household.dart'; +import 'package:closed_household/router/closed_household_router.gm.dart'; import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_components/widgets/atoms/digit_toaster.dart'; import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/data/local_store/no_sql/schema/dashboard_config_schema.dart'; +import 'package:digit_dss/models/entities/dashboard_response_model.dart'; +import 'package:digit_dss/router/dashboard_router.gm.dart'; +import 'package:digit_dss/utils/utils.dart'; import 'package:drift_db_viewer/drift_db_viewer.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:health_campaign_field_worker_app/data/local_store/no_sql/schema/service_registry.dart'; import 'package:inventory_management/inventory_management.dart'; import 'package:inventory_management/router/inventory_router.gm.dart'; import 'package:referral_reconciliation/referral_reconciliation.dart'; @@ -21,7 +28,9 @@ import 'package:registration_delivery/router/registration_delivery_router.gm.dar import '../blocs/app_initialization/app_initialization.dart'; import '../blocs/auth/auth.dart'; +import '../blocs/localization/localization.dart'; import '../blocs/sync/sync.dart'; +import '../data/local_store/app_shared_preferences.dart'; import '../data/local_store/no_sql/schema/app_configuration.dart'; import '../data/local_store/secure_store/secure_store.dart'; import '../models/entities/roles_type.dart'; @@ -92,7 +101,6 @@ class _HomePageState extends LocalizedState { return e.code; }); - //[TODO: Add below roles to enum] if (!(roles.contains(RolesType.distributor.toValue()) || roles.contains(RolesType.registrar.toValue()))) { skipProgressBar = true; @@ -181,7 +189,7 @@ class _HomePageState extends LocalizedState { state.maybeWhen( orElse: () => null, syncInProgress: () async { - await localSecureStore.setManualSyncTrigger(false); + await localSecureStore.setManualSyncTrigger(true); if (context.mounted) { DigitSyncDialog.show( context, @@ -315,6 +323,16 @@ class _HomePageState extends LocalizedState { final Map homeItemsMap = { // INFO : Need to add home items of package Here + i18.home.dashboard: homeShowcaseData.dashBoard.buildWith( + child: HomeItemCard( + icon: Icons.bar_chart_sharp, + label: i18.home.dashboard, + onPressed: () { + context.router.push(const UserDashboardRoute()); + }, + ), + ), + i18.home.beneficiaryLabel: homeShowcaseData.distributorBeneficiaries.buildWith( child: HomeItemCard( @@ -325,6 +343,18 @@ class _HomePageState extends LocalizedState { }, ), ), + i18.home.closedHouseHoldLabel: homeShowcaseData.closedHouseHold.buildWith( + child: HomeItemCard( + icon: Icons.home, + enableCustomIcon: true, + customIconSize: 48, + customIcon: Constants.closedHouseholdSvg, + label: i18.home.closedHouseHoldLabel, + onPressed: () { + context.router.push(const ClosedHouseholdWrapperRoute()); + }, + ), + ), i18.home.manageStockLabel: homeShowcaseData.warehouseManagerManageStock.buildWith( child: HomeItemCard( @@ -333,7 +363,11 @@ class _HomePageState extends LocalizedState { onPressed: () { context.read().state.maybeWhen( orElse: () {}, - initialized: (AppConfiguration appConfiguration, _) { + initialized: ( + AppConfiguration appConfiguration, + _, + __, + ) { context.router.push(ManageStocksRoute()); }, ); @@ -404,7 +438,11 @@ class _HomePageState extends LocalizedState { onPressed: () async { context.read().state.maybeWhen( orElse: () {}, - initialized: (AppConfiguration appConfiguration, _) { + initialized: ( + AppConfiguration appConfiguration, + _, + __, + ) { context.router.push(SearchReferralReconciliationsRoute()); }, ); @@ -445,18 +483,12 @@ class _HomePageState extends LocalizedState { }, ), ), - i18.home.db: homeShowcaseData.db.buildWith( + i18.home.dashboard: homeShowcaseData.dashBoard.buildWith( child: HomeItemCard( - icon: Icons.table_chart, - label: i18.home.db, + icon: Icons.bar_chart_sharp, + label: i18.home.dashboard, onPressed: () { - Navigator.of(context).push( - MaterialPageRoute( - builder: (context) => DriftDbViewer( - context.read(), - ), - ), - ); + context.router.push(const UserDashboardRoute()); }, ), ), @@ -480,11 +512,15 @@ class _HomePageState extends LocalizedState { i18.home.manageAttendanceLabel: homeShowcaseData.manageAttendance.showcaseKey, i18.home.db: homeShowcaseData.db.showcaseKey, + i18.home.closedHouseHoldLabel: + homeShowcaseData.closedHouseHold.showcaseKey, + i18.home.dashboard: homeShowcaseData.dashBoard.showcaseKey, }; final homeItemsLabel = [ // INFO: Need to add items label of package Here i18.home.beneficiaryLabel, + i18.home.closedHouseHoldLabel, i18.home.manageStockLabel, i18.home.stockReconciliationLabel, i18.home.myCheckList, @@ -494,6 +530,7 @@ class _HomePageState extends LocalizedState { i18.home.beneficiaryReferralLabel, i18.home.manageAttendanceLabel, i18.home.db, + i18.home.dashboard, ]; final List filteredLabels = homeItemsLabel @@ -598,9 +635,15 @@ class _HomePageState extends LocalizedState { void setPackagesSingleton(BuildContext context) { context.read().state.maybeWhen( orElse: () {}, - initialized: (AppConfiguration appConfiguration, _) { + initialized: ( + AppConfiguration appConfiguration, + List serviceRegistry, + DashboardConfigSchema? dashboardConfigSchema, + ) { + loadLocalization(context, appConfiguration); // INFO : Need to add singleton of package Here RegistrationDeliverySingleton().setInitialData( + loggedInUser: context.loggedInUserModel, loggedInUserUuid: context.loggedInUserUuid, maxRadius: appConfiguration.maxRadius!, projectId: context.projectId, @@ -623,9 +666,24 @@ void setPackagesSingleton(BuildContext context) { .map((e) => e.code) .toList(), symptomsTypes: - appConfiguration.symptomsTypes!.map((e) => e.code).toList(), + appConfiguration.symptomsTypes?.map((e) => e.code).toList(), + searchHouseHoldFilter: appConfiguration.searchHouseHoldFilters != null + ? appConfiguration.searchHouseHoldFilters! + .map((e) => e.code) + .toList() + : [], referralReasons: - appConfiguration.referralReasons!.map((e) => e.code).toList(), + appConfiguration.referralReasons?.map((e) => e.code).toList(), + houseStructureTypes: + appConfiguration.houseStructureTypes?.map((e) => e.code).toList(), + refusalReasons: + appConfiguration.refusalReasons?.map((e) => e.code).toList(), + ); + + ClosedHouseholdSingleton().setInitialData( + loggedInUserUuid: context.loggedInUserUuid, + projectId: context.projectId, + beneficiaryType: context.beneficiaryType, ); AttendanceSingleton().setInitialData( @@ -670,6 +728,7 @@ void setPackagesSingleton(BuildContext context) { ) .toList() .isNotEmpty, + loggedInUser: context.loggedInUserModel, projectId: context.projectId, loggedInUserUuid: context.loggedInUserUuid, transportTypes: appConfiguration.transportTypes @@ -678,9 +737,30 @@ void setPackagesSingleton(BuildContext context) { ..code = e.code) .toList(), ); + DashboardSingleton().setInitialData( + projectId: context.projectId, + tenantId: envConfig.variables.tenantId, + dashboardConfig: dashboardConfigSchema, + appVersion: Constants().version, + selectedProject: context.selectedProject, + actionPath: Constants.getEndPoint( + serviceRegistry: serviceRegistry, + service: DashboardResponseModel.schemaName.toUpperCase(), + action: ApiOperation.search.toValue(), + entityName: DashboardResponseModel.schemaName, + )); }); } +void loadLocalization( + BuildContext context, AppConfiguration appConfiguration) async { + context.read().add( + LocalizationEvent.onUpdateLocalizationIndex( + index: appConfiguration.languages!.indexWhere((element) => + element.value == AppSharedPreferences().getSelectedLocale), + code: AppSharedPreferences().getSelectedLocale!)); +} + class _HomeItemDataModel { final List homeItems; final List showcaseKeys; diff --git a/apps/health_campaign_field_worker_app/lib/pages/language_selection.dart b/apps/health_campaign_field_worker_app/lib/pages/language_selection.dart index 8214b2477..8c833ffed 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/language_selection.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/language_selection.dart @@ -1,5 +1,6 @@ import 'package:digit_components/digit_components.dart'; import 'package:digit_components/models/digit_row_card/digit_row_card_model.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:package_info_plus/package_info_plus.dart'; @@ -7,14 +8,30 @@ import 'package:package_info_plus/package_info_plus.dart'; import '../blocs/app_initialization/app_initialization.dart'; import '../blocs/localization/app_localization.dart'; import '../blocs/localization/localization.dart'; +import '../data/local_store/app_shared_preferences.dart'; +import '../data/local_store/no_sql/schema/app_configuration.dart'; import '../router/app_router.dart'; -import '../utils/utils.dart'; +import '../utils/constants.dart'; import '../utils/i18_key_constants.dart' as i18; +import '../utils/utils.dart'; @RoutePage() -class LanguageSelectionPage extends StatelessWidget { +class LanguageSelectionPage extends StatefulWidget { const LanguageSelectionPage({super.key}); + @override + _LanguageSelectionPageState createState() => _LanguageSelectionPageState(); +} + +class _LanguageSelectionPageState extends State { + bool isDialogVisible = false; + + @override + void dispose() { + isDialogVisible = false; + super.dispose(); + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -36,8 +53,66 @@ class LanguageSelectionPage extends StatelessWidget { return const Offstage(); } - return BlocBuilder( + return BlocConsumer( + listener: (context, state) { + if (state.loading && !isDialogVisible) { + isDialogVisible = true; + DigitComponentsUtils().showLocalizationLoadingDialog( + context, + DigitSyncDialogType.inProgress, + ); + } else if (!state.loading && isDialogVisible) { + isDialogVisible = false; + DigitComponentsUtils() + .hideLocalizationLoadingDialog(context); + } + if (!state.loading && + !isDialogVisible && + state.retryModule != null) { + DigitSyncDialog.show( + context, + type: DigitSyncDialogType.failed, + label: i18.common.failedToFetch, + primaryAction: DigitDialogActions( + label: AppLocalizations.of(context).translate( + i18.common.coreCommonRetry, + ), + action: (ctx) { + context.read().add( + LocalizationEvent.onLoadLocalization( + module: state.retryModule.toString(), + tenantId: appConfig.tenantId ?? "default", + locale: AppSharedPreferences() + .getSelectedLocale + .toString(), + path: Constants.localizationApiPath)); + Navigator.pop(ctx); + }, + ), + secondaryAction: DigitDialogActions( + label: AppLocalizations.of(context).translate( + i18.common.corecommonclose, + ), + action: (ctx) => Navigator.pop(ctx), + ), + ); + } + }, builder: (context, localizationState) { + if (localizationState.loading && + !isDialogVisible && + mounted && + ModalRoute.of(context)?.isCurrent == true) { + WidgetsBinding.instance.addPostFrameCallback((_) { + isDialogVisible = true; + DigitComponentsUtils().showLocationCapturingDialog( + context, + '', + DigitSyncDialogType.inProgress, + ); + }); + } + return localizationModulesList != null ? DigitLanguageCard( digitRowCardItems: languages.map((e) { @@ -60,25 +135,12 @@ class LanguageSelectionPage extends StatelessWidget { ele.value.toString() == value.value.toString(), ); - - context.read().add( - LocalizationEvent.onLoadLocalization( - module: localizationModulesList - .map((e) => e.name.toString()) - .join(',') - .toString(), - tenantId: appConfig.tenantId ?? "default", - locale: value.value.toString(), - path: Constants.localizationApiPath, - ), - ); - - context.read().add( - OnUpdateLocalizationIndexEvent( - index: index, - code: value.value.toString(), - ), - ); + triggerLanguageChange( + index, + localizationModulesList, + appConfig.tenantId ?? "default", + value.value.toString(), + ); }, onLanguageSubmit: () => context.router.push( LoginRoute(), @@ -96,4 +158,31 @@ class LanguageSelectionPage extends StatelessWidget { ), ); } + + void triggerLanguageChange( + int index, + List localizationModulesList, + String tenantId, + String locale, + ) { + setState(() {}); + context.read().add( + LocalizationEvent.onLoadLocalization( + module: localizationModulesList + .map((e) => e.name.toString()) + .join(',') + .toString(), + tenantId: tenantId, + locale: locale, + path: Constants.localizationApiPath, + ), + ); + + context.read().add( + OnUpdateLocalizationIndexEvent( + index: index, + code: locale, + ), + ); + } } diff --git a/apps/health_campaign_field_worker_app/lib/pages/login.dart b/apps/health_campaign_field_worker_app/lib/pages/login.dart index b87e6b6f5..703eee68c 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/login.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/login.dart @@ -4,11 +4,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:reactive_forms/reactive_forms.dart'; +import '../blocs/app_initialization/app_initialization.dart'; import '../blocs/auth/auth.dart'; +import '../data/local_store/no_sql/schema/app_configuration.dart'; import '../router/app_router.dart'; import '../utils/environment_config.dart'; import '../utils/i18_key_constants.dart' as i18; import '../widgets/localized.dart'; +import '../widgets/privacy_notice/privacy_component.dart'; @RoutePage() class LoginPage extends LocalizedStatefulWidget { @@ -23,8 +26,15 @@ class LoginPage extends LocalizedStatefulWidget { class _LoginPageState extends LocalizedState { var passwordVisible = false; + bool isPrivacyEnabled =false; static const _userId = 'userId'; static const _password = 'password'; + static const _privacyCheck = 'privacyCheck'; + + @override + void initState() { + super.initState(); + } @override Widget build(BuildContext context) { @@ -115,6 +125,31 @@ class _LoginPageState extends LocalizedState { obscureText: !passwordVisible, suffix: buildPasswordVisibility(), ), + BlocBuilder( + builder: (context, initState) { + final privacyPolicyJson = initState.maybeWhen( + initialized: + (AppConfiguration appConfiguration, _, __) => + appConfiguration.privacyPolicyConfig, + orElse: () => null); + if(privacyPolicyJson?.active==false){ + return const SizedBox.shrink(); + } + setState(() { + isPrivacyEnabled = true; + }); + return PrivacyComponent( + privacyPolicy: privacyPolicyJson, + formControlName: _privacyCheck, + text: localizations + .translate(i18.privacyPolicy.privacyNoticeText), + linkText: localizations.translate( + i18.privacyPolicy.privacyPolicyLinkText), + validationMessage: localizations.translate( + i18.privacyPolicy.privacyPolicyValidationText), + ); + }), const SizedBox(height: 16), DigitElevatedButton( onPressed: () { @@ -190,12 +225,16 @@ class _LoginPageState extends LocalizedState { FormGroup buildForm() => fb.group({ _userId: FormControl( - value: '', + value: 'QADistributor', validators: [Validators.required], ), _password: FormControl( validators: [Validators.required], - value: '', + value: 'eGov@1234', ), + _privacyCheck: FormControl( + validators: [Validators.requiredTrue], + value: isPrivacyEnabled ? false : true, + ) }); } diff --git a/apps/health_campaign_field_worker_app/lib/pages/profile.dart b/apps/health_campaign_field_worker_app/lib/pages/profile.dart index 2604031b7..b42a78708 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/profile.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/profile.dart @@ -69,7 +69,11 @@ class _ProfilePageState extends LocalizedState { _genderKey: FormControl( value: context.read().state.maybeWhen( orElse: () => null, - initialized: (appConfiguration, serviceRegistryList) { + initialized: ( + appConfiguration, + serviceRegistryList, + _, + ) { return appConfiguration.genderOptions ?.map((e) => e.code) .firstWhereOrNull((element) => element == user?.gender); @@ -254,7 +258,11 @@ class _ProfilePageState extends LocalizedState { AppInitializationState>( builder: (context, state) => state.maybeWhen( orElse: () => const Offstage(), - initialized: (appConfiguration, _) { + initialized: ( + appConfiguration, + _, + __, + ) { return Column( children: [ Row( diff --git a/apps/health_campaign_field_worker_app/lib/pages/project_facility_selection.dart b/apps/health_campaign_field_worker_app/lib/pages/project_facility_selection.dart index f977f1741..cab08f048 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/project_facility_selection.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/project_facility_selection.dart @@ -5,7 +5,6 @@ import 'package:flutter/material.dart'; import 'package:reactive_forms/reactive_forms.dart'; import '../blocs/localization/app_localization.dart'; -import '../models/data_model.dart'; import '../router/app_router.dart'; import '../utils/i18_key_constants.dart' as i18; import '../widgets/header/back_navigation_help_header.dart'; diff --git a/apps/health_campaign_field_worker_app/lib/pages/reports/beneficiary/beneficaries_report.dart b/apps/health_campaign_field_worker_app/lib/pages/reports/beneficiary/beneficaries_report.dart index 4440e7d0e..4ea93bd81 100644 --- a/apps/health_campaign_field_worker_app/lib/pages/reports/beneficiary/beneficaries_report.dart +++ b/apps/health_campaign_field_worker_app/lib/pages/reports/beneficiary/beneficaries_report.dart @@ -50,8 +50,8 @@ class BeneficiariesReportState extends LocalizedState { @override void deactivate() { context.read().add( - const DownSyncResetStateEvent(), - ); + const DownSyncResetStateEvent(), + ); super.deactivate(); } @@ -64,7 +64,12 @@ class BeneficiariesReportState extends LocalizedState { builder: (ctx, initState) { return initState.maybeWhen( orElse: () => const Offstage(), - initialized: (appConfiguration, _) => ScrollableContent( + initialized: ( + appConfiguration, + _, + __, + ) => + ScrollableContent( footer: SizedBox( child: DigitCard( margin: const EdgeInsets.only(top: kPadding), @@ -109,21 +114,21 @@ class BeneficiariesReportState extends LocalizedState { ), }, getBatchSize: ( - batchSize, - projectId, - boundaryCode, - pendingSync, - boundaryName, - ) => + batchSize, + projectId, + boundaryCode, + pendingSync, + boundaryName, + ) => context.read().add( - DownSyncCheckTotalCountEvent( - projectId: context.projectId, - boundaryCode: boundaryCode, - pendingSyncCount: pendingSyncCount, - boundaryName: boundaryName, - batchSize: batchSize, - ), - ), + DownSyncCheckTotalCountEvent( + projectId: context.projectId, + boundaryCode: boundaryCode, + pendingSyncCount: pendingSyncCount, + boundaryName: boundaryName, + batchSize: batchSize, + ), + ), report: (downSyncCriteriaList) { setState(() { downSyncList = downSyncCriteriaList; @@ -153,39 +158,39 @@ class BeneficiariesReportState extends LocalizedState { ), dataFound: (initialServerCount, batchSize) => showDownloadDialog( - context, - model: DownloadBeneficiary( - title: localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails.dataFound - : i18.beneficiaryDetails.noDataFound, - ), - projectId: context.projectId, - appConfiguartion: appConfiguration, - boundary: selectedBoundary!.code.toString(), - batchSize: 5, - totalCount: initialServerCount, - content: localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails.dataFoundContent - : i18.beneficiaryDetails.noDataFoundContent, - ), - primaryButtonLabel: localizations.translate( - initialServerCount > 0 - ? i18.common.coreCommonDownload - : i18.common.coreCommonGoback, - ), - secondaryButtonLabel: localizations.translate( - initialServerCount > 0 - ? i18.beneficiaryDetails + context, + model: DownloadBeneficiary( + title: localizations.translate( + initialServerCount > 0 + ? i18.beneficiaryDetails.dataFound + : i18.beneficiaryDetails.noDataFound, + ), + projectId: context.projectId, + appConfiguartion: appConfiguration, + boundary: selectedBoundary!.code.toString(), + batchSize: 5, + totalCount: initialServerCount, + content: localizations.translate( + initialServerCount > 0 + ? i18.beneficiaryDetails.dataFoundContent + : i18.beneficiaryDetails.noDataFoundContent, + ), + primaryButtonLabel: localizations.translate( + initialServerCount > 0 + ? i18.common.coreCommonDownload + : i18.common.coreCommonGoback, + ), + secondaryButtonLabel: localizations.translate( + initialServerCount > 0 + ? i18.beneficiaryDetails .proceedWithoutDownloading - : i18.acknowledgementSuccess.goToHome, - ), - boundaryName: selectedBoundary!.name.toString(), - ), - dialogType: DigitProgressDialogType.dataFound, - isPop: true, + : i18.acknowledgementSuccess.goToHome, ), + boundaryName: selectedBoundary!.name.toString(), + ), + dialogType: DigitProgressDialogType.dataFound, + isPop: true, + ), inProgress: (syncCount, totalCount) { downloadProgress.add( min( @@ -320,7 +325,7 @@ class BeneficiariesReportState extends LocalizedState { boundaryName: selectedBoundary!.name.toString(), ), dialogType: - DigitProgressDialogType.insufficientStorage, + DigitProgressDialogType.insufficientStorage, isPop: true, ), ); @@ -339,9 +344,8 @@ class BeneficiariesReportState extends LocalizedState { ), ), ), - ...downSyncList - .map( - (e) => DigitCard( + ...downSyncList.map( + (e) => DigitCard( child: Column( children: [ DigitTableCard( @@ -353,21 +357,20 @@ class BeneficiariesReportState extends LocalizedState { i18.beneficiaryDetails.status, ): e.offset == 0 && e.limit == 0 ? localizations.translate( - i18.beneficiaryDetails - .downloadcompleted, - ) + i18.beneficiaryDetails + .downloadcompleted, + ) : localizations.translate( - i18.beneficiaryDetails - .partialdownloaded, - ), + i18.beneficiaryDetails + .partialdownloaded, + ), localizations.translate( i18.beneficiaryDetails.downloadtime, ): e.lastSyncedTime != null ? '${DigitDateUtils.getTimeFromTimestamp(e.lastSyncedTime!)} on ${DigitDateUtils.getDateFromTimestamp(e.lastSyncedTime!)}' : '--', localizations.translate( - i18.beneficiaryDetails - .totalrecorddownload, + i18.beneficiaryDetails.totalrecorddownload, ): e.offset == 0 && e.limit == 0 ? '${e.totalCount}/${e.totalCount}' : '${e.offset}/${e.totalCount}', @@ -395,35 +398,31 @@ class BeneficiariesReportState extends LocalizedState { name: e.boundaryName, ); }); - context - .read() - .add( - DownSyncGetBatchSizeEvent( - appConfiguration: [ - appConfiguration, - ], - projectId: context.projectId, - boundaryCode: e.locality!, - pendingSyncCount: - pendingSyncCount, - boundaryName: - e.boundaryName.toString(), - ), - ); + context.read().add( + DownSyncGetBatchSizeEvent( + appConfiguration: [ + appConfiguration, + ], + projectId: context.projectId, + boundaryCode: e.locality!, + pendingSyncCount: pendingSyncCount, + boundaryName: + e.boundaryName.toString(), + ), + ); }, ), ], ), ), - ) - , + ), downSyncList.isEmpty ? NoResultCard( - align: Alignment.center, - label: localizations.translate( - i18.common.noResultsFound, - ), - ) + align: Alignment.center, + label: localizations.translate( + i18.common.noResultsFound, + ), + ) : const SizedBox.shrink(), ]), ), @@ -435,4 +434,4 @@ class BeneficiariesReportState extends LocalizedState { ), ); } -} \ No newline at end of file +} diff --git a/apps/health_campaign_field_worker_app/lib/router/app_router.dart b/apps/health_campaign_field_worker_app/lib/router/app_router.dart index 2624a0807..50382946e 100644 --- a/apps/health_campaign_field_worker_app/lib/router/app_router.dart +++ b/apps/health_campaign_field_worker_app/lib/router/app_router.dart @@ -1,7 +1,11 @@ import 'package:attendance_management/router/attendance_router.dart'; import 'package:attendance_management/router/attendance_router.gm.dart'; import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/router/closed_household_router.dart'; +import 'package:closed_household/router/closed_household_router.gm.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/router/dashboard_router.dart'; +import 'package:digit_dss/router/dashboard_router.gm.dart'; import 'package:digit_scanner/router/digit_scanner_router.dart'; import 'package:digit_scanner/router/digit_scanner_router.gm.dart'; import 'package:flutter/material.dart'; @@ -53,6 +57,8 @@ part 'app_router.gr.dart'; ReferralReconciliationRoute, DigitScannerPackageRoute, RegistrationDeliveryRoute, + ClosedHouseholdPackageRoute, + DashboardRoute, ], ) class AppRouter extends _$AppRouter { @@ -85,7 +91,11 @@ class AppRouter extends _$AppRouter { page: BeneficiariesReportRoute.page, path: 'beneficiary-downsync-report', ), - + // DSS Dashboard Routes + AutoRoute( + page: UserDashboardRoute.page, + path: 'dashboard', + ), AutoRoute( page: RegistrationDeliveryWrapperRoute.page, path: 'registration-delivery-wrapper', @@ -106,6 +116,8 @@ class AppRouter extends _$AppRouter { AutoRoute( page: HouseHoldDetailsRoute.page, path: 'household-details'), + AutoRoute( + page: HouseDetailsRoute.page, path: 'house-details'), AutoRoute( page: HouseholdLocationRoute.page, path: 'household-location', @@ -115,6 +127,10 @@ class AppRouter extends _$AppRouter { page: BeneficiaryAcknowledgementRoute.page, path: 'beneficiary-acknowledgement', ), + AutoRoute( + page: SummaryRoute.page, + path: 'beneficiary-summary', + ), ], ), AutoRoute( @@ -126,6 +142,10 @@ class AppRouter extends _$AppRouter { path: 'overview', initial: true, ), + AutoRoute( + page: BeneficiaryChecklistRoute.page, + path: 'beneficiary-checklist', + ), AutoRoute( page: BeneficiaryDetailsRoute.page, path: 'beneficiary-details', @@ -134,6 +154,10 @@ class AppRouter extends _$AppRouter { page: DeliverInterventionRoute.page, path: 'deliver-intervention', ), + AutoRoute( + page: RefusedDeliveryRoute.page, + path: 'refused-delivery', + ), AutoRoute( page: SideEffectsRoute.page, path: 'side-effects', @@ -163,10 +187,32 @@ class AppRouter extends _$AppRouter { path: 'household-acknowledgement', ), AutoRoute(page: ChecklistViewRoute.page, path: 'view'), + AutoRoute( + page: DeliverySummaryRoute.page, + path: 'delivery-summary', + ), ], ), ]), + /// close household + AutoRoute( + page: ClosedHouseholdWrapperRoute.page, + path: 'closed-household-wrapper', + children: [ + AutoRoute( + page: ClosedHouseholdDetailsRoute.page, + path: 'closed-household-details', + initial: true, + ), + AutoRoute( + page: ClosedHouseholdSummaryRoute.page, + path: 'closed-household-summary'), + AutoRoute( + page: ClosedHouseholdAcknowledgementRoute.page, + path: 'closed-household-acknowledgement'), + ]), + AutoRoute( page: ChecklistWrapperRoute.page, path: 'checklist', @@ -193,7 +239,6 @@ class AppRouter extends _$AppRouter { page: ProjectFacilitySelectionRoute.page, path: 'select-project-facilities', ), - AutoRoute( page: FacilitySelectionRoute.page, path: 'select-facilities', diff --git a/apps/health_campaign_field_worker_app/lib/router/app_router.gr.dart b/apps/health_campaign_field_worker_app/lib/router/app_router.gr.dart index f867a8cbf..68d85a6af 100644 --- a/apps/health_campaign_field_worker_app/lib/router/app_router.gr.dart +++ b/apps/health_campaign_field_worker_app/lib/router/app_router.gr.dart @@ -310,6 +310,8 @@ abstract class _$AppRouter extends RootStackRouter { ...ReferralReconciliationRoute().pagesMap, ...DigitScannerPackageRoute().pagesMap, ...RegistrationDeliveryRoute().pagesMap, + ...ClosedHouseholdPackageRoute().pagesMap, + ...DashboardRoute().pagesMap, }; } diff --git a/apps/health_campaign_field_worker_app/lib/utils/background_service.dart b/apps/health_campaign_field_worker_app/lib/utils/background_service.dart index 3da2b7155..6e2a08c2d 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/background_service.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/background_service.dart @@ -62,7 +62,7 @@ Future initializeService(dio, isar) async { AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); } - + requestDisableBatteryOptimization(); await service.configure( androidConfiguration: AndroidConfiguration( // this will be executed when app is in foreground or background in separated isolate @@ -127,6 +127,9 @@ void onStart(ServiceInstance service) async { makePeriodicTimer( Duration(seconds: interval), (timer) async { + service.invoke('serviceRunning', { + "enablesManualSync": false, + }); var battery = Battery(); final int batteryPercent = await battery.batteryLevel; if (batteryPercent <= @@ -137,85 +140,93 @@ void onStart(ServiceInstance service) async { final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); - if (frequencyCount != null) { + final isManualSyncRunning = + await LocalSecureStore.instance.isManualSyncRunning; + if (frequencyCount != null && !isManualSyncRunning) { final serviceRegistryList = await _isar.serviceRegistrys.where().findAll(); if (serviceRegistryList.isNotEmpty) { - final bandwidthPath = serviceRegistryList - .firstWhere((element) => element.service == 'BANDWIDTH-CHECK') - .actions - .first - .path; + final bandwidthService = serviceRegistryList.firstWhereOrNull( + (element) => element.service == 'BANDWIDTH-CHECK', + ); + if (bandwidthService != null) { + final bandwidthPath = bandwidthService.actions.first.path; - List speedArray = []; - for (var i = 0; i < frequencyCount; i++) { - try { - final double speed = await BandwidthCheckRepository( - _dio, - bandwidthPath: bandwidthPath, - ).pingBandwidthCheck(bandWidthCheckModel: null); - speedArray.add(speed); - } catch (e) { - service.invoke('serviceRunning', { - "enablesManualSync": true, - }); - service.stopSelf(); - break; + List speedArray = []; + for (var i = 0; i < frequencyCount; i++) { + try { + final double speed = await BandwidthCheckRepository( + _dio, + bandwidthPath: bandwidthPath, + ).pingBandwidthCheck(bandWidthCheckModel: null); + speedArray.add(speed); + } catch (e) { + service.invoke('serviceRunning', { + "enablesManualSync": true, + }); + service.stopSelf(); + break; + } } - } - double sum = speedArray.fold(0, (p, c) => p + c); + double sum = speedArray.fold(0, (p, c) => p + c); - int configuredBatchSize = getBatchSizeToBandwidth( - sum / speedArray.length, - appConfiguration, - ); - final BandwidthModel bandwidthModel = BandwidthModel.fromJson({ - 'userId': userRequestModel!.uuid, - 'batchSize': configuredBatchSize, - }); - flutterLocalNotificationsPlugin.show( - 888, - 'Auto Sync', - 'Speed : ${speedArray.firstOrNull}Mb/ps - BatchSize : $configuredBatchSize', - const NotificationDetails( - android: AndroidNotificationDetails( - "my_foreground", - 'AUTO SYNC', - icon: 'ic_bg_service_small', - ongoing: true, + int configuredBatchSize = getBatchSizeToBandwidth( + sum / speedArray.length, + appConfiguration, + ); + final BandwidthModel bandwidthModel = BandwidthModel.fromJson({ + 'userId': userRequestModel?.uuid, + 'batchSize': configuredBatchSize, + }); + flutterLocalNotificationsPlugin.show( + 888, + 'Auto Sync', + 'Speed : ${speedArray.isNotEmpty && speedArray.firstOrNull != null ? double.tryParse(speedArray.first.toString())?.toStringAsFixed(2) ?? '0' : '0'}Mb/ps - BatchSize : $configuredBatchSize', + const NotificationDetails( + android: AndroidNotificationDetails( + "my_foreground", + 'AUTO SYNC', + icon: 'ic_bg_service_small', + ongoing: true, + ), ), - ), - ); - final isSyncCompleted = await const NetworkManager( - configuration: NetworkManagerConfiguration( - persistenceConfig: PersistenceConfiguration.offlineFirst, - ), - ).performSync( - localRepositories: Constants.getLocalRepositories( - _sql, - _isar, - ).toList(), - remoteRepositories: Constants.getRemoteRepositories( - _dio, - getActionMap(serviceRegistryList), - ), - bandwidthModel: bandwidthModel, - service: service, - ); + ); + final isSyncCompleted = await const NetworkManager( + configuration: NetworkManagerConfiguration( + persistenceConfig: PersistenceConfiguration.offlineFirst, + ), + ).performSync( + localRepositories: Constants.getLocalRepositories( + _sql, + _isar, + ).toList(), + remoteRepositories: Constants.getRemoteRepositories( + _dio, + getActionMap(serviceRegistryList), + ), + bandwidthModel: bandwidthModel, + service: service, + ); - i++; - final isAppInActive = - await LocalSecureStore.instance.isAppInActive; + i++; + final isAppInActive = + await LocalSecureStore.instance.isAppInActive; - if (isSyncCompleted && i >= 2 && isAppInActive) { - service.stopSelf(); + if (isSyncCompleted && i >= 2 && isAppInActive) { + service.stopSelf(); + } } } } } + service.invoke('serviceRunning', { + "enablesManualSync": true, + }); }, fireNow: true, ); + } else { + service.stopSelf(); } } diff --git a/apps/health_campaign_field_worker_app/lib/utils/constants.dart b/apps/health_campaign_field_worker_app/lib/utils/constants.dart index 8ea41b143..3d05740b3 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/constants.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/constants.dart @@ -1,19 +1,19 @@ import 'package:attendance_management/attendance_management.dart'; +import 'package:closed_household/utils/utils.dart'; import 'package:collection/collection.dart'; import 'package:digit_components/utils/app_logger.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/digit_dss.dart'; +import 'package:digit_firebase_services/digit_firebase_services.dart' + as firebase_services; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:inventory_management/inventory_management.dart'; import 'package:isar/isar.dart'; import 'package:path_provider/path_provider.dart'; import 'package:referral_reconciliation/referral_reconciliation.dart'; -import 'package:referral_reconciliation/utils/utils.dart'; import 'package:registration_delivery/registration_delivery.dart'; -import 'package:digit_firebase_services/digit_firebase_services.dart' - as firebase_services; -import '../blocs/app_initialization/app_initialization.dart'; import '../data/local_store/no_sql/schema/app_configuration.dart'; import '../data/local_store/no_sql/schema/entity_mapper.dart'; import '../data/local_store/no_sql/schema/localization.dart'; @@ -61,6 +61,8 @@ class Constants { OpLogSchema, ProjectTypeListCycleSchema, RowVersionListSchema, + DashboardConfigSchemaSchema, + DashboardResponseSchema, ], name: 'HCM', inspector: true, @@ -78,6 +80,8 @@ class Constants { static const String checklistViewDateFormat = 'dd/MM/yyyy hh:mm a'; static const String healthFacilityChecklistPrefix = 'HF_RF'; + static const String boundaryLocalizationPath = 'rainmaker-boundary-admin'; + static List getLocalRepositories( LocalSqlDataStore sql, Isar isar, @@ -164,6 +168,9 @@ class Constants { _version = version; } + static const String closedHouseholdSvg = + 'assets/icons/svg/closed_household.svg'; + static List getRemoteRepositories( Dio dio, Map> actionMap, @@ -230,12 +237,12 @@ class Constants { } static String getEndPoint({ - required AppInitialized state, + required List serviceRegistry, required String service, required String action, required String entityName, }) { - final actionResult = state.serviceRegistryList + final actionResult = serviceRegistry .firstWhereOrNull((element) => element.service == service) ?.actions .firstWhereOrNull((element) => element.entityName == entityName) @@ -258,6 +265,7 @@ class Constants { errorDumpApiPath: envConfig.variables.dumpErrorApiPath, hierarchyType: envConfig.variables.hierarchyType); RegistrationDeliverySingleton().setTenantId(envConfig.variables.tenantId); + ClosedHouseholdSingleton().setTenantId(envConfig.variables.tenantId); AttendanceSingleton().setTenantId(envConfig.variables.tenantId); ReferralReconSingleton().setTenantId(envConfig.variables.tenantId); InventorySingleton().setTenantId(tenantId: envConfig.variables.tenantId); diff --git a/apps/health_campaign_field_worker_app/lib/utils/extensions/context_utility.dart b/apps/health_campaign_field_worker_app/lib/utils/extensions/context_utility.dart index 50f92e1b9..74935a44d 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/extensions/context_utility.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/extensions/context_utility.dart @@ -101,6 +101,7 @@ extension ContextUtilityExtensions on BuildContext { } // INFO: Set Boundary for packages RegistrationDeliverySingleton().setBoundary(boundary: selectedBoundary); + ClosedHouseholdSingleton().setBoundary(boundary: selectedBoundary); InventorySingleton().setBoundaryName(boundaryName: selectedBoundary.name!); ReferralReconSingleton().setBoundary(boundary: selectedBoundary); return selectedBoundary; @@ -146,6 +147,21 @@ extension ContextUtilityExtensions on BuildContext { return individualUUID; } + UserModel? get loggedInUserModel { + final userRequestModel = loggedInUser; + final userModel = UserModel( + userName: userRequestModel.userName, + name: userRequestModel.name, + uuid: userRequestModel.uuid, + mobileNumber: userRequestModel.mobileNumber, + gender: userRequestModel.gender, + active: userRequestModel.active, + tenantId: userRequestModel.tenantId, + ); + + return userModel; + } + String get loggedInUserUuid => loggedInUser.uuid; UserRequestModel get loggedInUser { diff --git a/apps/health_campaign_field_worker_app/lib/utils/extensions/extensions.dart b/apps/health_campaign_field_worker_app/lib/utils/extensions/extensions.dart index ae6f6bc98..daa11a867 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/extensions/extensions.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/extensions/extensions.dart @@ -1,4 +1,5 @@ // Importing necessary packages and files +import 'package:closed_household/utils/utils.dart'; import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; diff --git a/apps/health_campaign_field_worker_app/lib/utils/i18_key_constants.dart b/apps/health_campaign_field_worker_app/lib/utils/i18_key_constants.dart index aae850231..18305c911 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/i18_key_constants.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/i18_key_constants.dart @@ -11,6 +11,8 @@ const checklist = Checklist(); const complaints = Complaints(); const syncDialog = SyncDialog(); const homeShowcase = HomeShowcase(); +const privacyPolicy = PrivacyPolicy(); +const dashBoard = Dashboard(); const householdLocationShowcase = HouseholdLocationShowcase(); const householdLocation = HouseholdLocation(); @@ -60,6 +62,10 @@ class Common { String get corecommonclose => 'CORE_COMMON_CLOSE'; + String get coreCommonRetry => 'CORE_COMMON_RETRY'; + + String get failedToFetch => 'CORE_COMMON_FAILED_TO_FETCH'; + String get coreCommonOk => 'CORE_COMMON_OK'; String get coreCommonNA => 'CORE_COMMON_NA'; @@ -592,8 +598,11 @@ class Home { String get deleteAllLabel => 'HOME_DELETE_ALL_LABEL'; String get db => 'HOME_DB_LABEL'; + String get dashboard => 'HOME_DASHBOARD_LABEL'; String get beneficiaryReferralLabel => 'HOME_BENEFICIARY_REFERRAL_LABEL'; String get manageAttendanceLabel => 'HOME_MANAGE_ATTENDANCE_LABEL'; + + String get closedHouseHoldLabel => 'HOME_CLOSE_HOUSEHOLD_LABEL'; } class AcknowledgementSuccess { @@ -1031,4 +1040,27 @@ class BeneficiaryDetails { String get insufficientStorageContent => 'INSUFFICIENT_STORAGE_WARNING_CONTENT'; String get recordCycle => 'BENEFICIARY_DETAILS_RECORD_CYCLE'; -} \ No newline at end of file +} + +class PrivacyPolicy { + const PrivacyPolicy(); + + String get acceptText { + return 'PRIVACY_POLICY_ACCEPT_TEXT'; + } + + String get declineText { + return 'PRIVACY_POLICY_DECLINE_TEXT'; + } + + String get privacyNoticeText => 'PRIVACY_POLICY_TEXT'; + String get privacyPolicyLinkText => 'PRIVACY_POLICY_LINK_TEXT'; + String get privacyPolicyValidationText => 'PRIVACY_POLICY_VALIDATION_TEXT'; + +} + +class Dashboard { + const Dashboard(); + + String get dashboardHeaderLabel => 'DASHBOARD_HEADER'; +} diff --git a/apps/health_campaign_field_worker_app/lib/utils/localization_delegates.dart b/apps/health_campaign_field_worker_app/lib/utils/localization_delegates.dart index d6a5936b3..6e62855fe 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/localization_delegates.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/localization_delegates.dart @@ -1,68 +1,64 @@ -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:isar/isar.dart'; +import 'dart:ui'; + import 'package:attendance_management/blocs/app_localization.dart' as attendance_localization; +import 'package:closed_household/blocs/app_localization.dart' + as closed_household_localization; +import 'package:digit_data_model/data/local_store/sql_store/sql_store.dart'; +import 'package:digit_dss/blocs/app_localization.dart' + as digit_dss_localization; import 'package:digit_scanner/blocs/app_localization.dart' as scanner_localization; -import 'package:referral_reconciliation/blocs/app_localization.dart' - as referral_reconciliation_localization; +import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:inventory_management/blocs/app_localization.dart' as inventory_localization; +import 'package:referral_reconciliation/blocs/app_localization.dart' + as referral_reconciliation_localization; import 'package:registration_delivery/blocs/app_localization.dart' as registration_delivery_localization; import '../blocs/localization/app_localization.dart'; import '../data/local_store/no_sql/schema/app_configuration.dart'; -import 'utils.dart'; +import '../data/repositories/local/localization.dart'; getAppLocalizationDelegates({ - required Isar isar, + required LocalSqlDataStore sql, required AppConfiguration appConfig, - required String selectedLocale, + required Locale selectedLocale, }) { return [ - AppLocalizations.getDelegate( - appConfig, - isar, - ), + AppLocalizations.getDelegate(appConfig, sql), GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalMaterialLocalizations.delegate, referral_reconciliation_localization.ReferralReconLocalization.getDelegate( - getLocalizationString( - isar, - selectedLocale, - ), + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, appConfig.languages!, ), inventory_localization.InventoryLocalization.getDelegate( - getLocalizationString( - isar, - selectedLocale, - ), + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, appConfig.languages!, ), attendance_localization.AttendanceLocalization.getDelegate( - getLocalizationString( - isar, - selectedLocale, - ), + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, appConfig.languages!, ), scanner_localization.ScannerLocalization.getDelegate( - getLocalizationString( - isar, - selectedLocale, - ), + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, appConfig.languages!, ), registration_delivery_localization.RegistrationDeliveryLocalization .getDelegate( - getLocalizationString( - isar, - selectedLocale, - ), + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, appConfig.languages!, ), + closed_household_localization.ClosedHouseholdLocalization.getDelegate( + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, + appConfig.languages!, + ), + digit_dss_localization.DashboardLocalization.getDelegate( + LocalizationLocalRepository().returnLocalizationFromSQL(sql) as Future, + appConfig.languages!, + ) ]; } diff --git a/apps/health_campaign_field_worker_app/lib/utils/utils.dart b/apps/health_campaign_field_worker_app/lib/utils/utils.dart index eb4ec0a1c..dfda5e62f 100644 --- a/apps/health_campaign_field_worker_app/lib/utils/utils.dart +++ b/apps/health_campaign_field_worker_app/lib/utils/utils.dart @@ -1,10 +1,5 @@ library app_utils; -import 'package:registration_delivery/registration_delivery.init.dart' - as registration_delivery_mappers; -import 'package:digit_data_model/data_model.init.dart' as data_model_mappers; -import 'package:inventory_management/inventory_management.init.dart' - as inventory_mappers; import 'dart:async'; import 'dart:io'; @@ -16,13 +11,20 @@ import 'package:digit_components/widgets/atoms/digit_toaster.dart'; import 'package:digit_components/widgets/digit_dialog.dart'; import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:digit_data_model/data_model.init.dart' as data_model_mappers; +import 'package:digit_dss/digit_dss.dart' as dss_mappers; +import 'package:disable_battery_optimization/disable_battery_optimization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:inventory_management/inventory_management.init.dart' + as inventory_mappers; import 'package:isar/isar.dart'; import 'package:reactive_forms/reactive_forms.dart'; import 'package:referral_reconciliation/referral_reconciliation.dart' as referral_reconciliation_mappers; +import 'package:registration_delivery/registration_delivery.init.dart' + as registration_delivery_mappers; import '../blocs/app_initialization/app_initialization.dart'; import '../blocs/projects_beneficiary_downsync/project_beneficiaries_downsync.dart'; @@ -69,6 +71,15 @@ class CustomValidator { } } +Future requestDisableBatteryOptimization() async { + bool isIgnoringBatteryOptimizations = + await DisableBatteryOptimization.isBatteryOptimizationDisabled ?? false; + + if (!isIgnoringBatteryOptimizations) { + await DisableBatteryOptimization.showDisableBatteryOptimizationSettings(); + } +} + setBgRunning(bool isBgRunning) async { final localSecureStore = LocalSecureStore.instance; await localSecureStore.setBackgroundService(isBgRunning); @@ -104,7 +115,8 @@ performBackgroundService({ } else { if (!isRunning && isOnline) { service.startService(); - if (context != null) { + if (context != null && context.mounted) { + requestDisableBatteryOptimization(); DigitToast.show( context, options: DigitToastOptions( @@ -252,7 +264,7 @@ void showDownloadDialog( ); } else { Navigator.of(context, rootNavigator: true).pop(); - context.router.pop(); + context.router.replaceAll([HomeRoute()]); } }, ), @@ -260,7 +272,7 @@ void showDownloadDialog( label: model.secondaryButtonLabel ?? '', action: (ctx) { Navigator.of(context, rootNavigator: true).pop(); - context.router.pop(); + context.router.replaceAll([HomeRoute()]); }, ), ); @@ -285,7 +297,7 @@ void showDownloadDialog( action: (ctx) { if (dialogType == DigitProgressDialogType.pendingSync) { Navigator.of(context, rootNavigator: true).pop(); - context.router.popUntilRouteWithName(HomeRoute.name); + context.router.replaceAll([HomeRoute()]); } else { if ((model.totalCount ?? 0) > 0) { context.read().add( @@ -310,9 +322,12 @@ void showDownloadDialog( secondaryAction: model.secondaryButtonLabel != null ? DigitDialogActions( label: model.secondaryButtonLabel ?? '', - action: (ctx) { - Navigator.of(context, rootNavigator: true).pop(); - context.router.popUntilRouteWithName(HomeRoute.name); + action: (ctx) async { + await LocalSecureStore.instance.setManualSyncTrigger(false); + if (context.mounted) { + Navigator.of(context, rootNavigator: true).pop(); + context.router.replaceAll([HomeRoute()]); + } }, ) : null, @@ -329,8 +344,7 @@ void showDownloadDialog( label: '', prefixLabel: '', suffixLabel: - '${(snapshot.data == null ? 0 : snapshot.data! * model.totalCount!.toDouble()).toInt()}/${model.suffixLabel}' ?? - '', + '${(snapshot.data == null ? 0 : snapshot.data! * model.totalCount!.toDouble()).toInt()}/${model.suffixLabel}', value: snapshot.data ?? 0, valueColor: AlwaysStoppedAnimation( DigitTheme.instance.colorScheme.secondary, @@ -384,6 +398,7 @@ initializeAllMappers() async { Future(() => inventory_mappers.initializeMappers()), Future(() => data_model_mappers.initializeMappers()), Future(() => registration_delivery_mappers.initializeMappers()), + Future(() => dss_mappers.initializeMappers()), ]; await Future.wait(initializations); } @@ -431,3 +446,44 @@ int getSyncCount(List oplogs) { return count; } + +class LocalizationParams { + static final LocalizationParams _singleton = LocalizationParams._internal(); + + factory LocalizationParams() { + return _singleton; + } + + LocalizationParams._internal(); + + List? _code; + String? _module; + Locale? _locale; + bool? _exclude = true; + + void setCode(List? code) { + _code = code; + } + + void setModule(String? module, bool? exclude) { + _module = module; + _exclude = exclude; + } + + void setLocale(Locale locale) { + _locale = locale; + } + + void clear() { + _code = null; + _module = null; + } + + List? get code => _code; + + String? get module => _module; + + Locale? get locale => _locale; + + bool? get exclude => _exclude; +} diff --git a/apps/health_campaign_field_worker_app/lib/widgets/home/home_item_card.dart b/apps/health_campaign_field_worker_app/lib/widgets/home/home_item_card.dart index 9351bdb7a..6a63e84f5 100644 --- a/apps/health_campaign_field_worker_app/lib/widgets/home/home_item_card.dart +++ b/apps/health_campaign_field_worker_app/lib/widgets/home/home_item_card.dart @@ -9,6 +9,7 @@ class HomeItemCard extends StatelessWidget { final String customIcon; final String label; final VoidCallback? onPressed; + final double? customIconSize; final bool enableCustomIcon; const HomeItemCard({ @@ -16,6 +17,7 @@ class HomeItemCard extends StatelessWidget { required this.label, this.enableCustomIcon = false, this.customIcon = "", + this.customIconSize, this.onPressed, super.key, }); @@ -38,8 +40,8 @@ class HomeItemCard extends StatelessWidget { if (enableCustomIcon) SvgPicture.asset( customIcon, - width: 25, - height: 25, + width: customIconSize ?? 25, + height: customIconSize ?? 25, ), if (!enableCustomIcon) Icon( diff --git a/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_component.dart b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_component.dart new file mode 100644 index 000000000..e246dc30a --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_component.dart @@ -0,0 +1,169 @@ +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import '../../data/local_store/no_sql/schema/app_configuration.dart'; +import '../localized.dart'; +import 'privacy_notice_dialog.dart'; +import 'package:reactive_forms/reactive_forms.dart'; + +class PrivacyComponent extends LocalizedStatefulWidget { + final String formControlName; + final String text; + final String linkText; + final PrivacyPolicy? privacyPolicy; + final String? trailingText; + final String validationMessage; + + const PrivacyComponent({ + super.key, + super.appLocalizations, + required this.formControlName, + required this.text, + required this.linkText, + this.trailingText, + this.privacyPolicy, + required this.validationMessage, + }); + + @override + State createState() => _PrivacyComponentState(); +} + +class _PrivacyComponentState extends LocalizedState { + late ValueNotifier checkboxStateNotifier; + + @override + void initState() { + super.initState(); + checkboxStateNotifier = ValueNotifier(false); + } + + @override + void dispose() { + checkboxStateNotifier.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return ReactiveFormField( + formControlName: widget.formControlName, + builder: (field) { + return ValueListenableBuilder( + valueListenable: checkboxStateNotifier, + builder: (context, value, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + GestureDetector( + onTap: () { + checkboxStateNotifier.value = + !checkboxStateNotifier.value; + field.didChange(checkboxStateNotifier.value); + }, + child: value + ? Container( + width: kPadding*3, + height: kPadding*3, + decoration: BoxDecoration( + border: Border.all( + color: const DigitColors().burningOrange, + width: 2, + ), + borderRadius: BorderRadius.zero, + ), + child: Center( + child: Icon( + Icons.check, + size: kPadding*2, + color: const DigitColors().burningOrange, + ), + ), + ) + : Container( + width: kPadding*3, + height: kPadding*3, + decoration: BoxDecoration( + border: Border.all( + color: const DigitColors().woodsmokeBlack, + width: 1, + ), + borderRadius: BorderRadius.zero, + ), + ), + ), + const SizedBox(width: kPadding), + Expanded( + child: Text.rich( + TextSpan( + text: widget.text, + style: theme.textTheme.bodyLarge?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + children: [ + TextSpan( + text: widget.linkText, + style: theme.textTheme.bodyLarge?.copyWith( + color: const DigitColors().burningOrange, + decoration: TextDecoration.underline, + decorationColor: + const DigitColors().burningOrange, + ), + recognizer: TapGestureRecognizer() + ..onTap = () { + showDialog( + context: context, + builder: (context) { + + return FullPageDialog( + privacyPolicy: widget.privacyPolicy ?? PrivacyPolicy(), + onAccept: () { + checkboxStateNotifier.value = true; + field.didChange(true); + }, + onDecline: () { + checkboxStateNotifier.value = false; + field.didChange(false); + }, + ); + }, + ); + }, + ), + if (widget.trailingText != null) + TextSpan( + text: widget.trailingText, + style: theme.textTheme.bodyLarge?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + ], + ), + ), + ), + ], + ), + if (field.errorText != null) ...[ + const SizedBox(height: kPadding/2), + Text( + widget.validationMessage, + style: theme.textTheme.bodySmall?.copyWith( + color: const DigitColors().lavaRed, + ), + ), + ], + ], + ); + }, + ); + }, + validationMessages: { + ValidationMessage.required: (error) => widget.validationMessage, + }, + ); + } +} diff --git a/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_dialog.dart b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_dialog.dart new file mode 100644 index 000000000..55421cfc2 --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_dialog.dart @@ -0,0 +1,142 @@ +import 'package:digit_components/theme/colors.dart'; +import 'package:digit_components/widgets/digit_card.dart'; +import 'package:digit_components/widgets/digit_elevated_button.dart'; +import 'package:digit_components/widgets/digit_outline_button.dart'; +import 'package:flutter/material.dart'; +import '../../data/local_store/no_sql/schema/app_configuration.dart'; +import '../localized.dart'; +import 'privacy_notice_expand_component.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../models/privacy_notice/privacy_notice_model.dart'; +import '../showcase/showcase_wrappers.dart'; + +class FullPageDialog extends LocalizedStatefulWidget { + final PrivacyPolicy privacyPolicy; + final VoidCallback onAccept; + final VoidCallback onDecline; + + const FullPageDialog({ + super.key, + super.appLocalizations, + required this.privacyPolicy, + required this.onAccept, + required this.onDecline, + }); + + @override + _FullPageDialogState createState() => _FullPageDialogState(); +} + +class _FullPageDialogState extends LocalizedState { + @override + Widget build(BuildContext context) { + return Dialog.fullscreen( + backgroundColor: const DigitColors().white, + child: Container( + color: const DigitColors().white, + child: Column( + children: [ + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: kPadding*2), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: const EdgeInsets.only(top: kPadding*3, left: 0), + child: Text( + localizations.translate(widget.privacyPolicy.header), + maxLines: 3, + style: Theme.of(context).textTheme.displayMedium?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + Padding( + padding: EdgeInsets.zero, + child: InkWell( + onTap: () { + Navigator.of(context).pop(); + }, + child: Icon( + Icons.close, + size: kPadding*4, + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + ], + ), + const SizedBox(height: kPadding*2), + if(widget.privacyPolicy.contents != null) + Column( + children: widget.privacyPolicy.contents!.map((section) { + return Padding( + padding: const EdgeInsets.only(bottom: kPadding*2), + child: ExpandableSection(content: section), + ); + }).toList(), + ), + ], + ), + ), + ), + ), + Container( + decoration: BoxDecoration( + boxShadow: [ + BoxShadow( + color: const Color(0xFF000000).withOpacity(.16), + offset: const Offset(0, -1), + spreadRadius: 0, + blurRadius: 2, + ), + ], + ), + child: DigitCard( + margin: const EdgeInsets.symmetric(horizontal: 0), + padding: const EdgeInsets.all(kPadding), + child: Column( + children: [ + DigitElevatedButton( + onPressed: () { + widget.onAccept(); + Navigator.of(context).pop(); + }, + child: Text(localizations.translate(i18.privacyPolicy.acceptText)), + ), + DigitOutLineButton( + onPressed: () { + widget.onDecline(); + Navigator.of(context).pop(); + }, + label: localizations.translate(i18.privacyPolicy.declineText), + buttonStyle: OutlinedButton.styleFrom( + backgroundColor: Colors.white, + side: BorderSide( + width: 1.0, + color: Theme.of(context).colorScheme.secondary, + ), + minimumSize: Size( + MediaQuery.of(context).size.width, + 50, + ), + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.zero, + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_expand_component.dart b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_expand_component.dart new file mode 100644 index 000000000..6f3f6006a --- /dev/null +++ b/apps/health_campaign_field_worker_app/lib/widgets/privacy_notice/privacy_notice_expand_component.dart @@ -0,0 +1,285 @@ +import 'package:closed_household/widgets/showcase/showcase_wrappers.dart'; +import 'package:digit_components/theme/colors.dart'; +import 'package:flutter/material.dart'; +import '../../data/local_store/no_sql/schema/app_configuration.dart'; +import '../localized.dart'; + +class ExpandableSection extends LocalizedStatefulWidget { + final Content content; + + const ExpandableSection({ + super.key, + super.appLocalizations, + required this.content, + }); + + @override + _ExpandableSectionState createState() => _ExpandableSectionState(); +} + +class _ExpandableSectionState extends LocalizedState { + bool _isExpanded = false; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + color: const DigitColors().alabasterWhite, + borderRadius: const BorderRadius.all(Radius.circular(kPadding / 2)), + border: Border.all(color: const DigitColors().quillGray, width: 1.0), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + GestureDetector( + onTap: () { + setState(() { + _isExpanded = !_isExpanded; + }); + }, + child: Container( + padding: _isExpanded + ? const EdgeInsets.only( + top: kPadding * 2, + left: kPadding * 2, + right: kPadding * 2) + : const EdgeInsets.all(kPadding * 2), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.content.header != null) + Flexible( + child: Text( + localizations.translate(widget.content.header!), + maxLines: 3, + style: Theme.of(context) + .textTheme + .bodyLarge + ?.copyWith(fontWeight: FontWeight.bold), + ), + ), + Icon( + _isExpanded ? Icons.expand_less : Icons.chevron_right, + size: kPadding * 3, + ), + ], + ), + ), + ), + if (_isExpanded && widget.content.descriptions != null) + Padding( + padding: const EdgeInsets.symmetric(horizontal: kPadding * 2), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: + widget.content.descriptions!.asMap().entries.map((entry) { + int index = entry.key; + Description desc = entry.value; + int? stepNumber = desc.type == 'step' ? index + 1 : null; + return DescriptionWidget( + description: desc, + stepNumber: stepNumber, + ); + }).toList(), + ), + ), + ], + ), + ); + } +} + +class DescriptionWidget extends LocalizedStatefulWidget { + final Description description; + final int? stepNumber; + + const DescriptionWidget({ + super.key, + super.appLocalizations, + required this.description, + this.stepNumber, + }); + + @override + _DescriptionWidgetState createState() => _DescriptionWidgetState(); +} + +class _DescriptionWidgetState extends LocalizedState { + @override + Widget build(BuildContext context) { + final descriptionText = widget.description.text ?? ''; + final descriptionType = widget.description.type ?? "null"; + final isBold = widget.description.isBold ?? false; + final hasSubDescriptions = widget.description.subDescriptions != null; + + return Padding( + padding: const EdgeInsets.only(top: kPadding, bottom: kPadding), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildDescriptionText( + descriptionText, descriptionType, isBold, widget.stepNumber), + if (hasSubDescriptions) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: widget.description.subDescriptions! + .asMap() + .entries + .map((entry) { + final index = entry.key; + final subDesc = entry.value; + return SubDescriptionWidget( + subDescription: subDesc, + stepNumber: subDesc.type == 'step' + ? index + 1 + : null, // Pass step number if type is 'step' + ); + }).toList(), + ), + ], + ), + ); + } + + Widget _buildDescriptionText(String descriptionText, String descriptionType, + bool isBold, int? stepNumber) { + if (descriptionType == 'step') { + return RichText( + text: TextSpan( + text: '$stepNumber. ', + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + children: [ + TextSpan( + text: localizations.translate(descriptionText), + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ), + ], + ), + textAlign: TextAlign.justify, + ); + } else if (descriptionType == 'points') { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Column( + children: [ + SizedBox( + height: kPadding / 4, + ), + Icon(Icons.circle, size: kPadding), + ], + ), + const SizedBox(width: kPadding), + Expanded( + child: RichText( + text: TextSpan( + text: localizations.translate(descriptionText), + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ), + textAlign: TextAlign.justify, + ), + ), + ], + ); + } else { + return Text( + localizations.translate(descriptionText), + textAlign: TextAlign.justify, + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ); + } + } +} + +class SubDescriptionWidget extends LocalizedStatefulWidget { + final SubDescription subDescription; + final int? stepNumber; + + const SubDescriptionWidget({ + super.key, + super.appLocalizations, + required this.subDescription, + this.stepNumber, + }); + + @override + _SubDescriptionWidgetState createState() => _SubDescriptionWidgetState(); +} + +class _SubDescriptionWidgetState extends LocalizedState { + @override + Widget build(BuildContext context) { + final subDescriptionText = widget.subDescription.text ?? ''; + final subDescriptionType = widget.subDescription.type ?? "null"; + final isBold = widget.subDescription.isBold ?? false; + final isSpaceRequired = widget.subDescription.isSpaceRequired ?? false; + + return Padding( + padding: EdgeInsets.only( + left: isSpaceRequired ? kPadding * 2 : 0.0, + top: kPadding / 2, + bottom: kPadding / 2), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildSubDescriptionText(subDescriptionText, subDescriptionType, + isBold, widget.stepNumber), + ], + ), + ); + } + + Widget _buildSubDescriptionText(String subDescriptionText, + String subDescriptionType, bool isBold, int? stepNumber) { + if (subDescriptionType == 'step') { + return Text( + '$stepNumber. ${localizations.translate(subDescriptionText)}', + textAlign: TextAlign.justify, + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ); + } else if (subDescriptionType == 'points') { + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Column( + children: [ + SizedBox( + height: kPadding / 4, + ), + Icon(Icons.circle, size: kPadding), + ], + ), + const SizedBox(width: kPadding), + Expanded( + child: Text( + localizations.translate(subDescriptionText), + textAlign: TextAlign.justify, + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ), + ), + ], + ); + } else { + return Text( + localizations.translate(subDescriptionText), + textAlign: TextAlign.justify, + style: TextStyle( + fontWeight: isBold ? FontWeight.bold : FontWeight.normal, + ), + ); + } + } +} diff --git a/apps/health_campaign_field_worker_app/lib/widgets/showcase/config/home_showcase.dart b/apps/health_campaign_field_worker_app/lib/widgets/showcase/config/home_showcase.dart index cf5104bc1..0d712dc39 100644 --- a/apps/health_campaign_field_worker_app/lib/widgets/showcase/config/home_showcase.dart +++ b/apps/health_campaign_field_worker_app/lib/widgets/showcase/config/home_showcase.dart @@ -23,7 +23,8 @@ class _HomePageShowcaseData { supervisorComplaints, supervisorSyncData, deleteAll, - db + db, + closedHouseHold, ]; final distributorProgressBar = ShowcaseItemBuilder( @@ -97,4 +98,11 @@ class _HomePageShowcaseData { final db = ShowcaseItemBuilder( messageLocalizationKey: i18.home.db, ); + + final dashBoard = ShowcaseItemBuilder( + messageLocalizationKey: i18.home.dashboard, + ); + final closedHouseHold = ShowcaseItemBuilder( + messageLocalizationKey: i18.home.closedHouseHoldLabel, + ); } diff --git a/apps/health_campaign_field_worker_app/lib/widgets/sidebar/side_bar.dart b/apps/health_campaign_field_worker_app/lib/widgets/sidebar/side_bar.dart index 09a21c4f6..07530a05d 100644 --- a/apps/health_campaign_field_worker_app/lib/widgets/sidebar/side_bar.dart +++ b/apps/health_campaign_field_worker_app/lib/widgets/sidebar/side_bar.dart @@ -111,7 +111,7 @@ class SideBar extends StatelessWidget { ), icon: Icons.language, onPressed: () { - // TODO: Complete implementation + }, content: Offstage( offstage: languages == null, diff --git a/apps/health_campaign_field_worker_app/pubspec.lock b/apps/health_campaign_field_worker_app/pubspec.lock index 67cceb830..7ae4bdb06 100644 --- a/apps/health_campaign_field_worker_app/pubspec.lock +++ b/apps/health_campaign_field_worker_app/pubspec.lock @@ -69,10 +69,10 @@ packages: dependency: "direct main" description: name: attendance_management - sha256: "7a3719dcca80be6f9475bea2b1e5226e67fcc60f3c3c55d849aa4f7216512a43" + sha256: b14b538f2d2900c5e4f6a12fefef615d08905398338deb5ea6d67f45f52c8ef0 url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.0.2" audioplayers: dependency: "direct main" description: @@ -337,6 +337,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.1" + closed_household: + dependency: "direct main" + description: + name: closed_household + sha256: "7d3ae93e5702df79b1fb88720bba30fe4b8a603dd2b128a53bbf77d0a8a1dba4" + url: "https://pub.dev" + source: hosted + version: "1.0.1" code_builder: dependency: transitive description: @@ -484,18 +492,25 @@ packages: dependency: "direct main" description: name: digit_components - sha256: "53ee8c0a7c992c0e8d1c9c867b6cf1d52e1728200f4b4436943a5d6c5e4984c3" + sha256: "01320d4c72829045e789d1a56e23ff2bd85dad6a1831d27bd507a1acaceae17e" url: "https://pub.dev" source: hosted - version: "1.0.0+2" + version: "1.0.1" digit_data_model: dependency: "direct main" description: - name: digit_data_model - sha256: "0e1ec8e4d2776fcc4a8118ac85043b8876466ec7399c14880f3d585ad3586ef6" + path: "../../packages/digit_data_model" + relative: true + source: path + version: "1.0.4" + digit_dss: + dependency: "direct main" + description: + name: digit_dss + sha256: c21036372bb4dcb2b888024b488f8817997b9514e442c6f5c1ccf89d97537636 url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.0" digit_firebase_services: dependency: "direct main" description: @@ -507,10 +522,10 @@ packages: dependency: "direct main" description: name: digit_scanner - sha256: a040c9c413436aeb953fdea3bc99ef618641189b06e8f155d84ac83ba8d40fd1 + sha256: "1f1fe3ca8f038a3c93cd52491cf72c0b0e45c88b14580243d47eac59672e67ea" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" digit_showcase: dependency: "direct main" description: @@ -527,6 +542,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.4.3+1" + disable_battery_optimization: + dependency: "direct main" + description: + name: disable_battery_optimization + sha256: "6b2ba802f984af141faf1b6b5fb956d5ef01f9cd555597c35b9cc335a03185ba" + url: "https://pub.dev" + source: hosted + version: "1.1.1" disk_space: dependency: "direct main" description: @@ -1094,10 +1117,10 @@ packages: dependency: "direct main" description: name: inventory_management - sha256: "2be2d09552432266bef3c11f2cd6d12ce83f39339c925d350aeda764c2acfef9" + sha256: "5bad99832b9d828839f69e0288ad8fe06188e6504301c298f5dc3258cf677c75" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3+1" io: dependency: transitive description: @@ -1517,11 +1540,10 @@ packages: registration_delivery: dependency: "direct main" description: - name: registration_delivery - sha256: c315da85605c6d08b9b05147ced61a93ecb566d98bafee1653681659cfde4b84 - url: "https://pub.dev" - source: hosted - version: "1.0.2" + path: "../../packages/registration_delivery" + relative: true + source: path + version: "1.0.3" remove_emoji_input_formatter: dependency: transitive description: @@ -2056,5 +2078,5 @@ packages: source: hosted version: "3.1.2" sdks: - dart: ">=3.2.0 <3.9.0" + dart: ">=3.2.3 <3.9.0" flutter: ">=3.16.0" diff --git a/apps/health_campaign_field_worker_app/pubspec.yaml b/apps/health_campaign_field_worker_app/pubspec.yaml index 74375bbd8..50aba039c 100644 --- a/apps/health_campaign_field_worker_app/pubspec.yaml +++ b/apps/health_campaign_field_worker_app/pubspec.yaml @@ -1,7 +1,7 @@ name: health_campaign_field_worker_app description: A new Flutter project. publish_to: 'none' -version: 1.4.0+0 +version: 1.5.0+0 environment: sdk: '>=3.0.0 <=4.0.0' @@ -18,14 +18,14 @@ dependencies: sqlite3_flutter_libs: ^0.5.10 path_provider: ^2.0.11 path: ^1.8.2 - digit_components: ^1.0.0+2 + digit_components: ^1.0.1 auto_route: ^7.8.4 flutter_bloc: ^8.1.1 collection: ^1.16.0 reactive_forms: ^14.1.0 location: ^5.0.0 dart_mappable: ^4.2.0 - dio: ^5.1.2 + dio: ^5.4.2+1 flutter_keyboard_visibility: ^5.4.0 isar: ^3.0.5 isar_flutter_libs: ^3.0.5 @@ -65,12 +65,15 @@ dependencies: disk_space: ^0.2.1 google_mlkit_barcode_scanning: ^0.10.0 camera: ^0.10.5+7 - attendance_management: ^1.0.1 - digit_scanner: ^1.0.2 - inventory_management: ^1.0.2 + attendance_management: ^1.0.2 + digit_scanner: ^1.0.3 + inventory_management: ^1.0.3+1 referral_reconciliation: ^1.0.2 - digit_data_model: ^1.0.2 - registration_delivery: ^1.0.2 + digit_data_model: ^1.0.3 + registration_delivery: ^1.0.3 + disable_battery_optimization: ^1.1.1 + digit_dss: ^1.0.0 + closed_household: ^1.0.1 dev_dependencies: flutter_test: diff --git a/packages/attendance_management/CHANGELOG.md b/packages/attendance_management/CHANGELOG.md index a0a7ae29f..db47a0cc4 100644 --- a/packages/attendance_management/CHANGELOG.md +++ b/packages/attendance_management/CHANGELOG.md @@ -1,3 +1,7 @@ +## 1.0.2 +* Capturing location on attendance submit +* Pagination issue fix to fetch all attendees + ## 0.0.0-dev.1 * Initial release of the package @@ -38,3 +42,12 @@ ## 1.0.1 * Added try catch for local repository to handle db lock + +## 1.0.1+1 +* Get Precise location on Submitting latitude longitude details + +## 1.0.2-dev.1 +* Removed captured Location Dialog on attendance submit + +## 1.0.2-dev.2 +* Updated registers search to fetch all attendees to avoid limit on overall query \ No newline at end of file diff --git a/packages/attendance_management/lib/data/local_store/sql_store/tables/attendance.dart b/packages/attendance_management/lib/data/local_store/sql_store/tables/attendance.dart deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/attendance_management/lib/data/repositories/local/attendance_register.dart b/packages/attendance_management/lib/data/repositories/local/attendance_register.dart index 9de7a4b0e..1d8015533 100644 --- a/packages/attendance_management/lib/data/repositories/local/attendance_register.dart +++ b/packages/attendance_management/lib/data/repositories/local/attendance_register.dart @@ -16,41 +16,55 @@ class AttendanceLocalRepository extends LocalRepository>(() async { - final selectQuery = sql.select(sql.attendanceRegister).join([ + var attendanceRegisterQuery = sql.select(sql.attendanceRegister).join([]); + + if (query.limit != null && query.offSet != null) { + attendanceRegisterQuery.limit(query.limit!, offset: query.offSet); + } + + attendanceRegisterQuery = attendanceRegisterQuery + ..where(buildAnd([ + if (query.id != null) sql.attendanceRegister.id.equals(query.id!), + if (query.referenceId != null) + sql.attendanceRegister.referenceId.equals(query.referenceId!), + ])); + + final attendanceRegisterResults = await attendanceRegisterQuery.get(); + final registerIds = attendanceRegisterResults.map((e) { + return e.readTable(sql.attendanceRegister).id!; + }).toList(); + + var selectQuery = sql.select(sql.attendanceRegister).join([ leftOuterJoin( sql.staff, - sql.staff.registerId.equalsExp( - sql.attendanceRegister.id, - ), + sql.staff.registerId.equalsExp(sql.attendanceRegister.id), ), leftOuterJoin( sql.attendee, - sql.attendee.registerId.equalsExp( - sql.attendanceRegister.id, - ), + sql.attendee.registerId.equalsExp(sql.attendanceRegister.id), ), ]); - if (query.limit != null && query.offSet != null) { - selectQuery.limit(query.limit!, offset: query.offSet); - } + selectQuery = selectQuery + ..where(sql.attendanceRegister.id.isIn(registerIds)); - final results = await (selectQuery - ..where(buildAnd([ - if (query.id != null) - sql.attendanceRegister.id.equals( - query.id!, - ), - if (query.staffId != null) - sql.staff.userId.equals( - query.staffId!, - ), - if (query.referenceId != null) - sql.attendanceRegister.referenceId.equals( - query.referenceId!, - ), - ]))) - .get(); + selectQuery = selectQuery + ..where(buildAnd([ + if (query.id != null) + sql.attendanceRegister.id.equals( + query.id!, + ), + if (query.staffId != null) + sql.staff.userId.equals( + query.staffId!, + ), + if (query.referenceId != null) + sql.attendanceRegister.referenceId.equals( + query.referenceId!, + ), + ])); + + final results = await selectQuery.get(); final registerMap = {}; diff --git a/packages/attendance_management/lib/pages/mark_attendance.dart b/packages/attendance_management/lib/pages/mark_attendance.dart index 8c1e828c9..3e63719f5 100644 --- a/packages/attendance_management/lib/pages/mark_attendance.dart +++ b/packages/attendance_management/lib/pages/mark_attendance.dart @@ -6,6 +6,7 @@ import 'package:auto_route/auto_route.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_components/models/digit_table_model.dart'; import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data/data_repository.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -56,6 +57,7 @@ class _MarkAttendancePageState extends State { void initState() { controller = TextEditingController(); controller.addListener(searchByName); + context.read().add(const LoadLocationEvent()); individualLogBloc = AttendanceIndividualBloc( const AttendanceIndividualState.loading(), attendanceLogDataRepository: context @@ -177,6 +179,7 @@ class _MarkAttendancePageState extends State { EnumValues.draft.toValue(), locationState.latitude, locationState.longitude, + context, ); }, icon: Icons.drafts_outlined, @@ -196,6 +199,7 @@ class _MarkAttendancePageState extends State { .toValue(), locationState.latitude, locationState.longitude, + context, ); } : () { @@ -436,89 +440,98 @@ class _MarkAttendancePageState extends State { ThemeData theme, String type, double? latitude, - double? longitude) { - state.maybeWhen( - orElse: () {}, - loaded: ( - attendanceSearchModelList, - attendanceCollectionModel, - offsetData, - currentOffset, - countData, - limitData, - flag, - ) async { - if (((attendanceCollectionModel ?? []) - .any((a) => a.status == -1 || a.status == null) && - type != EnumValues.draft.toValue()) || - ((attendanceCollectionModel ?? []) - .every((a) => a.status == -1 || a.status == null) && - type == EnumValues.draft.toValue())) { - DigitToast.show( - context, - options: DigitToastOptions( - localizations - .translate(i18.attendance.pleaseMarkAttForIndividuals), - true, - theme, - ), - ); - } else { - if (type == EnumValues.draft.toValue()) { - individualLogBloc?.add(SaveAsDraftEvent( - entryTime: widget.entryTime, - exitTime: widget.exitTime, - selectedDate: widget.dateTime, - isSingleSession: widget.session == null, - createOplog: type != EnumValues.draft.toValue(), - latitude: latitude, - longitude: longitude, - )); + double? longitude, + BuildContext context) { + context.read().add(const LoadLocationEvent()); + DigitComponentsUtils().showLocationCapturingDialog( + context, + localizations.translate(i18.common.locationCapturing), + DigitSyncDialogType.inProgress); + Future.delayed(const Duration(seconds: 2), () async { + DigitComponentsUtils().hideLocationDialog(context); + state.maybeWhen( + orElse: () {}, + loaded: ( + attendanceSearchModelList, + attendanceCollectionModel, + offsetData, + currentOffset, + countData, + limitData, + flag, + ) async { + if (((attendanceCollectionModel ?? []) + .any((a) => a.status == -1 || a.status == null) && + type != EnumValues.draft.toValue()) || + ((attendanceCollectionModel ?? []) + .every((a) => a.status == -1 || a.status == null) && + type == EnumValues.draft.toValue())) { DigitToast.show( context, options: DigitToastOptions( - localizations.translate(i18.attendance.draftSavedMessage), - false, + localizations + .translate(i18.attendance.pleaseMarkAttForIndividuals), + true, theme, ), ); } else { - DigitDialog.show(context, - options: DigitDialogOptions( - titleText: localizations.translate( - i18.attendance.confirmationLabel, - ), - contentText: - '${localizations.translate(i18.attendance.confirmationDesc)} \n\n${localizations.translate(i18.attendance.confirmationDescNote)}', - primaryAction: DigitDialogActions( - label: localizations.translate( - i18.attendance.proceed, + if (type == EnumValues.draft.toValue()) { + individualLogBloc?.add(SaveAsDraftEvent( + entryTime: widget.entryTime, + exitTime: widget.exitTime, + selectedDate: widget.dateTime, + isSingleSession: widget.session == null, + createOplog: type != EnumValues.draft.toValue(), + latitude: latitude, + longitude: longitude, + )); + DigitToast.show( + context, + options: DigitToastOptions( + localizations.translate(i18.attendance.draftSavedMessage), + false, + theme, + ), + ); + } else { + DigitDialog.show(context, + options: DigitDialogOptions( + titleText: localizations.translate( + i18.attendance.confirmationLabel, ), - action: (context) { - individualLogBloc?.add(SaveAsDraftEvent( - entryTime: widget.entryTime, - exitTime: widget.exitTime, - selectedDate: widget.dateTime, - isSingleSession: widget.session == null, - createOplog: type != EnumValues.draft.toValue(), - latitude: latitude, - longitude: longitude, - )); - Navigator.of(context).pop(); - navigateToAcknowledgement(localizations); - }, - ), - secondaryAction: DigitDialogActions( - label: - localizations.translate(i18.common.coreCommonGoback), - action: (context) { - Navigator.of(context).pop(); - }, - ), - )); + contentText: + '${localizations.translate(i18.attendance.confirmationDesc)} \n\n${localizations.translate(i18.attendance.confirmationDescNote)}', + primaryAction: DigitDialogActions( + label: localizations.translate( + i18.attendance.proceed, + ), + action: (context) { + individualLogBloc?.add(SaveAsDraftEvent( + entryTime: widget.entryTime, + exitTime: widget.exitTime, + selectedDate: widget.dateTime, + isSingleSession: widget.session == null, + createOplog: type != EnumValues.draft.toValue(), + latitude: latitude, + longitude: longitude, + )); + Navigator.of(context).pop(); + navigateToAcknowledgement(localizations); + }, + ), + secondaryAction: DigitDialogActions( + label: localizations + .translate(i18.common.coreCommonGoback), + action: (context) { + Navigator.of(context).pop(); + }, + ), + )); + } } - } - }); + }); + }); } void navigateToAcknowledgement(AttendanceLocalization localizations) { diff --git a/packages/attendance_management/lib/utils/i18_key_constants.dart b/packages/attendance_management/lib/utils/i18_key_constants.dart index 9b6bf714c..56bf1453c 100644 --- a/packages/attendance_management/lib/utils/i18_key_constants.dart +++ b/packages/attendance_management/lib/utils/i18_key_constants.dart @@ -97,6 +97,10 @@ class Common { String get ageInMonths => 'AGE_IN_MONTHS_LABEL'; String get inactive => 'INACTIVE'; + + String get locationCapturing => 'CAPTURING_LOCATION'; + String get locationCaptured => 'LOCATION_CAPTURED'; + String get ctaProceed => 'PROCEED'; } class AcknowledgementSuccess { diff --git a/packages/attendance_management/pubspec.lock b/packages/attendance_management/pubspec.lock index 2189ae14f..77b186a33 100644 --- a/packages/attendance_management/pubspec.lock +++ b/packages/attendance_management/pubspec.lock @@ -316,18 +316,18 @@ packages: dependency: "direct main" description: name: digit_components - sha256: "53ee8c0a7c992c0e8d1c9c867b6cf1d52e1728200f4b4436943a5d6c5e4984c3" + sha256: "90e12017934343a197a0c25bec00e5fc28e19cfbf11e522798cc39719609612c" url: "https://pub.dev" source: hosted - version: "1.0.0+2" + version: "1.0.0+9" digit_data_model: dependency: "direct main" description: name: digit_data_model - sha256: "0e1ec8e4d2776fcc4a8118ac85043b8876466ec7399c14880f3d585ad3586ef6" + sha256: "5559c3e652a24f3d24f324d275399f6e864ca5671285386516b94fdf9fe8724c" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3-dev.3" dio: dependency: "direct main" description: diff --git a/packages/attendance_management/pubspec.yaml b/packages/attendance_management/pubspec.yaml index 43a353baa..1838be863 100644 --- a/packages/attendance_management/pubspec.yaml +++ b/packages/attendance_management/pubspec.yaml @@ -1,6 +1,6 @@ name: attendance_management description: Digit UI attendance management specification - This tool is designed for tracking user attendance with customizable session counts per day. -version: 1.0.1 +version: 1.0.2 homepage: "https://github.com/egovernments/health-campaign-field-worker-app/tree/master/packages/attendance_management" repository: "https://github.com/egovernments/health-campaign-field-worker-app" @@ -11,7 +11,7 @@ environment: dependencies: flutter: sdk: flutter - digit_components: ^1.0.0+2 + digit_components: ^1.0.0+9 flutter_bloc: ^8.1.1 freezed_annotation: ^2.1.0 build_runner: ^2.2.1 @@ -27,7 +27,7 @@ dependencies: path: ^1.8.2 drift_db_viewer: ^2.0.0 auto_route: ^7.8.4 - digit_data_model: ^1.0.2 + digit_data_model: ^1.0.3 connectivity_plus: ^5.0.2 collection: ^1.16.0 location: ^5.0.0 diff --git a/packages/closed_household/.gitignore b/packages/closed_household/.gitignore new file mode 100644 index 000000000..ac5aa9893 --- /dev/null +++ b/packages/closed_household/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/packages/closed_household/.metadata b/packages/closed_household/.metadata new file mode 100644 index 000000000..b2c661a57 --- /dev/null +++ b/packages/closed_household/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "67457e669f79e9f8d13d7a68fe09775fefbb79f4" + channel: "stable" + +project_type: package diff --git a/packages/closed_household/CHANGELOG.md b/packages/closed_household/CHANGELOG.md new file mode 100644 index 000000000..53f7cc70c --- /dev/null +++ b/packages/closed_household/CHANGELOG.md @@ -0,0 +1,24 @@ +## 1.0.1 + +* Updated digit_data_model and registration_delivery + +## 1.0.0 + +* Introducing new closed household for IRS campaign + +## 0.0.0-dev.4 + +* Updated registration_delivery package and digit_data_model package + +## 0.0.0-dev.3 + +* Updated registration_delivery package + +## 0.0.0-dev.2 + +* Closed Household flow change using registration_delivery models to register a closed household + +## 0.0.0-dev.1 + +* Initial release of closed household flow + diff --git a/packages/closed_household/LICENSE b/packages/closed_household/LICENSE new file mode 100644 index 000000000..f7d7ac958 --- /dev/null +++ b/packages/closed_household/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 eGovernments Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/closed_household/README.md b/packages/closed_household/README.md new file mode 100644 index 000000000..346dcdc82 --- /dev/null +++ b/packages/closed_household/README.md @@ -0,0 +1,49 @@ +ClosedHousehold helps health workers to mark a house hold closed after visiting and record the details like latitude and name of household head member. + +## Features + +* Create a closed household +* Update user actions like Resolved, Sprayed etc. + +## Getting started +To use this package, add the following dependency to your `pubspec.yaml` file: + +```yaml +dependencies: + closed_household: ^any +``` + +## Usage + +To Navigate to any screens of the package: + +First add closed_household_router to your main app router + +Navigate to the required screen using the below code and pass the required data: + +```dart +context.router.push(ClosedHouseholdDetailsRoute(),); +``` + +To Consume any bloc of the package in main app: + +```dart +BlocProvider(create: (context) {return ClosedHouseholdBloc();},), +``` + +Closed Household package requires below data to be passed from main app: + +```dart +String? _tenantId; +String? _loggedInUserUuid; +String? _projectId; +BoundaryModel? _boundaryModel; +PersistenceConfiguration? _persistenceConfiguration = PersistenceConfiguration + .offlineFirst; +``` + +To set the required data use: + +```dart +ClosedHouseholdSingleton().setInitialData(); + diff --git a/packages/closed_household/analysis_options.yaml b/packages/closed_household/analysis_options.yaml new file mode 100644 index 000000000..a5744c1cf --- /dev/null +++ b/packages/closed_household/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/closed_household/assets/icons/app_icon.png b/packages/closed_household/assets/icons/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e9e2930ca86e716425b2fca130d8eaee3802293d GIT binary patch literal 10790 zcmeHNQ+p<`)_rSxYP(b0wmqFO5@*-2J* zR=A?P1OhA$EC2vNkdhQt{;q-l&CrnFrSiHJ)OQ8qs4O82sGh<*0RV^qQldhtZaNp* zFzTuYPd-=K(PH2$Vjyg;C{GaJPgTmS4Y#J6hsq|#>Sf7g#+fU{$#j}2n#CH2DH$OV z5k%CPBt#VvRQ051R!?7Eu7|sv2or#o&*;02qZ^QP&uP9RzN3$+mw)<#3=w_^q`>9c ziv_0$02PQC@-i!E5`g`}$AXs}5Dk(k?uQC2-cX1x0ncO7n}=2eU2c3UyGa7DLR#T~ zNCPrm1lV#={f7MHNCjc^<}XWzR6u92YR$o^K&)0j7Tlx(IAHA20CGRMj$9lC7(qi| zF-jhIt@)G6-cJxS`2ThG{{rK7E(rk6@0}DAO0eR~9M-De^UM*_J?GtWOw5Yx$}Fl% z)Kp|6^HyiiH0ol3)h`_D3QYyFSKfeV26ZDdpo1$r6Ag;On1h09;wPn-Jf1bR`e;WG zklEGNThyEyhIVmd!8_nC6U@hu(Y&%6v<|v?=oxhbVjb5a2*;!3XHWdw*_)@~gYEgp zgZ_#-*ZYS7nje($lpQ#@3s5~Amacp;O!uAT@hsaA8pn1dN$)xKIN)a%EIt;oDfDCw zhTe}6ZhMdp*C7(EtpqJ;&|datnbb>#<&~eW7EKn2v}<{jnpMr}W70LMzkV70z{E7g zKu6c+5LBC)QN}+79h{%P>;7lG%3G#Xp-onKuWVrOjs&pCz>*X`lh)iF`csIG$y`r9 zee>yHZ*PC|^psmQYq2(3c-x7~QSIw`cQ_f~;e_c$d$!W?v^Qht-OJ80)d-+5w*B=> z^;||lLBWi~SjEb6;8wUkN0EVjc$Fq%;D9+l|(a}=> z$_m%O;s%Ri#q2YS-gAcP6L}X2AY1ls~I`?SuDyo`}jtRB@&r`Jas{cAyx=ZI?j|}*vsyqSFBlH?{f>feJJ-tnpU$}i-Oin#H|l30{&}TXvxx@sB4J6+Xgyp@ZZYD`;M?MQpae!ZTqL|>thzH=aJUa zQwz57dQk`&`x;Epn0X5$=C;3$g`B&~bp-`<16#C(lWG&SVzO>fZ=Nm#AAb-UQB#nd z9PDxE8Y}rM0#owG)8Y3M1TGPW>%)oNB(y-1lY%RW1)*zk5cp4k~zrA|&T)-c>+r#L))Wd&y`Qyu$(iLM(K#k;x`AUv!TN`S)q@&{q}zv0V)b^X{B{TE0>*LmnvDh=_jZiosHpn+@iRaz}=-{{o*rnWr5i53^BPwa)pB&MG2X9RL~A$W0t#i&?v$y<~t zs(wB!>2J+_CrDD4|59MJ-EO z7U*KJ?rZY^<^3@#$+#d43LUiY`u6s8 zu~4)oAy1dp?tnKcC~Dehfc;OtOc~YtERye&CBay7WyoKt4p4E>I)>}Mk>$O9n1XFu2#M|n@|5yPF^bZc%0h)6$I#5d1=nNx$?zl-`SxqMKU%y$CCoB}1 zjoK?pNfH8s*l`dzLxN>jL7RxjXK1Jq%rOcDx(6#`0qv~xh85-1zTI9-#!ay0_p7U# zbL~w=KVYZ-+2jaSS64rMAD059$`$IU*Wy(e3ZR~zQ0D6|txD3S@H6%J#09w?lNsVFMp^}v` zS(wvhGm&!{iCOM$g=D1j!qIT$0Qvd{QV09{`_+4t{VQv0JZ~+Q95vQjJw@M+NTi*; z6s}8#3R9sR3f4TDU1^_gPS1CKf5Zz0h zQ-sLL>uEHjl`JL@qj!4|_4Yl@_|MUBaoPUq@v(Lk5(4R6dal1(thkcZ71(-FE>q3O zPQI}*F!)PeU@kWa=zDWEP7Ob2)&u4>b^G`*l&eyU$hr&H(rUSr+%D(s?i%P1OwJG( zc&Z$+$hK?Bf-c1C%@H|WtzZ~(qGzcB)7dFu{l+f4L&q?1AB+fI|*H4@dF!mHW<~++PPLU)_I4v*t z_Wg9XOHk5dqXdKYiC2KmOd``K&koxSDUe4E7jrz|m^4-OXAMw6Rhv(9k1uFK=;O{J`oZ35Iw zh9+Lp20xl}uBo!JazIeW5gG_({`Pnw^7cUJ_P6`?l9fEnj z%iL`*xuSAbu~5qxAa@+d7-dlwArR6!)0u691u|aGwr#iO#H}5Xu$b^5)_g1m=%H^~ z#sI`hmj3pw7+ecuaNJ{hL zjfOR2#2_VT+aDdd`x;Y2uimtCGS;c*edmP zLw#XV${1YjUeS%@D@%2?55en#Ay$tOT+%PHsxvp@Ca~%ptw4l^6ixM>2r0kzdSbVc zxT`L$mh_@Ixk{L9C1w_Csh+G)bpr#ulR`Lh@oyBzu^9EP6?{H@<{?1ixYLvVBqt{; zNgxu!nu`V!85!TIq|q?aMxN6BrUIF0LPPMauE?kCeB})=@rk(wCGV;BYkba9gGkQ? zO)g@3cKbuM#dUYN7lY{|D<&3C1B^RBY1ipd1LJg;tn+-q%G!8Hg{TT#2H!qFz(##- zPjx+W{Z-C`W=Tc`142)(o8fyh7i=p^0@#wmXS0wEQW;Mn9gVB-L5-LQk%o(m=;p?D zKW`IX7!9fF)+fx%x4Mpf1UaSizpR7L!?jj#J>tyj63PE%Uug8tQJh02&kV#$cNOku zC>e{Vet9w@+LKG#2s*BJOf%3+ifKq+W0HTpIjBNhik+^V8C!Dy1Eij8-VdOO04DKU@2MO) z>x~>1Z8I&@U!_OLxh)0$cCjlLS@3d%Q3a?cUxquhnMlQf756vLwOOd3pr}>4-0l zLewx{T}jDf9|eXhs9+eqEl81=5F7 zXnxeojA9lS78bs5&L|_ULYWc3Igu+4&s@4Wc+;w~#V9Vu{gQ7-AvComvN%IM*M88~ zRuuTy!+3tk2_G|<)A)BgZ@}yc3Ga%1Mt~bMmsQ`6TJEzkKmo8Fe!fA`Wg+4A(Qo1C-MEE?P_XjhmovEz_V}q@PrM*2iA;(6iEF8_Tt5{u6Jc+#dOjs z2mvOpQ28f5JTy>8QaUXwC8aqO75E35G$@P{lB#0#gJHYsFhdjY!k< zHL%dsNfTnvf#mr8gnK$e1Y*RjA-7P5#&>&nSF_L{ks_K|do7KNJY(r{M4#Qm(u5HP z?_d08@h5gIc1bDT1ds+WqJfTvv94fOb-lZuMs5~Qb?2d5cT%= z7kD4fpkS&}7vWC=TtiQLn9!`A#r4&a-z#0wV7`Dqwm{-6J^l7>?TD{9>2EB7nVBG$ zwC!Wlz6alfAw1Jk6dLZKTRYzB@on|(K+KKX_zkHM_CCfCK2yq;`gFB54<*>7v{lH} zpC|fbi}U&Q6%h-Mm8`h9SbTZCZ~WlQjfcm`)P$bf_w(HJp;3@GoZI>I)ovP?(*p}m zK_i6@3o!}!a)4w^C3nL9+mOhk=K4v%9|7a6Lr26jmQKwXu`q%fnPz(OWSjBm{b08~DG!x8-CYetU!?1l(i|rQ0aI0z} z7+#^W6paMb@Z;JtkSf0T=)vA!BT*i46)v8~8 zV)VnayT9vrF9J;_z_3>PTJp&3Mjm+_;;rM1>abs=J}WHmu2y@>$y0^(DXS`}wtS9f zda*tHA5t6UT zEXN!NG6@V6a^GoV@tR7}+cO}Nfq=&&34TyhGX)mAac42_X;~RsX0+gJyZV?D%5Z}t z@6V)=0kWH>JOb3u$bq?N^|aMxxtm-LJ8E#^UhUqBtqN+V0f>(mgd_NI$pdCCSeuPk zTISnjl0fBxO}-`stBBM>(_&lss7SQtaP~%q0ES@AW~&o!JH44y`l>%8hjx;FLJ<6_BX}9bH^-x^6qpc0fDL^ zDq@5N8tvpV05@R>aB$v#MV3z&ud5nM6Iw1e*|Oe5Qj&i04pK$RMcVQ*8YvkWubHz1 zkSfZ-DM~J1U`Qq-Mz`#*iHIW^1Vw-7Q%y}xeXw0Wc{LVHMxlReZ&5PVPO}R5_AH&B zpMy%l)l91gAs5z=98Uu9G+f5-0^do~W8PKERDahT>3m$Tw>kFB(ie|OZBiCU#PTio zjhfSP1qT3u_E`~y>1ziEOeiQ4Bg_aguSTH!yc9tr1>&)COq|pqz|A;xE80s-Vx=@{&Dbe7))`)l59#5JP!5-;S>n67 z$HWlm7!D(l^2Dx7*{QFdP>w?c`HIF!7fH9e?+vBg-#5yUlam`!Xts#<-!FF%@4u2G zi2VL$e(nwJ?HS-iJtFH*Q@TGi&aK4f(iv?%1)xJtN7m{>5~O4 zABMO7hRMq`J9)Ds!qalw-aia8kzZ#Gy3MY$%mwJ0u}=BjV%)Mso9bj9{q#|;$^C&p zu3oxmq>nWGH8D!e%tv)1HHhH*2}tR4sS9g~{wS3Hve?SsY* zJz6kJ&BV`U>zsjI4Sj_eb=lxG`q!)r7I5PYQlrGY1#q8nlmx;fSw(R_&lR<*gB>lg zZ7|n`7Y@-m+tRas5XTKDh7@@m=R91kA>6TFfwo#m8fnJWcv+ti4|YHO-n-^@VC7k% zB25wrxuX!)Fj0rZfuwxVR;MJdWMS_74GiDHjUGe^RfdvdJtQVo3cUAsRzNm-U zjrry!LEa8JREZv}$i7MgyR6IBw5aDlN!sLa_fcdI*udrWekvDuDlh(zBua!d>I^Z38b_2v84xYe4@;vG;t(p+~m!CZ{StSlUwz0c5 zi(bwhU7|g?yx_MX%KD?8wIZYzaT+k#@&xFtb!13!A~8Mv`e?T;W#E4Bg|=wITS`PE zKHywA7y{DFfNVfI_uWKeo_6CI4%`{Wy-R@F7$1>3Z89bmnf7&^K}%k&5mB0O&`Xs3 zGp4H%l(@%wgf3LJ{b6(=c3k<3s?z~~txtEqK|VLU_xh3>{B%`|v&ETm#9}4>PJ+bf z(Zwk16-8{xN20Hp(+%M`;C7vMpDd2y5bP3nI}%Yy1t=JTi|xDH2lAH?EY)S|m>r0@ zM2}hU7WQ*nG5R@>M={OB=7E~r4+OM5&)sSg4%+LQZef!@y0Rg4=X4%}pD$ET;+gEn zVXEGV?#VK*De}}M_cYIY*McnB#S7M2YJ%LMXb7Z^4x*daor2vBr1@wd1ZmK8udTC9}bp+Pt% zuicN(3Kg6vR+;wfQ^ zef~;$8GrE&&{TzsK-rzJ7@@>k>sd}R{4lZWy$>e$MZ|p_Ns*gHD<`ZO?1+?)_~&7d z_j)62@vdvmS2-QOdljgez6~^Muz<`J=S#RLv z%C{1FQ^*a9RQxj-{Ne_rN)9I^(OK};zy5MU^hWQ{!4K~oC%3ac3Nme`*ewZ0`die2 zBp%Apr}Z&9MU_7>yEwZsdAPST!i($3~J?52jTKJ2Y^xb1d+JU3tDFmy6=`@uR2v<9gyBTG-2r)v*#ku6It>n#R*LZSb<6 zCnn{@T3T3T15e$aalKW#&{CYd+59jP?At#q-VaB-cQcH?zU$GLPuatSS2e;z<_^~> zd};$GM7xpLk}JLhkqSpUPss|zF2nLV^jxTS>A6#eXYYbO*F^8zZ08zWFtcltE-5<~ zg~E8BjPR5#;t^d6+nW@?sA(Munq2>9FKRBqu^fT+!oBToH9L8|x1A!={S>a+8yPa7~^9(W0{-dwx;Yhm;icadkZLssU!VMh15E8 zH6${LI0k1@G9r+QzI_hUyrrN)w+dedTCRGiGNq-ur%4EaCZH6!Jsi5-Oa4~ZnM(5- z6udjj)^W3^g3olYhbFoF6)&_UwA8kcEcjMii1wnE%=3HX-UqAYo-yUgVZJB#SvA@< zk)`e<8C{RHgvokCsgu7PDo!HCM*q6^z;gL|;g69x{(z@B_A*L0d^nV|@kYOGO`uu< z@XB_o|IPg1*u}P1`?aGeW z-Q>^kGw0a??EOu?ubQKn=mi@4W>%Z!UpL~`=lr#gBoU;1X3Y1_3#3zkB0jkm>n8u$ zIu+=ZZm6@_-FyF#iNOnyK7eckyY3Ajex()VpEdq52jgS&rtftp`g=c%u5vB;@PK@H z-jjaYVqMKjr#2y#?RKTD)%V6!{mG5;^J_=oXt!lB5V?y5qd+$;pl+vU=M1|b9v$D` zHL+&5#h3=UCDZAjf8CC5e^WGRGeb@|=F@p#feejR7I#j|qOTpt#3wT(%v*Qg6^-s7 z<&uTnZl>|_$JFrk<(~f$yROiEN*m|(EIVzqNZp*Atv(dp%TqA5NbxO!$;un9|Dw0Eg zC!q}q`L4H>cTQHDEp%_ z*r(lCq?|#2B*_bg<9u9v^Q8_B4E*H~1f)!dIv4*Ivv7+bCj7K>UiahTH0WPQ}!}-g8uPVL?EgV&?R8 z-?>-FHFz4!MQJu*g5 zBsRG_TmISsal%^0X1LspsG$(>TTpj!Dh9tQ!5fTk8n?gCL`woh>&GexK<#t=^xwnd zMnVED_$jeETG%0akGF=-(!(8Sn*%F&2*WH&85IoIaw0jy4}@cm1u$mN7G{sI$K?|q zm|MouU%UxdI0O1q@+)b-0~39iJZG0D>(ltMkvWQLhs1AqFMYQ8!As7k-1m;+|GsBq zX(&@<#?cAk5R*8Kz~k>Kp3aSg3lOJ~Se2@`&B$W5H#Mu<^CO6Bwv#xmQ!&FOld$o} z7%5%sYG}u4EqtS}P9PsmP93%dJ*=S@Y4=lVC4M+{&#QtYXgOE3lUgFa;4GypMARuA zl^2)idC<;%L9#+B6AhR+hUa%Yl%)2*bL|GyIUWnvR)Uws_ob+8;0cEM$d7O2<91K4V|jYJrDuq;bhZ$;A*>k6>&Ex3b*6b{1416LKdXan z2?@dZ9udpOstv#13SHP+tQFHx&`o%wXVC-1>^jS|byG&n%)+Meq=M3asa&zYM;+65 z4yzaYCFTy3jGHNy=T z#x?Q%m8)LX!P2N1Y?cL_J>V?netZi*0a9Y}qSeBB0sjHpLS>f# literal 0 HcmV?d00001 diff --git a/packages/closed_household/assets/icons/svg/mychecklist.svg b/packages/closed_household/assets/icons/svg/mychecklist.svg new file mode 100644 index 000000000..826f196b1 --- /dev/null +++ b/packages/closed_household/assets/icons/svg/mychecklist.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages/closed_household/assets/icons/svg/no_result.svg b/packages/closed_household/assets/icons/svg/no_result.svg new file mode 100644 index 000000000..dd93d89db --- /dev/null +++ b/packages/closed_household/assets/icons/svg/no_result.svg @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/closed_household/assets/images/powered_by_digit.png b/packages/closed_household/assets/images/powered_by_digit.png new file mode 100644 index 0000000000000000000000000000000000000000..f83334fd6168e2aadc21bac07d217b53600ee296 GIT binary patch literal 5524 zcmV;F6>I8=P)c4-rr>7^6m#xQ3VEAt>?^Q4FF2f`GCx_ngV}q`IcMrzcDTpWFZMJ71FS zQ>UtX`uw`8x~9W%h71`pWXO;qLxv0)GGxe*Awy@TKneGUKrwe6*foI}-0$iAs6c@0 z5Gdk01}1SgfL{V-*X=ImE~3jsQ(|J``6iR?Mzh&`mzq7y^S23t&wJe zabl6pX1f$(bupPtHx3#!h zm2_M~hRz8EO1ZxUCURBq^9cO>F)*2XJ@60iI)zVh;`y-eQLtTLr@;c09R+(6!9|wS z5+)wci)AKWIL-^^Kot8KY==oOzX$dV&zm1cSaC6e3Sq|!Vk5*l4R%lv%u@>s3ooPn z^avq>&`eGi2J*aRFvJ=Qe~*E-4Nev;0}*}*54xO|@R*=oE1-=hc|kf3F=v&Ol>CAA zLxJxVJTE;5{y#C!mu@rh;*VBqY5{y6=h1Z-GIZ7i5V{PYvV#GedIVC~Z!+fu@UWny zw8y#Cfo$#qvJN#3;`y$S9H;1H(P^h3aW^H4(ufeGqRQvhAR+a7?1;5d^84*9OC30M+}@&Y=&bq+CnKVF+P8or-ZfKfj;^+IKPS4DbUMntx%` z8?%`u>!JDc=MRK>en;11$k16404FU1FtSbI{wM7BIQLP+el;uQdXaUgsc+u_>2#8` z!T@gKM^>x7ceEi83}OBPz6a$=H zx`0vOzZ=U4PTw4Q-?^kf88sueh25m zV2D*mmrGCgS3~>$MuQFfuLbCBr~O-DCp{i-T|>j#{!qu|WF0}lMZ7e0L93d{;j7^t zzG{)HeFf!|4sXnK@jW#GMR$Fri!6Z)T^O2p_hc+CJ^!d&xS~qy;Cd&HiOh z&ftZ)Lx#WU<)xiB{VI(QG+J`oP~m&7M6w9olw19b1+foV@87OgN#El9F!lq^Ccg zlRIP{TDs4_Qj{!5=@?{N@!V!TlCvZycUZ8@s8NMatz5Y>33_L@LLK3ud{`zIfG3m$ z`pjEQ$1oIs{pR5mIMOljnot{<3^0-bQ^uVLEcGvi3pG3u8(25T8F==heGC}2*d*@P z{nL6?E?TtcQnC&;slh2d!(ZL7c5VN|hYxqgp2nd=hc1VoS5z!na%*;WZkE-Wx&k1> zgp||eUR7CHc{5!Xs6;P-SnG`qvOv8ZVL#Knsji+lI(y>sWzot+mfTGTDS zV2s=0aL<)2wp~_R+Md$V(y?$H_cS#%;nPN@wBU5)$Pp%-P`DlJQn3F*8$Nt^A879$ zIu4rCa+UFQ(fI5V&yEs8P2s zU%tHi_uqft1^hIjtp%qae)vHZPAoy2AE)C8f^@2MQdt4ErKYAPvWKK50#3W>eWY+m zM*!-eDEf>EtTxnt0-R8A;p1KO9#Baa-HgWgv-HD%l z_F3ZEwQIZA*4B2U%V>!OC+KPH-?nYr{m~M+Uq9QQc+vb4T|Su1-t-TkZ3%Q4bvR{L zK*BQNB#O3f&5!k!W!!FW9kjFeH{X2IDH=3ze>5MIDxAEr!>M1tff;lh1ozCDGc)$@ z-~ZpVzozuU357kWSb9(ABEZh1O?t}e@zJAr!zo_vY8Ms5-F0l;P29+T-NNNnvKK2B ze|jM|vgVecANt22CY-FPOcu?5S6sU;Xr)(3rDzG?J66xL0) z3H%OXy`s%`H|>iejjUskKL>n3 zLhqABeinLePOZ|Iy6eGS=f>841>o5WR>_U3{j0*K=wG+P{$`z_!Diw_@Sqr5pi3L{QyC9`tGKnL0kA- zwgyh2;|~7LGWzr5iSw)mRXkUOPXfLFj1}xL)vp5R1Qa%=ZVOlVW^=+9R9ynwHb?l3 zt*_^@*Xde>$%K<+Yg)g4y)HO`I+#r6f6_4o!E(H$v~)NOHx)^!2B*x->+?HffrTEa!O0U>IL&BVIAKqNxWG%ueLM*!N5*vd;>9EkPN>UC z;ZWY0$)O@E33*pbTsompqTL-XPxpkB;P98oU<}qtOz_jmNI$`B?kV_3n4EqeSqJv4 znDOzLiSt3n4}n~+|6s5zYzvv9ZD_3Xq9!74)Yv4LwLV)}#Ane+?~98HYr986CuBwS zQqZTUo{!iU_W7{YO9{-e!3h^4PN8GKuD5qQT;Mcq+B6>x z?Wl?cP6!A20wxoV9D-mH6Gg(}TY5-}vZ0<&^N@+|`7|eSI7!iu+>Z*!btu~(txd{$ zeKq7hC7k>v6j?sO_#qI`@yYXOvip7HK3QZNS_>yu?}ls_9zVHH>slZ`3;J`4 zn~FbH2haHWVL_kq^@Ah!$@W;Sm5Rue8l39u>w7{n>VgxLnM%h%I8B&Pod4;kpI)u- z)qvBcO`Di-;zj8T+W*m!Bd0)Y)%8lU05%t!1aUP{_DE)C<}m1`F~2IK1}B%tTfJq= zmN>vkI`;I_Pqz)6FcHawqCpV8qf*;R>4JgXw@k4;1ej3W!LoEOL@rDBs>q=kxt$c> zGL%s~eI(9_Y7ZgYE7ORt7zPpXd1B~A`ja}-IVbvDlA?xZiP5$P_Yv)3K`$P%E#1|f z8&`ia0y<;sPTxK6a{+yBcx7`k{vGL4`|q14ExV77$&wnJYHDiq!l?s*XaOAqhjo)C zP0C)gW{o~LWn@;YTemI(PRYs1m-D>1miEue%6_@A@#6&ApVq*E1OEcBQLK;3%FZs| zx^*k_I#Pp^)8(n&uwla)!wJsSvB^`X0-RR28czBQl99YP$vGchWjG*yhVxsRNL68>H z{%LmSn%Y|G;Q&Ld`T%U@4Gj&QXW znJhA76x*Oq+#dQn3^1~8d0TM1a{i>T52bE!Hywr5~SkJubFBfwE+_;&0e$y6j<<2Fa?LRtz z^!a$(o_^Lv8{gobY1qO&_0i@*vp;-o*6aFuO(-^;tW9sd^_DI;34)NsGu~=ovD&_< ztgP%wuT*Ej0?p&gsDR#D1e{PQX7gy;-z-_apDEy{i8ro4sT#U>W;+TjukVxrGHk4Mv$w?*O$z@*>5ZFet9$xNEQ9~Hz ze2_jPpTflmCtY?9!YOzzX+LWCmdMzaK>D|ZAQ?KHJbAJ&SpO3zPT-2|^QiqD_Uzen z6AV-O!=1ffU0of{!{|;RH8{QU$}7DAE}C!(O;&HB%cJ@InX{mL*W%)0MSEGWK=XKg z6;)MLOgIUG?GEtykt%cA?r^?4b?Q{jNpY-?E(=4*^5x5y#|S4^^*isp6BjtaIXNRZ zh3}NHC>}j06dwYO3gvPCm8>0*HsCN~|6Wpey; z2u`8%qwG16bAx>7JcmCEmGf~{RN3Q?T;;u8xp%tW#Z}!I@s$xRvET$lvP1d#1v&HQ z&sU9wZ;0eY^ZRt!=JL|PC!c&$Sh{p+0$olGPA-qPV)5d|OgQ1wHIra2r_10%%(OJ; zJg3vCdQBt=!X5PL@^pX`)D;_?9Ik386Bjs*8#m!>z==J7!4gkCv5OcUwhY^FpPV2h zGzgzYYQ8D#6Y|sDCYGYYNn>qQG%4Cf^wwy#C7iV8mQcjfkKi@I%MUWzcu1#PZ};dA zU~1r2^gIN=ALLftTg$ENu4@?qiUlV$i^aAjJ3AYPka9A1z*otph+3Co<}12P zDEUtK{r+hc6&3f)nKLKiiI^&!T%L-B3l}osgzBGS>1^W7JLz&@CwWm?4{aKsEC}}v z7%-sIph1H=hF*c&m*>sz(q+8q>E#O+EQkqCX=#pXXkT35G8b#jslo{rddXZw*%lM=HNyKL{yzN4tF+ba_Lf6kF~KPn z;52L2thm4_KR^Gh!Kp;+Vn>k)p>_u*=f8q}j9v+GSC>Ji7?#M=(k&yQN{u#d(v2rMth3I5brn$WIV-pj=RQ?pg} zP)wYwNefOf+DTiQeOYmFalaQ|oR*-L#AVdS80rM8%H)DfQJB#S)3o&`wVN-8c^w-iKegQLH>~HJq5S z73>)P{D*FleHN}jbSLEQEQ}V zDds{{AVy8tMywbo75eIoqD>(ng|}f0F;zK{uLn*j)-f~UGZPzEtt)(*&l6d$QU1M^ za0-`a#K!Z>91hD;4(+thb9<_w@wr5+-DJhoDkc^5qM(Q+t zC-=A3)U?+!A9=(+Zrr%L%gTzbh?czB+1VHHqWKMFEa|A%>&qKEc5K8uy48enBq_Cz zS+c$gaNNz~+*4#5G4^rMEPWwatt;Ga_qd@$hbBGt*kfJP{+kNQWHOJZV>q3j$DmA1 zZ$L;Egx&)6&kvxjU*+WFSOMV7SK_EDUT{K%l69^k2|^b)YmF33#A@%xS!m5) zwYTsa`TmBI6d*|rUqpybH(1mnhHKnAaT+3t6M=&>;036oT)F<-ta(e=tBHx`I zMUdp@Lrltc5JmIT(7wHJ>^rR1)Mw#1AI!_ki|Jii9KQ2hlqQ%2^S5xkhXv8HJvG%{ zI&9dmzXM!V;n;4H7fl8Yl2cD2w1?WdO|6X|^lwEuy=raz7SL%g5ovFIx$ny^b2q>F zl(VknUFZAbtDdTQamwNqi*KU+qNoE7x13IAcaO($zq)yPc)i{`eLi0TfT`oiks~k0 zw^Y)>^ay)C0Fhfg9(xbJ-+x?ZKV>M)`S>d@omErZ-7QQoS|u|Ic#6qCndLOGW7b0000 localizedStrings; + final List languages; + + ClosedHouseholdLocalization(this.locale, this.localizedStrings, this.languages); + + // Method to get the current localization instance from context + static ClosedHouseholdLocalization of(BuildContext context) { + return Localizations.of(context, ClosedHouseholdLocalization)!; + } + + static final List _localizedStrings = []; + + // Method to get the delegate for localization + static LocalizationsDelegate getDelegate( + Future localizedStrings, List languages) => + ClosedHouseholdLocalizationDelegate(localizedStrings, languages); + + // Method to load localized strings + Future load() async { + _localizedStrings.clear(); + // Iterate over localized strings and filter based on locale + for (var element in await localizedStrings) { + if (element.locale == '${locale.languageCode}_${locale.countryCode}') { + _localizedStrings.add(element); + } + } + + return true; + } + + // Method to translate a given localized value + String translate(String localizedValues) { + if (_localizedStrings.isEmpty) { + return localizedValues; + } else { + final index = _localizedStrings.indexWhere( + (medium) => medium.code == localizedValues, + ); + + return index != -1 ? _localizedStrings[index].message : localizedValues; + } + } +} diff --git a/packages/closed_household/lib/blocs/closed_household.dart b/packages/closed_household/lib/blocs/closed_household.dart new file mode 100644 index 000000000..9d85ae83b --- /dev/null +++ b/packages/closed_household/lib/blocs/closed_household.dart @@ -0,0 +1,343 @@ +import 'dart:async'; + +import 'package:digit_data_model/data_model.dart'; +import 'package:digit_data_model/models/entities/address_type.dart'; +import 'package:digit_data_model/utils/typedefs.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:registration_delivery/models/entities/household.dart'; +import 'package:registration_delivery/models/entities/household_member.dart'; +import 'package:registration_delivery/models/entities/project_beneficiary.dart'; +import 'package:registration_delivery/models/entities/status.dart' + as reg_status; +import 'package:registration_delivery/models/entities/task.dart'; +import 'package:registration_delivery/utils/typedefs.dart'; + +import '../utils/utils.dart'; + +part 'closed_household.freezed.dart'; + +typedef ClosedHouseholdEmitter = Emitter; + +class ClosedHouseholdBloc + extends Bloc { + final IndividualDataRepository individualRepository; + + final HouseholdDataRepository householdRepository; + + final HouseholdMemberDataRepository householdMemberRepository; + + final ProjectBeneficiaryDataRepository projectBeneficiaryRepository; + + final TaskDataRepository taskRepository; + + ClosedHouseholdBloc( + super.initialState, { + required this.individualRepository, + required this.householdRepository, + required this.householdMemberRepository, + required this.projectBeneficiaryRepository, + required this.taskRepository, + }) { + on(_handleSubmit); + on(_handleSummary); + } + + FutureOr _handleSubmit( + ClosedHouseholdSubmitEvent event, + ClosedHouseholdEmitter emit, + ) async { + emit(state.copyWith(loading: true)); + + var locality = LocalityModel( + code: ClosedHouseholdSingleton().boundary!.code!, + name: ClosedHouseholdSingleton().boundary!.name!); + + try { + var address = AddressModel( + latitude: event.latitude, + longitude: event.longitude, + locationAccuracy: event.locationAccuracy, + type: AddressType.correspondence, + locality: LocalityModel( + code: ClosedHouseholdSingleton().boundary!.code!, + name: ClosedHouseholdSingleton().boundary!.name, + ), + tenantId: ClosedHouseholdSingleton().tenantId, + rowVersion: 1, + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + var household = HouseholdModel( + clientReferenceId: IdGen.i.identifier, + address: address, + memberCount: 1, + rowVersion: 1, + tenantId: ClosedHouseholdSingleton().tenantId.toString(), + longitude: event.longitude, + latitude: event.latitude, + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + var individual = IndividualModel( + clientReferenceId: IdGen.i.identifier, + tenantId: ClosedHouseholdSingleton().tenantId, + rowVersion: 1, + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + var name = NameModel( + givenName: event.householdHeadName, + individualClientReferenceId: individual.clientReferenceId, + tenantId: ClosedHouseholdSingleton().tenantId, + rowVersion: 1, + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + var identifier = IdentifierModel( + clientReferenceId: individual.clientReferenceId, + tenantId: ClosedHouseholdSingleton().tenantId, + rowVersion: 1, + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + + var projectBeneficiary = ProjectBeneficiaryModel( + tag: event.tag, + rowVersion: 1, + tenantId: ClosedHouseholdSingleton().tenantId, + clientReferenceId: IdGen.i.identifier, + dateOfRegistration: DateTime.now().millisecondsSinceEpoch, + projectId: ClosedHouseholdSingleton().projectId, + beneficiaryClientReferenceId: + ClosedHouseholdSingleton().beneficiaryType == + BeneficiaryType.individual + ? individual.clientReferenceId + : household.clientReferenceId, + clientAuditDetails: ClientAuditDetails( + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + + individual = individual.copyWith( + name: name, + address: [ + address.copyWith( + relatedClientReferenceId: individual.clientReferenceId, + auditDetails: individual.auditDetails, + clientAuditDetails: individual.clientAuditDetails, + locality: locality, + ), + ], + identifiers: [ + identifier.copyWith( + identifierId: IdGen.i.identifier, + identifierType: 'DEFAULT', + ), + ], + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + var householdMember = HouseholdMemberModel( + householdClientReferenceId: household.clientReferenceId, + individualClientReferenceId: individual.clientReferenceId, + isHeadOfHousehold: true, + tenantId: ClosedHouseholdSingleton().tenantId, + rowVersion: 1, + clientReferenceId: IdGen.i.identifier, + clientAuditDetails: ClientAuditDetails( + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + ), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid.toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + + var task = TaskModel( + projectBeneficiaryClientReferenceId: + projectBeneficiary.clientReferenceId, + clientReferenceId: IdGen.i.identifier, + tenantId: ClosedHouseholdSingleton().tenantId, + projectId: ClosedHouseholdSingleton().projectId, + rowVersion: 1, + address: address, + status: reg_status.Status.closeHousehold.toValue(), + auditDetails: AuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid!, + createdTime: DateTime.now().millisecondsSinceEpoch, + ), + clientAuditDetails: ClientAuditDetails( + createdBy: ClosedHouseholdSingleton().loggedInUserUuid!, + createdTime: DateTime.now().millisecondsSinceEpoch, + ), + ); + + await householdRepository.create( + household.copyWith( + address: address.copyWith( + relatedClientReferenceId: household.clientReferenceId, + auditDetails: individual.auditDetails, + clientAuditDetails: individual.clientAuditDetails, + locality: locality, + ), + ), + ); + + final initialModifiedAt = DateTime.now().millisecondsSinceEpoch; + await individualRepository.create( + individual.copyWith( + address: [ + address.copyWith( + relatedClientReferenceId: individual.clientReferenceId, + auditDetails: individual.auditDetails, + clientAuditDetails: individual.clientAuditDetails, + locality: locality, + ), + ], + ), + ); + + await projectBeneficiaryRepository.create( + projectBeneficiary, + ); + + await householdMemberRepository.create(householdMember.copyWith( + clientAuditDetails: householdMember.clientAuditDetails!.copyWith( + lastModifiedTime: initialModifiedAt, + ))); + + await taskRepository.create(task); + + emit(state.copyWith(loading: false)); + } catch (error) { + rethrow; + } + } + + FutureOr _handleSummary( + ClosedHouseholdSummaryEvent event, + ClosedHouseholdEmitter emit, + ) async { + emit(state.copyWith( + longitude: event.longitude, + latitude: event.latitude, + locationAccuracy: event.locationAccuracy, + householdHeadName: event.householdHeadName, + )); + } +} + +@freezed +class ClosedHouseholdEvent with _$ClosedHouseholdEvent { + const factory ClosedHouseholdEvent.handleSubmit( + {@Default(0) double latitude, + @Default(0) double longitude, + @Default(0) double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context}) = ClosedHouseholdSubmitEvent; + + const factory ClosedHouseholdEvent.handleSummary({ + @Default(0) double latitude, + @Default(0) double longitude, + @Default(0) double locationAccuracy, + String? householdHeadName, + }) = ClosedHouseholdSummaryEvent; +} + +@freezed +class ClosedHouseholdState with _$ClosedHouseholdState { + const factory ClosedHouseholdState({ + @Default(false) bool loading, + @Default(false) bool isEditing, + @Default(0) double latitude, + @Default(0) double longitude, + @Default(0) double locationAccuracy, + String? householdHeadName, + }) = _ClosedHouseholdState; +} diff --git a/packages/closed_household/lib/blocs/closed_household.freezed.dart b/packages/closed_household/lib/blocs/closed_household.freezed.dart new file mode 100644 index 000000000..4604ceeb8 --- /dev/null +++ b/packages/closed_household/lib/blocs/closed_household.freezed.dart @@ -0,0 +1,831 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'closed_household.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$ClosedHouseholdEvent { + double get latitude => throw _privateConstructorUsedError; + double get longitude => throw _privateConstructorUsedError; + double get locationAccuracy => throw _privateConstructorUsedError; + String? get householdHeadName => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context) + handleSubmit, + required TResult Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName) + handleSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context)? + handleSubmit, + TResult? Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName)? + handleSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName, String? tag, BuildContext? context)? + handleSubmit, + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName)? + handleSummary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(ClosedHouseholdSubmitEvent value) handleSubmit, + required TResult Function(ClosedHouseholdSummaryEvent value) handleSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult? Function(ClosedHouseholdSummaryEvent value)? handleSummary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult Function(ClosedHouseholdSummaryEvent value)? handleSummary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $ClosedHouseholdEventCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ClosedHouseholdEventCopyWith<$Res> { + factory $ClosedHouseholdEventCopyWith(ClosedHouseholdEvent value, + $Res Function(ClosedHouseholdEvent) then) = + _$ClosedHouseholdEventCopyWithImpl<$Res, ClosedHouseholdEvent>; + @useResult + $Res call( + {double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName}); +} + +/// @nodoc +class _$ClosedHouseholdEventCopyWithImpl<$Res, + $Val extends ClosedHouseholdEvent> + implements $ClosedHouseholdEventCopyWith<$Res> { + _$ClosedHouseholdEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? latitude = null, + Object? longitude = null, + Object? locationAccuracy = null, + Object? householdHeadName = freezed, + }) { + return _then(_value.copyWith( + latitude: null == latitude + ? _value.latitude + : latitude // ignore: cast_nullable_to_non_nullable + as double, + longitude: null == longitude + ? _value.longitude + : longitude // ignore: cast_nullable_to_non_nullable + as double, + locationAccuracy: null == locationAccuracy + ? _value.locationAccuracy + : locationAccuracy // ignore: cast_nullable_to_non_nullable + as double, + householdHeadName: freezed == householdHeadName + ? _value.householdHeadName + : householdHeadName // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ClosedHouseholdSubmitEventImplCopyWith<$Res> + implements $ClosedHouseholdEventCopyWith<$Res> { + factory _$$ClosedHouseholdSubmitEventImplCopyWith( + _$ClosedHouseholdSubmitEventImpl value, + $Res Function(_$ClosedHouseholdSubmitEventImpl) then) = + __$$ClosedHouseholdSubmitEventImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context}); +} + +/// @nodoc +class __$$ClosedHouseholdSubmitEventImplCopyWithImpl<$Res> + extends _$ClosedHouseholdEventCopyWithImpl<$Res, + _$ClosedHouseholdSubmitEventImpl> + implements _$$ClosedHouseholdSubmitEventImplCopyWith<$Res> { + __$$ClosedHouseholdSubmitEventImplCopyWithImpl( + _$ClosedHouseholdSubmitEventImpl _value, + $Res Function(_$ClosedHouseholdSubmitEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? latitude = null, + Object? longitude = null, + Object? locationAccuracy = null, + Object? householdHeadName = freezed, + Object? tag = freezed, + Object? context = freezed, + }) { + return _then(_$ClosedHouseholdSubmitEventImpl( + latitude: null == latitude + ? _value.latitude + : latitude // ignore: cast_nullable_to_non_nullable + as double, + longitude: null == longitude + ? _value.longitude + : longitude // ignore: cast_nullable_to_non_nullable + as double, + locationAccuracy: null == locationAccuracy + ? _value.locationAccuracy + : locationAccuracy // ignore: cast_nullable_to_non_nullable + as double, + householdHeadName: freezed == householdHeadName + ? _value.householdHeadName + : householdHeadName // ignore: cast_nullable_to_non_nullable + as String?, + tag: freezed == tag + ? _value.tag + : tag // ignore: cast_nullable_to_non_nullable + as String?, + context: freezed == context + ? _value.context + : context // ignore: cast_nullable_to_non_nullable + as BuildContext?, + )); + } +} + +/// @nodoc + +class _$ClosedHouseholdSubmitEventImpl implements ClosedHouseholdSubmitEvent { + const _$ClosedHouseholdSubmitEventImpl( + {this.latitude = 0, + this.longitude = 0, + this.locationAccuracy = 0, + this.householdHeadName, + this.tag, + this.context}); + + @override + @JsonKey() + final double latitude; + @override + @JsonKey() + final double longitude; + @override + @JsonKey() + final double locationAccuracy; + @override + final String? householdHeadName; + @override + final String? tag; + @override + final BuildContext? context; + + @override + String toString() { + return 'ClosedHouseholdEvent.handleSubmit(latitude: $latitude, longitude: $longitude, locationAccuracy: $locationAccuracy, householdHeadName: $householdHeadName, tag: $tag, context: $context)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ClosedHouseholdSubmitEventImpl && + (identical(other.latitude, latitude) || + other.latitude == latitude) && + (identical(other.longitude, longitude) || + other.longitude == longitude) && + (identical(other.locationAccuracy, locationAccuracy) || + other.locationAccuracy == locationAccuracy) && + (identical(other.householdHeadName, householdHeadName) || + other.householdHeadName == householdHeadName) && + (identical(other.tag, tag) || other.tag == tag) && + (identical(other.context, context) || other.context == context)); + } + + @override + int get hashCode => Object.hash(runtimeType, latitude, longitude, + locationAccuracy, householdHeadName, tag, context); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ClosedHouseholdSubmitEventImplCopyWith<_$ClosedHouseholdSubmitEventImpl> + get copyWith => __$$ClosedHouseholdSubmitEventImplCopyWithImpl< + _$ClosedHouseholdSubmitEventImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context) + handleSubmit, + required TResult Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName) + handleSummary, + }) { + return handleSubmit( + latitude, longitude, locationAccuracy, householdHeadName, tag, context); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context)? + handleSubmit, + TResult? Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName)? + handleSummary, + }) { + return handleSubmit?.call( + latitude, longitude, locationAccuracy, householdHeadName, tag, context); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName, String? tag, BuildContext? context)? + handleSubmit, + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName)? + handleSummary, + required TResult orElse(), + }) { + if (handleSubmit != null) { + return handleSubmit(latitude, longitude, locationAccuracy, + householdHeadName, tag, context); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(ClosedHouseholdSubmitEvent value) handleSubmit, + required TResult Function(ClosedHouseholdSummaryEvent value) handleSummary, + }) { + return handleSubmit(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult? Function(ClosedHouseholdSummaryEvent value)? handleSummary, + }) { + return handleSubmit?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult Function(ClosedHouseholdSummaryEvent value)? handleSummary, + required TResult orElse(), + }) { + if (handleSubmit != null) { + return handleSubmit(this); + } + return orElse(); + } +} + +abstract class ClosedHouseholdSubmitEvent implements ClosedHouseholdEvent { + const factory ClosedHouseholdSubmitEvent( + {final double latitude, + final double longitude, + final double locationAccuracy, + final String? householdHeadName, + final String? tag, + final BuildContext? context}) = _$ClosedHouseholdSubmitEventImpl; + + @override + double get latitude; + @override + double get longitude; + @override + double get locationAccuracy; + @override + String? get householdHeadName; + String? get tag; + BuildContext? get context; + @override + @JsonKey(ignore: true) + _$$ClosedHouseholdSubmitEventImplCopyWith<_$ClosedHouseholdSubmitEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$ClosedHouseholdSummaryEventImplCopyWith<$Res> + implements $ClosedHouseholdEventCopyWith<$Res> { + factory _$$ClosedHouseholdSummaryEventImplCopyWith( + _$ClosedHouseholdSummaryEventImpl value, + $Res Function(_$ClosedHouseholdSummaryEventImpl) then) = + __$$ClosedHouseholdSummaryEventImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName}); +} + +/// @nodoc +class __$$ClosedHouseholdSummaryEventImplCopyWithImpl<$Res> + extends _$ClosedHouseholdEventCopyWithImpl<$Res, + _$ClosedHouseholdSummaryEventImpl> + implements _$$ClosedHouseholdSummaryEventImplCopyWith<$Res> { + __$$ClosedHouseholdSummaryEventImplCopyWithImpl( + _$ClosedHouseholdSummaryEventImpl _value, + $Res Function(_$ClosedHouseholdSummaryEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? latitude = null, + Object? longitude = null, + Object? locationAccuracy = null, + Object? householdHeadName = freezed, + }) { + return _then(_$ClosedHouseholdSummaryEventImpl( + latitude: null == latitude + ? _value.latitude + : latitude // ignore: cast_nullable_to_non_nullable + as double, + longitude: null == longitude + ? _value.longitude + : longitude // ignore: cast_nullable_to_non_nullable + as double, + locationAccuracy: null == locationAccuracy + ? _value.locationAccuracy + : locationAccuracy // ignore: cast_nullable_to_non_nullable + as double, + householdHeadName: freezed == householdHeadName + ? _value.householdHeadName + : householdHeadName // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc + +class _$ClosedHouseholdSummaryEventImpl implements ClosedHouseholdSummaryEvent { + const _$ClosedHouseholdSummaryEventImpl( + {this.latitude = 0, + this.longitude = 0, + this.locationAccuracy = 0, + this.householdHeadName}); + + @override + @JsonKey() + final double latitude; + @override + @JsonKey() + final double longitude; + @override + @JsonKey() + final double locationAccuracy; + @override + final String? householdHeadName; + + @override + String toString() { + return 'ClosedHouseholdEvent.handleSummary(latitude: $latitude, longitude: $longitude, locationAccuracy: $locationAccuracy, householdHeadName: $householdHeadName)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ClosedHouseholdSummaryEventImpl && + (identical(other.latitude, latitude) || + other.latitude == latitude) && + (identical(other.longitude, longitude) || + other.longitude == longitude) && + (identical(other.locationAccuracy, locationAccuracy) || + other.locationAccuracy == locationAccuracy) && + (identical(other.householdHeadName, householdHeadName) || + other.householdHeadName == householdHeadName)); + } + + @override + int get hashCode => Object.hash( + runtimeType, latitude, longitude, locationAccuracy, householdHeadName); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ClosedHouseholdSummaryEventImplCopyWith<_$ClosedHouseholdSummaryEventImpl> + get copyWith => __$$ClosedHouseholdSummaryEventImplCopyWithImpl< + _$ClosedHouseholdSummaryEventImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context) + handleSubmit, + required TResult Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName) + handleSummary, + }) { + return handleSummary( + latitude, longitude, locationAccuracy, householdHeadName); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName, + String? tag, + BuildContext? context)? + handleSubmit, + TResult? Function(double latitude, double longitude, + double locationAccuracy, String? householdHeadName)? + handleSummary, + }) { + return handleSummary?.call( + latitude, longitude, locationAccuracy, householdHeadName); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName, String? tag, BuildContext? context)? + handleSubmit, + TResult Function(double latitude, double longitude, double locationAccuracy, + String? householdHeadName)? + handleSummary, + required TResult orElse(), + }) { + if (handleSummary != null) { + return handleSummary( + latitude, longitude, locationAccuracy, householdHeadName); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(ClosedHouseholdSubmitEvent value) handleSubmit, + required TResult Function(ClosedHouseholdSummaryEvent value) handleSummary, + }) { + return handleSummary(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult? Function(ClosedHouseholdSummaryEvent value)? handleSummary, + }) { + return handleSummary?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ClosedHouseholdSubmitEvent value)? handleSubmit, + TResult Function(ClosedHouseholdSummaryEvent value)? handleSummary, + required TResult orElse(), + }) { + if (handleSummary != null) { + return handleSummary(this); + } + return orElse(); + } +} + +abstract class ClosedHouseholdSummaryEvent implements ClosedHouseholdEvent { + const factory ClosedHouseholdSummaryEvent( + {final double latitude, + final double longitude, + final double locationAccuracy, + final String? householdHeadName}) = _$ClosedHouseholdSummaryEventImpl; + + @override + double get latitude; + @override + double get longitude; + @override + double get locationAccuracy; + @override + String? get householdHeadName; + @override + @JsonKey(ignore: true) + _$$ClosedHouseholdSummaryEventImplCopyWith<_$ClosedHouseholdSummaryEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$ClosedHouseholdState { + bool get loading => throw _privateConstructorUsedError; + bool get isEditing => throw _privateConstructorUsedError; + double get latitude => throw _privateConstructorUsedError; + double get longitude => throw _privateConstructorUsedError; + double get locationAccuracy => throw _privateConstructorUsedError; + String? get householdHeadName => throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $ClosedHouseholdStateCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ClosedHouseholdStateCopyWith<$Res> { + factory $ClosedHouseholdStateCopyWith(ClosedHouseholdState value, + $Res Function(ClosedHouseholdState) then) = + _$ClosedHouseholdStateCopyWithImpl<$Res, ClosedHouseholdState>; + @useResult + $Res call( + {bool loading, + bool isEditing, + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName}); +} + +/// @nodoc +class _$ClosedHouseholdStateCopyWithImpl<$Res, + $Val extends ClosedHouseholdState> + implements $ClosedHouseholdStateCopyWith<$Res> { + _$ClosedHouseholdStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? loading = null, + Object? isEditing = null, + Object? latitude = null, + Object? longitude = null, + Object? locationAccuracy = null, + Object? householdHeadName = freezed, + }) { + return _then(_value.copyWith( + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + isEditing: null == isEditing + ? _value.isEditing + : isEditing // ignore: cast_nullable_to_non_nullable + as bool, + latitude: null == latitude + ? _value.latitude + : latitude // ignore: cast_nullable_to_non_nullable + as double, + longitude: null == longitude + ? _value.longitude + : longitude // ignore: cast_nullable_to_non_nullable + as double, + locationAccuracy: null == locationAccuracy + ? _value.locationAccuracy + : locationAccuracy // ignore: cast_nullable_to_non_nullable + as double, + householdHeadName: freezed == householdHeadName + ? _value.householdHeadName + : householdHeadName // ignore: cast_nullable_to_non_nullable + as String?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ClosedHouseholdStateImplCopyWith<$Res> + implements $ClosedHouseholdStateCopyWith<$Res> { + factory _$$ClosedHouseholdStateImplCopyWith(_$ClosedHouseholdStateImpl value, + $Res Function(_$ClosedHouseholdStateImpl) then) = + __$$ClosedHouseholdStateImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {bool loading, + bool isEditing, + double latitude, + double longitude, + double locationAccuracy, + String? householdHeadName}); +} + +/// @nodoc +class __$$ClosedHouseholdStateImplCopyWithImpl<$Res> + extends _$ClosedHouseholdStateCopyWithImpl<$Res, _$ClosedHouseholdStateImpl> + implements _$$ClosedHouseholdStateImplCopyWith<$Res> { + __$$ClosedHouseholdStateImplCopyWithImpl(_$ClosedHouseholdStateImpl _value, + $Res Function(_$ClosedHouseholdStateImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? loading = null, + Object? isEditing = null, + Object? latitude = null, + Object? longitude = null, + Object? locationAccuracy = null, + Object? householdHeadName = freezed, + }) { + return _then(_$ClosedHouseholdStateImpl( + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + isEditing: null == isEditing + ? _value.isEditing + : isEditing // ignore: cast_nullable_to_non_nullable + as bool, + latitude: null == latitude + ? _value.latitude + : latitude // ignore: cast_nullable_to_non_nullable + as double, + longitude: null == longitude + ? _value.longitude + : longitude // ignore: cast_nullable_to_non_nullable + as double, + locationAccuracy: null == locationAccuracy + ? _value.locationAccuracy + : locationAccuracy // ignore: cast_nullable_to_non_nullable + as double, + householdHeadName: freezed == householdHeadName + ? _value.householdHeadName + : householdHeadName // ignore: cast_nullable_to_non_nullable + as String?, + )); + } +} + +/// @nodoc + +class _$ClosedHouseholdStateImpl implements _ClosedHouseholdState { + const _$ClosedHouseholdStateImpl( + {this.loading = false, + this.isEditing = false, + this.latitude = 0, + this.longitude = 0, + this.locationAccuracy = 0, + this.householdHeadName}); + + @override + @JsonKey() + final bool loading; + @override + @JsonKey() + final bool isEditing; + @override + @JsonKey() + final double latitude; + @override + @JsonKey() + final double longitude; + @override + @JsonKey() + final double locationAccuracy; + @override + final String? householdHeadName; + + @override + String toString() { + return 'ClosedHouseholdState(loading: $loading, isEditing: $isEditing, latitude: $latitude, longitude: $longitude, locationAccuracy: $locationAccuracy, householdHeadName: $householdHeadName)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ClosedHouseholdStateImpl && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.isEditing, isEditing) || + other.isEditing == isEditing) && + (identical(other.latitude, latitude) || + other.latitude == latitude) && + (identical(other.longitude, longitude) || + other.longitude == longitude) && + (identical(other.locationAccuracy, locationAccuracy) || + other.locationAccuracy == locationAccuracy) && + (identical(other.householdHeadName, householdHeadName) || + other.householdHeadName == householdHeadName)); + } + + @override + int get hashCode => Object.hash(runtimeType, loading, isEditing, latitude, + longitude, locationAccuracy, householdHeadName); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ClosedHouseholdStateImplCopyWith<_$ClosedHouseholdStateImpl> + get copyWith => + __$$ClosedHouseholdStateImplCopyWithImpl<_$ClosedHouseholdStateImpl>( + this, _$identity); +} + +abstract class _ClosedHouseholdState implements ClosedHouseholdState { + const factory _ClosedHouseholdState( + {final bool loading, + final bool isEditing, + final double latitude, + final double longitude, + final double locationAccuracy, + final String? householdHeadName}) = _$ClosedHouseholdStateImpl; + + @override + bool get loading; + @override + bool get isEditing; + @override + double get latitude; + @override + double get longitude; + @override + double get locationAccuracy; + @override + String? get householdHeadName; + @override + @JsonKey(ignore: true) + _$$ClosedHouseholdStateImplCopyWith<_$ClosedHouseholdStateImpl> + get copyWith => throw _privateConstructorUsedError; +} diff --git a/packages/closed_household/lib/blocs/closed_household_localization_delegate.dart b/packages/closed_household/lib/blocs/closed_household_localization_delegate.dart new file mode 100644 index 000000000..ae3165f1c --- /dev/null +++ b/packages/closed_household/lib/blocs/closed_household_localization_delegate.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; +import 'app_localization.dart'; + +class ClosedHouseholdLocalizationDelegate + extends LocalizationsDelegate { + final Future localizedStrings; + final List languages; + + const ClosedHouseholdLocalizationDelegate(this.localizedStrings, this.languages); + + @override + bool isSupported(Locale locale) { + return languages.map((e) { + final results = e.value.split('_'); + if (results.isNotEmpty) return results.first; + }).contains(locale.languageCode); + } + + @override + Future load(Locale locale) async { + ClosedHouseholdLocalization localization = + ClosedHouseholdLocalization(locale, localizedStrings, languages); + await localization.load(); + + return localization; + } + + @override + bool shouldReload(covariant LocalizationsDelegate old) { + return true; + } +} diff --git a/packages/closed_household/lib/closed_household.dart b/packages/closed_household/lib/closed_household.dart new file mode 100644 index 000000000..c490c8973 --- /dev/null +++ b/packages/closed_household/lib/closed_household.dart @@ -0,0 +1,14 @@ +@MappableLib( + generateInitializerForScope: InitializerScope.package, +) +library closed_household; + +import 'package:dart_mappable/dart_mappable.dart'; + +export 'blocs/app_localization.dart'; +export 'blocs/closed_household.dart'; +export 'utils/utils.dart' show ClosedHouseholdSingleton; +export 'pages/closed_household_details.dart'; +export 'pages/closed_household_summary.dart'; +export 'pages/closed_household_acknowledgement.dart'; +export 'router/closed_household_router.dart'; \ No newline at end of file diff --git a/packages/closed_household/lib/pages/closed_household_acknowledgement.dart b/packages/closed_household/lib/pages/closed_household_acknowledgement.dart new file mode 100644 index 000000000..8cdc00795 --- /dev/null +++ b/packages/closed_household/lib/pages/closed_household_acknowledgement.dart @@ -0,0 +1,47 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/material.dart'; + +import '../../../utils/i18_key_constants.dart' as i18; +import '../../../widgets/localized.dart'; + +@RoutePage() +class ClosedHouseholdAcknowledgementPage extends LocalizedStatefulWidget { + + const ClosedHouseholdAcknowledgementPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => + _ClosedHouseholdAcknowledgementPageState(); +} + +class _ClosedHouseholdAcknowledgementPageState + extends LocalizedState { + @override + Widget build(BuildContext context) { + return PopScope( + canPop: false, + child: Scaffold( + body: DigitAcknowledgement.success( + action: () { + final parent = context.router.parent() as StackRouter; + // Pop twice to navigate back to the previous screen + parent.popUntilRoot(); + }, + enableViewHousehold: false, + actionLabel: localizations + .translate(i18.acknowledgementSuccess.actionLabelText), + description: localizations.translate( + i18.acknowledgementSuccess.acknowledgementDescriptionText, + ), + label: localizations.translate( + i18.acknowledgementSuccess.acknowledgementLabelText, + ), + ), + ), + ); + } +} diff --git a/packages/closed_household/lib/pages/closed_household_details.dart b/packages/closed_household/lib/pages/closed_household_details.dart new file mode 100644 index 000000000..5058973c6 --- /dev/null +++ b/packages/closed_household/lib/pages/closed_household_details.dart @@ -0,0 +1,205 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/closed_household.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; +import 'package:digit_components/widgets/atoms/text_block.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:reactive_forms/reactive_forms.dart'; + +import '../../utils/i18_key_constants.dart' as i18; +import '../router/closed_household_router.gm.dart'; +import '../utils/utils.dart'; +import '../widgets/back_navigation_help_header.dart'; +import '../widgets/localized.dart'; + +@RoutePage() +class ClosedHouseholdDetailsPage extends LocalizedStatefulWidget { + const ClosedHouseholdDetailsPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => + ClosedHouseholdDetailsPageState(); +} + +class ClosedHouseholdDetailsPageState + extends LocalizedState { + static const _administrationAreaKey = 'administrationArea'; + static const _householdHeadNameKey = 'householdHeadName'; + static const _latKey = 'lat'; + static const _lngKey = 'lng'; + static const _accuracyKey = 'accuracy'; + static const maxLength = 64; + + @override + void initState() { + context.read().add(const LoadLocationEvent()); + + WidgetsBinding.instance.addPostFrameCallback((_) { + // Show the dialog after the first frame is built + DigitComponentsUtils().showLocationCapturingDialog( + context, + localizations.translate(i18.common.locationCapturing), + DigitSyncDialogType.inProgress, + ); + }); + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final bloc = context.read(); + + return Scaffold( + body: ReactiveFormBuilder( + form: () => buildForm(bloc.state), + builder: (_, form, __) => BlocListener( + listener: (context, locationState) { + if (locationState.accuracy != null) { + //Hide the dialog after 1 seconds + Future.delayed(const Duration(seconds: 1), () { + DigitComponentsUtils().hideLocationDialog(context); + }); + } + final lat = locationState.latitude; + final lng = locationState.longitude; + final accuracy = locationState.accuracy; + form.control(_latKey).value ??= lat; + form.control(_lngKey).value ??= lng; + form.control(_accuracyKey).value ??= accuracy; + }, + listenWhen: (previous, current) { + final lat = form.control(_latKey).value; + final lng = form.control(_lngKey).value; + final accuracy = form.control(_accuracyKey).value; + + return lat != null || lng != null || accuracy != null + ? false + : true; + }, + child: BlocBuilder( + builder: (context, state) { + return ScrollableContent( + enableFixedButton: true, + header: const Column( + children: [ + BackNavigationHelpHeaderWidget( + showHelp: false, + ), + ], + ), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: BlocBuilder( + builder: (context, locationState) { + return DigitElevatedButton( + onPressed: () { + final String? householdHeadName = form + .control(_householdHeadNameKey) + .value as String?; + + context.read().add( + ClosedHouseholdEvent.handleSummary( + latitude: locationState.latitude!, + longitude: locationState.longitude!, + locationAccuracy: locationState.accuracy!, + householdHeadName: householdHeadName != null && + householdHeadName.trim().isNotEmpty + ? householdHeadName + : null, + ), + ); + + context.router.push(ClosedHouseholdSummaryRoute()); + }, + child: Center( + child: Text( + localizations.translate( + i18.common.coreCommonNext, + ), + ), + ), + ); + }, + ), + ), + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + TextBlock( + heading: localizations.translate( + i18.closeHousehold.closeHouseHoldDetailLabel, + ), + headingStyle: theme.textTheme.displayMedium, + body: localizations.translate( + i18.closeHousehold.closeHouseHoldDetailDescLabel, + ), + ), + Column(children: [ + DigitTextFormField( + formControlName: _administrationAreaKey, + label: localizations.translate( + i18.closeHousehold.villageName, + ), + readOnly: true, + ), + DigitTextFormField( + readOnly: true, + formControlName: _accuracyKey, + label: localizations.translate( + i18.closeHousehold.accuracyLabel, + ), + ), + DigitTextFormField( + formControlName: _householdHeadNameKey, + label: localizations.translate( + i18.closeHousehold.headNameLabel, + ), + validationMessages: { + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', maxLength.toString()), + }, + ), + ]), + ], + ), + ), + ), + ], + ); + }), + ), + ), + ); + } + + FormGroup buildForm(ClosedHouseholdState state) { + return fb.group({ + _administrationAreaKey: FormControl( + value: localizations + .translate(ClosedHouseholdSingleton().boundary!.name.toString()), + validators: [Validators.required], + ), + _householdHeadNameKey: FormControl( + value: null, + validators: [ + CustomValidator.requiredMin, + Validators.maxLength(200), + ], + ), + _latKey: FormControl(validators: []), + _lngKey: FormControl(), + _accuracyKey: FormControl(), + }); + } +} diff --git a/packages/closed_household/lib/pages/closed_household_summary.dart b/packages/closed_household/lib/pages/closed_household_summary.dart new file mode 100644 index 000000000..826af79f4 --- /dev/null +++ b/packages/closed_household/lib/pages/closed_household_summary.dart @@ -0,0 +1,188 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/blocs/closed_household.dart'; +import 'package:closed_household/router/closed_household_router.gm.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_components/widgets/atoms/details_card.dart'; +import 'package:digit_scanner/blocs/scanner.dart'; +import 'package:digit_scanner/pages/qr_scanner.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../../widgets/localized.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../utils/utils.dart'; +import '../widgets/back_navigation_help_header.dart'; +import '../widgets/showcase/showcase_button.dart'; + +@RoutePage() +class ClosedHouseholdSummaryPage extends LocalizedStatefulWidget { + const ClosedHouseholdSummaryPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => + ClosedHouseholdSummaryPageState(); +} + +class ClosedHouseholdSummaryPageState + extends LocalizedState { + String getLocalizedMessage(String code) { + return localizations.translate(code); + } + + @override + void initState() { + context + .read() + .add(const DigitScannerEvent.handleScanner(qrCode: [], barCode: [])); + super.initState(); + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + builder: (context, householdState) { + return Scaffold( + body: ScrollableContent( + enableFixedButton: true, + header: const BackNavigationHelpHeaderWidget( + showHelp: false, + showcaseButton: ShowcaseButton(), + ), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: + const EdgeInsets.fromLTRB(kPadding, kPadding, kPadding, 0), + child: BlocBuilder( + builder: (context, scannerState) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + DigitOutlineIconButton( + buttonStyle: OutlinedButton.styleFrom( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.zero, + ), + ), + onPressed: () { + Navigator.of(context).push( + // [TODO: Add the route to auto_route] + MaterialPageRoute( + builder: (context) => const DigitScannerPage( + quantity: 1, + isGS1code: false, + singleValue: true, + ), + settings: + const RouteSettings(name: '/qr-scanner'), + ), + ); + }, + icon: Icons.qr_code, + label: localizations.translate(i18 + .closeHousehold.closeHouseholdVoucherScannerLabel), + ), + DigitElevatedButton( + onPressed: () { + context.read().add( + ClosedHouseholdEvent.handleSubmit( + context: context, + householdHeadName: + householdState.householdHeadName, + locationAccuracy: + householdState.locationAccuracy, + longitude: householdState.longitude, + latitude: householdState.latitude, + tag: scannerState.qrCodes.isNotEmpty + ? scannerState.qrCodes.first + : null)); + + ///clear the scanner + context.router + .push(ClosedHouseholdAcknowledgementRoute()); + }, + child: Center( + child: Text( + localizations + .translate(i18.common.coreCommonSubmit), + ), + ), + ), + ], + ); + }), + ), + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + DigitCard( + child: LabelValueList( + heading: localizations.translate( + i18.closeHousehold.closeHouseholdSummaryLabel), + withDivider: false, + items: [ + LabelValuePair( + label: localizations.translate( + i18.closeHousehold.closeHouseholdDate), + value: (DigitDateUtils.getDateFromTimestamp( + DateTime.now().millisecondsSinceEpoch, + dateFormat: 'dd MMM yyyy')) + .toString(), + ), + LabelValuePair( + label: localizations.translate( + i18.closeHousehold.closeHouseholdVillageName), + value: ClosedHouseholdSingleton() + .boundary! + .name + .toString(), + ), + LabelValuePair( + label: localizations.translate( + i18.closeHousehold.closeHouseholdHeadName), + value: householdState.householdHeadName ?? + localizations + .translate(i18.common.coreCommonNA), + ), + LabelValuePair( + label: localizations.translate(i18 + .closeHousehold.closeHouseholdGpsAccuracyLabel), + value: householdState.locationAccuracy != null + ? '${householdState.locationAccuracy.toStringAsFixed(2)} ${localizations.translate(i18.common.coreCommonMeters)}' + : localizations + .translate(i18.common.coreCommonNA), + ), + ]), + ), + BlocBuilder( + builder: (context, state) { + if (state.qrCodes.isNotEmpty) { + return DigitCard( + child: LabelValueList( + heading: localizations.translate(i18.closeHousehold + .closeHouseholdVoucherSummaryLabel), + withDivider: false, + items: [ + LabelValuePair( + label: localizations.translate(i18.closeHousehold + .closeHouseholdVoucherCodeLabel), + value: state.qrCodes.first, + ), + ], + ), + ); + } else { + return const SizedBox(); + } + }), + ], + ), + ) + ])); + }); + } +} diff --git a/packages/closed_household/lib/pages/closed_household_wrapper.dart b/packages/closed_household/lib/pages/closed_household_wrapper.dart new file mode 100644 index 000000000..3bcab0b3b --- /dev/null +++ b/packages/closed_household/lib/pages/closed_household_wrapper.dart @@ -0,0 +1,50 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/blocs/closed_household.dart'; +import 'package:closed_household/closed_household.dart'; +import 'package:closed_household/utils/extensions/extensions.dart'; +import 'package:digit_data_model/models/entities/individual.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/models/entities/household.dart'; +import 'package:registration_delivery/models/entities/household_member.dart'; +import 'package:registration_delivery/models/entities/project_beneficiary.dart'; +import 'package:registration_delivery/models/entities/task.dart'; + +@RoutePage() +class ClosedHouseholdWrapperPage extends StatelessWidget { + const ClosedHouseholdWrapperPage({ + super.key, + }); + + @override + Widget build(BuildContext context) { + return MultiBlocProvider( + providers: [ + BlocProvider( + create: (_) { + return ClosedHouseholdBloc( + const ClosedHouseholdState(), + householdMemberRepository: context.repository< + HouseholdMemberModel, HouseholdMemberSearchModel>(context), + householdRepository: context + .repository(context), + individualRepository: context + .repository(context), + projectBeneficiaryRepository: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(context), + taskRepository: + context.repository(context), + ); + }, + lazy: false, + ), + ], + child: BlocBuilder( + builder: (context, houseHoldOverviewState) { + return const AutoRouter(); + }, + ), + ); + } +} diff --git a/packages/closed_household/lib/router/closed_household_router.dart b/packages/closed_household/lib/router/closed_household_router.dart new file mode 100644 index 000000000..ead0995e8 --- /dev/null +++ b/packages/closed_household/lib/router/closed_household_router.dart @@ -0,0 +1,31 @@ +import 'package:auto_route/auto_route.dart'; + +import 'closed_household_router.gm.dart'; + + +@AutoRouterConfig.module() +class ClosedHouseholdPackageRoute extends $ClosedHouseholdPackageRoute { + @override + RouteType get defaultRouteType => const RouteType.material(); + + @override + List routes = [ + AutoRoute( + page: ClosedHouseholdWrapperRoute.page, + path: 'closed-household-wrapper', + children: [ + AutoRoute( + page: ClosedHouseholdDetailsRoute.page, + path: 'closed-household-details', + initial: true, + ), + AutoRoute( + page: ClosedHouseholdSummaryRoute.page, + path: 'closed-household-summary'), + AutoRoute( + page: ClosedHouseholdAcknowledgementRoute.page, + path: 'closed-household-acknowledgement'), + ]), + + ]; +} diff --git a/packages/closed_household/lib/router/closed_household_router.gm.dart b/packages/closed_household/lib/router/closed_household_router.gm.dart new file mode 100644 index 000000000..5cf8d0251 --- /dev/null +++ b/packages/closed_household/lib/router/closed_household_router.gm.dart @@ -0,0 +1,195 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +// ************************************************************************** +// AutoRouterGenerator +// ************************************************************************** + +// ignore_for_file: type=lint +// coverage:ignore-file + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'package:auto_route/auto_route.dart' as _i5; +import 'package:closed_household/blocs/app_localization.dart' as _i7; +import 'package:closed_household/closed_household.dart' as _i8; +import 'package:closed_household/pages/closed_household_acknowledgement.dart' + as _i1; +import 'package:closed_household/pages/closed_household_details.dart' as _i2; +import 'package:closed_household/pages/closed_household_summary.dart' as _i3; +import 'package:closed_household/pages/closed_household_wrapper.dart' as _i4; +import 'package:flutter/material.dart' as _i6; + +abstract class $ClosedHouseholdPackageRoute extends _i5.AutoRouterModule { + @override + final Map pagesMap = { + ClosedHouseholdAcknowledgementRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const ClosedHouseholdAcknowledgementRouteArgs()); + return _i5.AutoRoutePage( + routeData: routeData, + child: _i1.ClosedHouseholdAcknowledgementPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, + ClosedHouseholdDetailsRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const ClosedHouseholdDetailsRouteArgs()); + return _i5.AutoRoutePage( + routeData: routeData, + child: _i2.ClosedHouseholdDetailsPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, + ClosedHouseholdSummaryRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const ClosedHouseholdSummaryRouteArgs()); + return _i5.AutoRoutePage( + routeData: routeData, + child: _i3.ClosedHouseholdSummaryPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, + ClosedHouseholdWrapperRoute.name: (routeData) { + return _i5.AutoRoutePage( + routeData: routeData, + child: const _i4.ClosedHouseholdWrapperPage(), + ); + }, + }; +} + +/// generated route for +/// [_i1.ClosedHouseholdAcknowledgementPage] +class ClosedHouseholdAcknowledgementRoute + extends _i5.PageRouteInfo { + ClosedHouseholdAcknowledgementRoute({ + _i6.Key? key, + _i7.ClosedHouseholdLocalization? appLocalizations, + List<_i5.PageRouteInfo>? children, + }) : super( + ClosedHouseholdAcknowledgementRoute.name, + args: ClosedHouseholdAcknowledgementRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'ClosedHouseholdAcknowledgementRoute'; + + static const _i5.PageInfo page = + _i5.PageInfo(name); +} + +class ClosedHouseholdAcknowledgementRouteArgs { + const ClosedHouseholdAcknowledgementRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i6.Key? key; + + final _i7.ClosedHouseholdLocalization? appLocalizations; + + @override + String toString() { + return 'ClosedHouseholdAcknowledgementRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i2.ClosedHouseholdDetailsPage] +class ClosedHouseholdDetailsRoute + extends _i5.PageRouteInfo { + ClosedHouseholdDetailsRoute({ + _i6.Key? key, + _i8.ClosedHouseholdLocalization? appLocalizations, + List<_i5.PageRouteInfo>? children, + }) : super( + ClosedHouseholdDetailsRoute.name, + args: ClosedHouseholdDetailsRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'ClosedHouseholdDetailsRoute'; + + static const _i5.PageInfo page = + _i5.PageInfo(name); +} + +class ClosedHouseholdDetailsRouteArgs { + const ClosedHouseholdDetailsRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i6.Key? key; + + final _i8.ClosedHouseholdLocalization? appLocalizations; + + @override + String toString() { + return 'ClosedHouseholdDetailsRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i3.ClosedHouseholdSummaryPage] +class ClosedHouseholdSummaryRoute + extends _i5.PageRouteInfo { + ClosedHouseholdSummaryRoute({ + _i6.Key? key, + _i7.ClosedHouseholdLocalization? appLocalizations, + List<_i5.PageRouteInfo>? children, + }) : super( + ClosedHouseholdSummaryRoute.name, + args: ClosedHouseholdSummaryRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'ClosedHouseholdSummaryRoute'; + + static const _i5.PageInfo page = + _i5.PageInfo(name); +} + +class ClosedHouseholdSummaryRouteArgs { + const ClosedHouseholdSummaryRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i6.Key? key; + + final _i7.ClosedHouseholdLocalization? appLocalizations; + + @override + String toString() { + return 'ClosedHouseholdSummaryRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i4.ClosedHouseholdWrapperPage] +class ClosedHouseholdWrapperRoute extends _i5.PageRouteInfo { + const ClosedHouseholdWrapperRoute({List<_i5.PageRouteInfo>? children}) + : super( + ClosedHouseholdWrapperRoute.name, + initialChildren: children, + ); + + static const String name = 'ClosedHouseholdWrapperRoute'; + + static const _i5.PageInfo page = _i5.PageInfo(name); +} diff --git a/packages/closed_household/lib/utils/constants.dart b/packages/closed_household/lib/utils/constants.dart new file mode 100644 index 000000000..00223163c --- /dev/null +++ b/packages/closed_household/lib/utils/constants.dart @@ -0,0 +1,7 @@ +class Constants { + + final String dateFormat = 'dd/MM/yyyy'; + final String notAvailable = 'N/A'; + final String dateTimeExtFormat = 'dd-MM-yyyy'; + static const String checklistViewDateFormat = 'dd/MM/yyyy hh:mm a'; +} \ No newline at end of file diff --git a/packages/closed_household/lib/utils/extensions/context_utility.dart b/packages/closed_household/lib/utils/extensions/context_utility.dart new file mode 100644 index 000000000..9e29ab907 --- /dev/null +++ b/packages/closed_household/lib/utils/extensions/context_utility.dart @@ -0,0 +1,28 @@ +part of 'extensions.dart'; + +extension ContextUtilityExtensions on BuildContext { + int millisecondsSinceEpoch([DateTime? dateTime]) { + return (dateTime ?? DateTime.now()).millisecondsSinceEpoch; + } + + Future get packageInfo async { + final info = await PackageInfo.fromPlatform(); + + return info.version; + } + + + DataRepository + repository( + BuildContext context, + ) { + switch (ClosedHouseholdSingleton().persistenceConfiguration) { + case PersistenceConfiguration.offlineFirst: + return context.read>(); + case PersistenceConfiguration.onlineOnly: + return context.read>(); + default: + return context.read>(); + } + } +} diff --git a/packages/closed_household/lib/utils/extensions/extensions.dart b/packages/closed_household/lib/utils/extensions/extensions.dart new file mode 100644 index 000000000..a9f422079 --- /dev/null +++ b/packages/closed_household/lib/utils/extensions/extensions.dart @@ -0,0 +1,67 @@ +// Importing necessary packages and files +import 'package:digit_data_model/data_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:intl/intl.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import '../constants.dart'; + +import '../utils.dart'; + +part 'context_utility.dart'; + +// Extension to calculate age based on a DateTime object. +extension DateAgeExtension on DateTime { + int get age { + DateTime currentDate = DateTime.now(); + int ageInYears = currentDate.year - year; + int ageInMonths = currentDate.month - month; + + if (currentDate.day < day) { + ageInMonths--; + } + + if (ageInMonths < 0) { + ageInYears--; + ageInMonths += 12; + } + + return ageInYears; + } +} + +// Extension to format a DateTime object to a string. +extension DateTimeExtension on DateTime? { + String? getFormattedDate() { + if (this == null) return null; + + return DateFormat(Constants().dateTimeExtFormat).format(this!); + } +} + +// Extension to increment an integer by a specific value. +extension IntIncrementer on int? { + int get increment { + return _incrementBy(1); + } + + int _incrementBy(int value) { + return this == null ? value : (this! + value); + } +} + +// Extension to remove duplicates from a list based on a provided constraint. +extension UniqueListItem on List { + void removeDuplicates(I Function(E element) constraintMapper) { + final distinctList = map(constraintMapper).toSet(); + + retainWhere((element) => distinctList.remove(constraintMapper(element))); + } +} + +// Extension to convert an integer (epoch) to a DateTime object. +extension EpochToDateTime on int? { + DateTime? get toDateTime { + return this == null ? null : DateTime.fromMillisecondsSinceEpoch(this!); + } +} diff --git a/packages/closed_household/lib/utils/i18_key_constants.dart b/packages/closed_household/lib/utils/i18_key_constants.dart new file mode 100644 index 000000000..cd87d39cf --- /dev/null +++ b/packages/closed_household/lib/utils/i18_key_constants.dart @@ -0,0 +1,169 @@ +const common = Common(); +const acknowledgementSuccess = AcknowledgementSuccess(); +const closeHousehold = CloseHousehold(); +const closedHouseholdDetailsShowcase = ClosedHouseholdDetailsShowcase(); + +class Common { + const Common(); + + String get coreCommonContinue => 'CORE_COMMON_CONTINUE'; + + String get coreCommonAge => 'CORE_COMMON_AGE'; + + String get coreCommonName => 'CORE_COMMON_NAME'; + + String get coreCommonEmailId => 'CORE_COMMON_EMAIL_ID'; + + String get coreCommonGender => 'CORE_COMMON_GENDER'; + + String get coreCommonMobileNumber => 'CORE_COMMON_MOBILE_NUMBER'; + + String get coreCommonSubmit => 'CORE_COMMON_SUBMIT'; + + String get coreCommonSave => 'CORE_COMMON_SAVE'; + + String get coreCommonCancel => 'CORE_COMMON_CANCEL'; + + String get corecommonRequired => 'CORE_COMMON_REQUIRED'; + + String get searchByName => 'CORE_COMMON_SEARCH_BY_NAME'; + + String get coreCommonReasonRequired => 'CORE_COMMON_REASON_REQUIRED'; + + String get corecommonclose => 'CORE_COMMON_CLOSE'; + + String get coreCommonOk => 'CORE_COMMON_OK'; + + String get coreCommonNA => 'CORE_COMMON_NA'; + + String get coreCommonProfile => 'CORE_COMMON_PROFILE'; + + String get coreCommonLogout => 'CORE_COMMON_LOGOUT'; + + String get coreCommonBack => 'CORE_COMMON_BACK'; + + String get coreCommonHelp => 'CORE_COMMON_HELP'; + + String get coreCommonHome => 'CORE_COMMON_HOME'; + + String get coreCommonViewDownloadedData => 'CORE_COMMON_VIEW_DOWNLOADED_DATA'; + + String get coreCommonlanguage => 'CORE_COMMON_LANGUAGE'; + + String get coreCommonSyncProgress => 'CORE_COMMON_SYNC_PROGRESS'; + + String get coreCommonDataSynced => 'CORE_COMMON_DATA_SYNCED'; + + String get coreCommonDataSyncFailed => 'CORE_COMMON_DATA_SYNC_FAILED'; + + String get coreCommonDataSyncRetry => 'CORE_COMMON_DATA_SYNC_RETRY'; + + String get connectionLabel => 'CORE_COMMON_CONNECTION_LABEL'; + + String get connectionContent => 'CORE_COMMON_CONNECTION_CONTENT'; + + String get coreCommonSkip => 'CORE_COMMON_SKIP'; + + String get coreCommonNext => 'CORE_COMMON_NEXT'; + + String get coreCommonYes => 'CORE_COMMON_YES'; + + String get coreCommonNo => 'CORE_COMMON_NO'; + String get coreCommonGoback => 'CORE_COMMON_GO_BACK'; + + String get coreCommonRequiredItems => 'CORE_COMMON_REQUIRED_ITEMS'; + + String get min2CharsRequired => 'MIN_2_CHARS_REQUIRED'; + + String get maxCharsRequired => 'MAX_CHARS_ALLOWED'; + + String get maxValue => 'MAX_VALUE_ALLOWED'; + String get minValue => 'MIN_VALUE_ALLOWED'; + + String get noResultsFound => 'NO_RESULTS_FOUND'; + + String get noProjectSelected => 'NO_PROJECT_SELECTED'; + + String get coreCommonSyncInProgress => 'CORE_COMMON_SYNC_IN_PROGRESS'; + + String get facilitySearchHeaderLabel => 'FACILITY_SEARCH_HEADER_LABEL'; + String get projectFacilitySearchHeaderLabel => + 'PROJECT_FACILITY_SEARCH_HEADER_LABEL'; + + String get coreCommonDownload => 'CORE_COMMON_DOWNLOAD'; + + String get coreCommonDownloadFailed => 'CORE_COMMON_DOWNLOAD_FAILED'; + + String get noMatchFound => 'CORE_COMMON_NO_MATCH_FOUND'; + + String get scanBales => 'CORE_COMMON_SCAN_BALES'; + String get ageInMonths => 'AGE_IN_MONTHS_LABEL'; + String get locationCapturing => 'CAPTURING_LOCATION'; + String get coreCommonMeters => 'CORE_COMMON_METERS'; +} + + +class AcknowledgementSuccess { + const AcknowledgementSuccess(); + + String get actionLabelText => 'ACKNOWLEDGEMENT_SUCCESS_ACTION_LABEL_TEXT'; + + String get acknowledgementDescriptionText => + 'ACKNOWLEDGEMENT_SUCCESS_DESCRIPTION_TEXT'; + + String get acknowledgementLabelText => 'ACKNOWLEDGEMENT_SUCCESS_LABEL_TEXT'; + + String get goToHome => 'GO_TO_HOME_SCREEN'; + String get downloadmoredata => 'DOWNLOAD_MORE_DATA'; + String get dataDownloadedSuccessLabel => 'DATA_DOWNLOADED_SUCCESS_LABEL'; +} + +class CloseHousehold { + const CloseHousehold(); + + String get closeHouseHoldDetailLabel => 'CLOSE_HOUSEHOLD_DETAIL_LABEL'; + + String get closeHouseHoldDetailDescLabel => 'CLOSE_HOUSEHOLD_DETAIL_DESC_LABEL'; + + String get villageName => 'CLOSE_HOUSEHOLD_VILLAGE_NAME_LABEL'; + + String get accuracyLabel => 'CLOSE_HOUSEHOLD_GPS_ACCURACY_LABEL'; + + String get headNameLabel => 'CLOSE_HOUSEHOLD_HEAD_NAME_LABEL'; + + String get closeHouseholdDate => 'CLOSE_HOUSEHOLD_SUMMARY_DATE_LABEL'; + + String get closeHouseholdVillageName => 'CLOSE_HOUSEHOLD_SUMMARY_VILLAGE_NAME_LABEL'; + + String get closeHouseholdHeadName => 'CLOSE_HOUSEHOLD_SUMMARY_HEAD_NAME_LABEL'; + + String get closeHouseholdGpsAccuracyLabel => 'CLOSE_HOUSEHOLD_SUMMARY_GPS_ACCURACY_LABEL'; + + String get closeHouseholdSummaryLabel => 'CLOSE_HOUSEHOLD_SUMMARY_LABEL'; + + String get closeHouseholdVoucherSummaryLabel => 'CLOSE_HOUSEHOLD_SUMMARY_VOUCHERS_LABEL'; + + String get closeHouseholdVoucherCodeLabel => 'CLOSE_HOUSEHOLD_SUMMARY_VOUCHER_CODE_LABEL'; + + String get closeHouseholdVoucherScannerLabel => 'CLOSE_HOUSEHOLD_VOUCHER_SCANNER_LABEL'; +} + + +class ClosedHouseholdDetailsShowcase { + const ClosedHouseholdDetailsShowcase(); + + String get villageName { + return 'HOUSEHOLD_LOCATION_SHOWCASE_VILLAGE_NAME'; + } + + String get gpsAccuracy { + return 'HOUSEHOLD_LOCATION_SHOWCASE_GPS_ACCURACY'; + } + + String get householdHeadName { + return 'HOUSEHOLD_LOCATION_SHOWCASE_HEAD_NAME'; + } + +} + + diff --git a/packages/closed_household/lib/utils/utils.dart b/packages/closed_household/lib/utils/utils.dart new file mode 100644 index 000000000..4c0de8bf5 --- /dev/null +++ b/packages/closed_household/lib/utils/utils.dart @@ -0,0 +1,69 @@ +// create a singleton class for Closed Household package where set data and get data methods are defined + +import 'package:digit_data_model/data_model.dart'; +import 'package:reactive_forms/reactive_forms.dart'; + +/// This class contains custom validators for form controls. +class CustomValidator { + /// Validates that control's value must be `true` + static Map? requiredMin( + AbstractControl control, + ) { + return control.value == null || + control.value.toString().length >= 2 || + control.value.toString().trim().isEmpty + ? null + : {'required': true}; + } +} + +class ClosedHouseholdSingleton { + static final ClosedHouseholdSingleton _singleton = + ClosedHouseholdSingleton._internal(); + + factory ClosedHouseholdSingleton() { + return _singleton; + } + + ClosedHouseholdSingleton._internal(); + + String? _tenantId; + String? _loggedInUserUuid; + String? _projectId; + BoundaryModel? _boundaryModel; + BeneficiaryType? _beneficiaryType; + + PersistenceConfiguration? _persistenceConfiguration = PersistenceConfiguration + .offlineFirst; // Default to offline first persistence configuration + + void setBoundary({required BoundaryModel boundary}) { + _boundaryModel = boundary; + } + + void setPersistenceConfiguration( + {required PersistenceConfiguration persistenceConfiguration}) { + _persistenceConfiguration = persistenceConfiguration; + } + + void setInitialData({ + required String loggedInUserUuid, + required String projectId, + required BeneficiaryType beneficiaryType, + }) { + _loggedInUserUuid = loggedInUserUuid; + _projectId = projectId; + _beneficiaryType = beneficiaryType; + } + + void setTenantId(String tenantId) { + _tenantId = tenantId; + } + + String? get tenantId => _tenantId; + String? get loggedInUserUuid => _loggedInUserUuid; + String? get projectId => _projectId; + PersistenceConfiguration? get persistenceConfiguration => + _persistenceConfiguration; + BoundaryModel? get boundary => _boundaryModel; + BeneficiaryType? get beneficiaryType => _beneficiaryType; +} diff --git a/packages/closed_household/lib/widgets/back_navigation_help_header.dart b/packages/closed_household/lib/widgets/back_navigation_help_header.dart new file mode 100644 index 000000000..251c8e6a3 --- /dev/null +++ b/packages/closed_household/lib/widgets/back_navigation_help_header.dart @@ -0,0 +1,85 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/blocs/app_localization.dart'; +import 'package:closed_household/widgets/showcase/showcase_button.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/material.dart'; + +import '../../utils/i18_key_constants.dart' as i18; + +class BackNavigationHelpHeaderWidget extends StatelessWidget { + final bool showHelp; + final bool showBackNavigation; + final bool showLogoutCTA; + final VoidCallback? helpClicked; + final VoidCallback? handleBack; + final ShowcaseButton? showcaseButton; + + const BackNavigationHelpHeaderWidget({ + super.key, + this.showHelp = false, //hiding help + this.showBackNavigation = true, + this.showLogoutCTA = false, + this.helpClicked, + this.handleBack, + this.showcaseButton, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Padding( + padding: const EdgeInsets.all(kPadding / 2), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + if (showBackNavigation) + Flexible( + child: TextButton.icon( + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.onBackground, + padding: EdgeInsets.zero, + ), + onPressed: () { + context.router.maybePop(); + handleBack != null ? handleBack!() : null; + }, + icon: const Icon(Icons.arrow_left_sharp), + label: Text( + ClosedHouseholdLocalization.of(context).translate( + i18.common.coreCommonBack, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ), + ], + ), + ), + SizedBox(width: showHelp ? kPadding * 2 : 0), + if (showHelp) + TextButton( + style: TextButton.styleFrom(padding: EdgeInsets.zero), + onPressed: helpClicked, + child: Row( + children: [ + Text( + ClosedHouseholdLocalization.of(context) + .translate(i18.common.coreCommonHelp), + overflow: TextOverflow.ellipsis, + ), + const Icon( + Icons.help_outline_outlined, + ), // Add the icon to the right + ], + ), + ), + SizedBox(width: showcaseButton != null ? 16 : 0), + if (showcaseButton != null) showcaseButton!, + ], + ), + ); + } +} diff --git a/packages/closed_household/lib/widgets/localized.dart b/packages/closed_household/lib/widgets/localized.dart new file mode 100644 index 000000000..35b88fe1b --- /dev/null +++ b/packages/closed_household/lib/widgets/localized.dart @@ -0,0 +1,33 @@ +import 'package:flutter/material.dart'; +import '../blocs/app_localization.dart'; + +abstract class LocalizedStatefulWidget extends StatefulWidget { + final ClosedHouseholdLocalization? appLocalizations; + + const LocalizedStatefulWidget({ + super.key, + this.appLocalizations, + }); +} + +abstract class LocalizedState + extends State { + late ClosedHouseholdLocalization _localizations; + + ClosedHouseholdLocalization get localizations => _localizations; + + set localizations(ClosedHouseholdLocalization localizations) { + if (mounted) { + setState(() { + _localizations = localizations; + }); + } + } + + @override + @mustCallSuper + void didChangeDependencies() { + _localizations = widget.appLocalizations ?? ClosedHouseholdLocalization.of(context); + super.didChangeDependencies(); + } +} diff --git a/packages/closed_household/lib/widgets/showcase/config/closed_household_details.dart b/packages/closed_household/lib/widgets/showcase/config/closed_household_details.dart new file mode 100644 index 000000000..4363942ab --- /dev/null +++ b/packages/closed_household/lib/widgets/showcase/config/closed_household_details.dart @@ -0,0 +1,31 @@ +part of 'showcase_constants.dart'; + +class _ClosedHouseholdDetailsShowcaseData { + static final _ClosedHouseholdDetailsShowcaseData _instance = + _ClosedHouseholdDetailsShowcaseData._(); + + _ClosedHouseholdDetailsShowcaseData._(); + + factory _ClosedHouseholdDetailsShowcaseData() => _instance; + + List get showcaseData => [ + villageName, + gpsAccuracy, + householdHeadName, + ]; + + final villageName = ShowcaseItemBuilder( + messageLocalizationKey: i18.closedHouseholdDetailsShowcase.villageName, + ); + + final gpsAccuracy = ShowcaseItemBuilder( + messageLocalizationKey: + i18.closedHouseholdDetailsShowcase.gpsAccuracy, + ); + + final householdHeadName = ShowcaseItemBuilder( + messageLocalizationKey: + i18.closedHouseholdDetailsShowcase.householdHeadName, + ); + +} diff --git a/packages/closed_household/lib/widgets/showcase/config/showcase_constants.dart b/packages/closed_household/lib/widgets/showcase/config/showcase_constants.dart new file mode 100644 index 000000000..db1a08d79 --- /dev/null +++ b/packages/closed_household/lib/widgets/showcase/config/showcase_constants.dart @@ -0,0 +1,7 @@ +import '../../../utils/i18_key_constants.dart' as i18; +import '../showcase_wrappers.dart'; + + +part 'closed_household_details.dart'; + +final closedHouseholdDetailsShowcaseData = _ClosedHouseholdDetailsShowcaseData(); diff --git a/packages/closed_household/lib/widgets/showcase/showcase_button.dart b/packages/closed_household/lib/widgets/showcase/showcase_button.dart new file mode 100644 index 000000000..9e7b1f968 --- /dev/null +++ b/packages/closed_household/lib/widgets/showcase/showcase_button.dart @@ -0,0 +1,73 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:closed_household/blocs/app_localization.dart'; +import 'package:closed_household/router/closed_household_router.gm.dart'; +import 'package:digit_components/theme/digit_theme.dart'; +import 'package:digit_showcase/showcase_widget.dart'; +import 'package:flutter/material.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../localized.dart'; +import 'config/showcase_constants.dart'; + +class ShowcaseButton extends LocalizedStatefulWidget { + final Iterable? showcaseFor; + + const ShowcaseButton({super.key, this.showcaseFor}); + + @override + LocalizedState createState() => _ShowcaseButtonState(); +} + +class _ShowcaseButtonState extends LocalizedState { + @override + Widget build(BuildContext context) { + return TextButton( + style: TextButton.styleFrom(padding: EdgeInsets.zero), + onPressed: () { + if (widget.showcaseFor?.isNotEmpty == true) { + ShowcaseWidget.of(context).startShowCase( + widget.showcaseFor!.toList(), + ); + + return; + } + + final current = context.router.current.name; + final paths = _showcasePathsForRoute(current); + + if (paths == null) return; + if (paths.isEmpty) return; + + ShowcaseWidget.of(context).startShowCase(paths.toList()); + }, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB( + kPadding, + kPadding, + kPadding / 2, + kPadding, + ), + child: Text( + ClosedHouseholdLocalization.of(context) + .translate(i18.common.coreCommonHelp), + overflow: TextOverflow.ellipsis, + ), + ), + const Icon(Icons.help_outline), + ], + ), + ); + } + + Iterable? _showcasePathsForRoute(String routeName) { + switch (routeName) { + case ClosedHouseholdDetailsRoute.name: + return closedHouseholdDetailsShowcaseData.showcaseData.map( + (e) => e.showcaseKey, + ); + default: + return null; + } + } +} diff --git a/packages/closed_household/lib/widgets/showcase/showcase_wrappers.dart b/packages/closed_household/lib/widgets/showcase/showcase_wrappers.dart new file mode 100644 index 000000000..a2ac9e398 --- /dev/null +++ b/packages/closed_household/lib/widgets/showcase/showcase_wrappers.dart @@ -0,0 +1,65 @@ +import 'package:digit_showcase/showcase.dart'; +import 'package:flutter/material.dart'; + +import '../localized.dart'; + +const kPadding = 8.0; + +class ShowcaseItemBuilder { + final GlobalKey showcaseKey; + final String messageLocalizationKey; + + ShowcaseItemBuilder({required this.messageLocalizationKey}) + : showcaseKey = GlobalKey(debugLabel: messageLocalizationKey); + + Widget buildWith({required Widget child}) => ShowcaseItemWrapperWidget( + showcaseKey: showcaseKey, + messageLocalizationKey: messageLocalizationKey, + child: child, + ); +} + +class ShowcaseItemWrapperWidget extends LocalizedStatefulWidget { + final Widget child; + final String messageLocalizationKey; + final GlobalKey showcaseKey; + + const ShowcaseItemWrapperWidget({ + super.key, + required this.messageLocalizationKey, + required this.child, + required this.showcaseKey, + }); + + @override + LocalizedState createState() => + _ShowcaseItemWrapperWidgetState(); +} + +class _ShowcaseItemWrapperWidgetState + extends LocalizedState { + @override + Widget build(BuildContext context) { + return Showcase( + key: widget.showcaseKey, + disableMovingAnimation: true, + disableScaleAnimation: true, + description: localizations.translate(widget.messageLocalizationKey), + targetPadding: const EdgeInsets.fromLTRB( + kPadding / 2, + kPadding / 2, + kPadding / 2, + kPadding / 2, + ), + child: Container( + padding: const EdgeInsets.fromLTRB( + kPadding / 2, + kPadding / 2, + kPadding / 2, + kPadding / 2, + ), + child: widget.child, + ), + ); + } +} diff --git a/packages/closed_household/pubspec.yaml b/packages/closed_household/pubspec.yaml new file mode 100644 index 000000000..26dd71e26 --- /dev/null +++ b/packages/closed_household/pubspec.yaml @@ -0,0 +1,62 @@ +name: closed_household +description: This package enables health facility workers to mark household closed and update. +version: 1.0.1 +homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/develop/packages/closed_household +repository: https://github.com/egovernments/health-campaign-field-worker-app + +environment: + sdk: '>=3.0.0 <4.0.0' + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + digit_components: ^1.0.0+9 + flutter_bloc: ^8.1.1 + freezed_annotation: ^2.1.0 + build_runner: ^2.2.1 + reactive_forms: ^14.1.0 + fluttertoast: ^8.1.2 + overlay_builder: ^1.1.0 + intl: ^0.18.0 + flutter_svg: ^2.0.8 + dart_mappable: ^4.2.0 + drift: ^2.0.0 + sqlite3_flutter_libs: ^0.5.10 + path_provider: ^2.0.11 + path: ^1.8.2 + drift_db_viewer: ^2.0.0 + uuid: ^3.0.6 + recase: ^4.1.0 + pluto_grid: ^7.0.1 + digit_scanner: ^1.0.2 + gs1_barcode_parser: ^1.0.5 + auto_route: ^7.8.4 + digit_data_model: ^1.0.3 + package_info_plus: ^5.0.1 + digit_showcase: ^1.0.0 + collection: ^1.16.0 + flutter_keyboard_visibility: ^5.4.0 + stream_transform: ^2.1.0 + async: ^2.11.0 + formula_parser: ^2.0.1 + registration_delivery: ^1.0.3 + + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^3.0.1 + dart_code_metrics: ^5.7.6 + freezed: ^2.1.0+1 + json_serializable: ^6.4.0 + drift_dev: ^2.14.1 + bloc_test: ^9.1.0 + mocktail: ^1.0.2 + dart_mappable_builder: ^4.2.0 + auto_route_generator: ^7.3.2 + +flutter: + assets: + - assets/images/ + - assets/icons/svg/ \ No newline at end of file diff --git a/packages/closed_household/test/closed_household_test.dart b/packages/closed_household/test/closed_household_test.dart new file mode 100644 index 000000000..bc833007d --- /dev/null +++ b/packages/closed_household/test/closed_household_test.dart @@ -0,0 +1,4 @@ + +void main() { + //TODO: add tests +} diff --git a/packages/digit_components/CHANGELOG.md b/packages/digit_components/CHANGELOG.md index 03c6603f6..8ad9209a7 100644 --- a/packages/digit_components/CHANGELOG.md +++ b/packages/digit_components/CHANGELOG.md @@ -1,109 +1,112 @@ -## 0.0.1 - -* Initial Releaase - -## 0.0.1+1 - -* Read Me file added - -## 0.0.1+2 - -* Read Me file modified with Components example - -## 0.0.1+3 - -* example file added - -## 0.0.1+4 +## 1.0.1 +* Added new loader dialog -* dart doc added and auto generated files added - -## 0.0.1+5 - -* Example file with Reactive Forms - -## 0.0.1+6 - -* Updated Components behaviour in ReadMe File - -## 0.0.1+8 - -* Updated Images in ReadMe File - -## 0.0.2+0 +## 1.0.0+9 +* Added maximum validation for digit_integer_form_picker -* Updated digit_components to the latest version +## 1.0.0+8 +* Added close icon button for digit_dialog -## 0.0.2+1 +## 1.0.0+7 +* Added buttonDisabled for DigitIconButton -* Updated digit_components missing utils and components +## 1.0.0+6 +* Added text direction for DigitIconButton +* SelectionBox UI fixes +* Details card UI fixes -## 0.0.3+1 +## 1.0.0+5 +* Added new component details_card -* Synced digit_components with flutter 3.16.5 version +## 1.0.0+4 +* Added new component selected box -## 0.0.3+2 +## 1.0.0+3 +* Capture and Hide Location Dialog added to utils -* Updated repository URL and dart doc +## 1.0.0+2 +* DigitTextField component update -## 0.0.3+3 +## 1.0.0+1 +* Stable release with searchable dropdown fix -* Updated intl version 0.18.1 +## 1.0.0 +* Stable release -## 0.0.3+4 +## 0.0.3+16 +* Removed flutter_localizations dependency -* Updated example folder +## 0.0.3+15 +* Updated digit_components to develop branch -## 0.0.3+5 +## 0.0.3+14 +* Reactive Drop down fix -* Updated flutter sdk version +## 0.0.3+13 +* Fixed empty string issue in searchable_dropdown_field -## 0.0.3+6 +## 0.0.3+12 +* Downgraded intl to 0.18.0 -* Updated flutter repository url +## 0.0.3+11 +* Removed flutter localizations dependency -## 0.0.3+7 +## 0.0.3+10 +* Updated homepage url -* Updated intl version and added pubspec_override +## 0.0.3+9 +* Updated homepage url ## 0.0.3+8 +* Updated intl version and added pubspec_override +## 0.0.3+7 * Updated intl version and added pubspec_override -## 0.0.3+9 +## 0.0.3+6 +* Updated flutter repository url -* Updated homepage url +## 0.0.3+5 +* Updated flutter sdk version -## 0.0.3+10 +## 0.0.3+4 +* Updated example folder -* Updated homepage url +## 0.0.3+3 +* Updated intl version 0.18.1 -## 0.0.3+11 +## 0.0.3+2 +* Updated repository URL and dart doc -* Removed flutter localizations dependency +## 0.0.3+1 +* Synced digit_components with flutter 3.16.5 version -## 0.0.3+12 +## 0.0.2+1 +* Updated digit_components missing utils and components -* Downgraded intl to 0.18.0 +## 0.0.2+0 +* Updated digit_components to the latest version -## 0.0.3+13 +## 0.0.1+8 +* Updated Images in ReadMe File -* Fixed empty string issue in searchable_dropdown_field +## 0.0.1+6 +* Updated Components behaviour in ReadMe File -## 0.0.3+14 -* Reactive Drop down fix +## 0.0.1+5 +* Example file with Reactive Forms -## 0.0.3+15 -* Updated digit_components to develop branch +## 0.0.1+4 +* dart doc added and auto generated files added -## 0.0.3+16 -* Removed flutter_localizations dependency +## 0.0.1+3 +* example file added -## 1.0.0 -* Stable release +## 0.0.1+2 +* Read Me file modified with Components example -## 1.0.0+1 -* Stable release with searchable dropdown fix +## 0.0.1+1 +* Read Me file added -## 1.0.0+2 -* DigitTextField component update \ No newline at end of file +## 0.0.1 +* Initial Releaase \ No newline at end of file diff --git a/packages/digit_components/example/ios/Podfile b/packages/digit_components/example/ios/Podfile new file mode 100644 index 000000000..fdcc671eb --- /dev/null +++ b/packages/digit_components/example/ios/Podfile @@ -0,0 +1,44 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/packages/digit_components/example/pubspec.lock b/packages/digit_components/example/pubspec.lock index a599660fe..be10b5ed0 100644 --- a/packages/digit_components/example/pubspec.lock +++ b/packages/digit_components/example/pubspec.lock @@ -231,7 +231,7 @@ packages: path: ".." relative: true source: path - version: "1.0.0+2" + version: "1.0.0+8" easy_stepper: dependency: transitive description: diff --git a/packages/digit_components/lib/digit_components.dart b/packages/digit_components/lib/digit_components.dart index c777381b5..78a5a21fe 100644 --- a/packages/digit_components/lib/digit_components.dart +++ b/packages/digit_components/lib/digit_components.dart @@ -4,8 +4,9 @@ library digit_components; export 'blocs/location/location.dart'; export 'theme/theme.dart'; -export 'widgets/widgets.dart'; export 'utils/app_logger.dart'; +export 'utils/utils.dart'; +export 'widgets/widgets.dart'; class DigitUi { static const DigitUi _instance = DigitUi._internal(); diff --git a/packages/digit_components/lib/utils/utils.dart b/packages/digit_components/lib/utils/utils.dart new file mode 100644 index 000000000..3fecc38ee --- /dev/null +++ b/packages/digit_components/lib/utils/utils.dart @@ -0,0 +1,41 @@ +import 'package:digit_components/widgets/digit_sync_dialog.dart'; +import 'package:flutter/material.dart'; + +class DigitComponentsUtils { + void hideLocationDialog(BuildContext context) { // [TODO: create it as a common method since it has the similar behaviour of hideLocalizationLoadingDialog] + Navigator.of( + context, + rootNavigator: true, + ).popUntil( + (route) => route is! PopupRoute, + ); + } + + void showLocationCapturingDialog( + BuildContext context, String label, DigitSyncDialogType dialogType) { + DigitSyncDialog.show( + context, + type: dialogType, + label: label, + ); + } + + void hideLocalizationLoadingDialog(BuildContext context) { + Navigator.of( + context, + rootNavigator: true, + ).popUntil( + (route) => route is! PopupRoute, + ); + } + + void showLocalizationLoadingDialog( + BuildContext context, DigitSyncDialogType dialogType) { + DigitSyncDialog.show( + context, + type: dialogType, + ); + } + + static const String noResultSvg = 'assets/images/no_result.svg'; +} diff --git a/packages/digit_components/lib/widgets/atoms/details_card.dart b/packages/digit_components/lib/widgets/atoms/details_card.dart new file mode 100644 index 000000000..e79e0fccb --- /dev/null +++ b/packages/digit_components/lib/widgets/atoms/details_card.dart @@ -0,0 +1,127 @@ +import 'package:digit_components/theme/colors.dart'; +import 'package:digit_components/theme/digit_theme.dart'; +import 'package:digit_components/widgets/atoms/digit_divider.dart'; +import 'package:flutter/material.dart'; + +class LabelValueList extends StatelessWidget { + final List items; + final EdgeInsets? padding; + final String? heading; + final bool withDivider; + + const LabelValueList({ + Key? key, + required this.items, + this.padding, + this.heading, + this.withDivider = false, + + /// Default to no divider + }) : super(key: key); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final textTheme = theme.textTheme; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (heading != null) + Padding( + padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0), + child: Text( + heading!, + style: textTheme.headlineLarge?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + ..._buildItemsWithDividers(items, context), + ], + ); + } + + List _buildItemsWithDividers( + List items, BuildContext context) { + List itemList = []; + for (int i = 0; i < items.length; i++) { + itemList.add(_buildItem(items[i], context)); + if (i < items.length - 1 && withDivider) { + itemList.add( + const DigitDivider(), + ); + } + } + return itemList; + } + + Widget _buildItem(LabelValuePair item, BuildContext context) { + final theme = Theme.of(context); + final textTheme = theme.textTheme; + + return Padding( + padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0), + child: item.isInline + ? Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Label taking 30% width + Expanded( + flex: 6, // 45% width + child: Text( + item.label, + style: textTheme.headlineSmall?.copyWith( + height: 1.14, + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + const SizedBox( + width: kPadding * 4), // Gap between label and value + // Value taking rest of the width + Expanded( + flex: 8, // Remaining 55% width + child: Text( + item.value, + style: textTheme.bodyLarge?.copyWith( + height: 1.14, + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + ], + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + item.label, + style: textTheme.headlineSmall?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + const SizedBox(height: 4), + Text( + item.value, + style: textTheme.bodyMedium?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + ], + ), + ); + } +} + +class LabelValuePair { + final String label; + final String value; + final bool isInline; + + LabelValuePair({ + required this.label, + required this.value, + this.isInline = true, + }); +} diff --git a/packages/digit_components/lib/widgets/atoms/digit_icon_button.dart b/packages/digit_components/lib/widgets/atoms/digit_icon_button.dart index 8868ac1e0..7a2a734b2 100644 --- a/packages/digit_components/lib/widgets/atoms/digit_icon_button.dart +++ b/packages/digit_components/lib/widgets/atoms/digit_icon_button.dart @@ -8,6 +8,8 @@ class DigitIconButton extends StatelessWidget { final ImageIcon? imageIcon; final Color? iconColor; final Color? iconTextColor; + final TextDirection textDirection; + final bool buttonDisabled; const DigitIconButton({ super.key, @@ -18,6 +20,8 @@ class DigitIconButton extends StatelessWidget { this.imageIcon, this.iconColor, this.iconTextColor, + this.textDirection = TextDirection.ltr, + this.buttonDisabled = false, }); @override @@ -30,6 +34,7 @@ class DigitIconButton extends StatelessWidget { ), onPressed: onPressed, child: Row( + textDirection: textDirection, mainAxisSize: MainAxisSize.min, children: [ Flexible( @@ -37,7 +42,9 @@ class DigitIconButton extends StatelessWidget { Icon( icon, size: iconSize, - color: iconColor ?? theme.colorScheme.secondary, + color: buttonDisabled == false + ? iconColor ?? theme.colorScheme.secondary + : theme.colorScheme.outline, ), ), const SizedBox( @@ -47,7 +54,9 @@ class DigitIconButton extends StatelessWidget { Text( iconText!, style: TextStyle( - color: iconTextColor ?? theme.colorScheme.secondary, + color: buttonDisabled == false + ? iconTextColor ?? theme.colorScheme.secondary + : theme.colorScheme.outline, fontSize: 16), ), ], diff --git a/packages/digit_components/lib/widgets/atoms/digit_integer_form_picker.dart b/packages/digit_components/lib/widgets/atoms/digit_integer_form_picker.dart index 7f93e5da5..22bb2ce2d 100644 --- a/packages/digit_components/lib/widgets/atoms/digit_integer_form_picker.dart +++ b/packages/digit_components/lib/widgets/atoms/digit_integer_form_picker.dart @@ -10,6 +10,8 @@ class DigitIntegerFormPicker extends StatelessWidget { final String label; final FormGroup form; final String formControlName; + final double? buttonWidth; + final void Function()? onChange; const DigitIntegerFormPicker({ super.key, this.minimum, @@ -19,6 +21,8 @@ class DigitIntegerFormPicker extends StatelessWidget { this.hint, required this.form, required this.label, + this.buttonWidth, + this.onChange, }); @override @@ -41,30 +45,35 @@ class DigitIntegerFormPicker extends StatelessWidget { child: IntrinsicHeight( child: Row( children: [ - _buildButton( - context, - border: Border( - left: _borderSide, - bottom: _borderSide, - top: _borderSide, - ), - icon: Icons.remove, - onPressed: () => minimum != null + _buildButton(context, + border: Border( + left: _borderSide, + bottom: _borderSide, + top: _borderSide, + ), + icon: Icons.remove, onPressed: () { + minimum != null ? form.control(formControlName).value > minimum || form.control(formControlName).value == null ? form.control(formControlName).value -= 1 : 1 - : form.control(formControlName).value -= 1, - ), + : form.control(formControlName).value -= 1; + if (onChange != null) { + onChange!(); + } + }), Expanded( - child: ReactiveTextField( - readOnly: true, - textAlign: TextAlign.center, - formControlName: formControlName, - decoration: InputDecoration( - labelText: hint, + child: SizedBox( + height: kPadding * 5, + child: ReactiveTextField( + readOnly: true, + textAlign: TextAlign.center, + formControlName: formControlName, + decoration: InputDecoration( + labelText: hint, + ), + keyboardType: TextInputType.number, ), - keyboardType: TextInputType.number, ), ), _buildButton(context, @@ -73,8 +82,16 @@ class DigitIntegerFormPicker extends StatelessWidget { bottom: _borderSide, top: _borderSide, ), - icon: Icons.add, - onPressed: () => form.control(formControlName).value += 1), + icon: Icons.add, onPressed: () { + if(maximum != null && form.control(formControlName).value == maximum) { + form.control(formControlName).value =maximum; + }else{ + form.control(formControlName).value += 1; + } + if (onChange != null) { + onChange!(); + } + }), ], ), )); @@ -86,8 +103,9 @@ class DigitIntegerFormPicker extends StatelessWidget { required IconData icon, VoidCallback? onPressed, }) => - AspectRatio( - aspectRatio: 1, + SizedBox( + width: buttonWidth ?? 100, + height: kPadding * 5, child: Material( shape: border, color: Theme.of(context).colorScheme.background, diff --git a/packages/digit_components/lib/widgets/atoms/digit_reactive_search_dropdown.dart b/packages/digit_components/lib/widgets/atoms/digit_reactive_search_dropdown.dart index 225d9b3f3..e433d0534 100644 --- a/packages/digit_components/lib/widgets/atoms/digit_reactive_search_dropdown.dart +++ b/packages/digit_components/lib/widgets/atoms/digit_reactive_search_dropdown.dart @@ -53,7 +53,7 @@ class _DigitReactiveSearchDropdownState Widget build(BuildContext context) { return LabeledField( padding: widget.padding ?? const EdgeInsets.only(top: kPadding * 2), - label: '${widget.label}${widget.isRequired ? '*' : ''}', + label: '${widget.label}${widget.isRequired ? ' *' : ''}', child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, @@ -67,7 +67,7 @@ class _DigitReactiveSearchDropdownState displayItemFn: (dynamic str) => Text( str != null ? widget.valueMapper(str) : '', style: TextStyle( - fontSize: 14, + fontSize: 16, color: !widget.enabled ? const DigitColors().hintGrey : const DigitColors().woodsmokeBlack), diff --git a/packages/digit_components/lib/widgets/atoms/selection_card.dart b/packages/digit_components/lib/widgets/atoms/selection_card.dart new file mode 100644 index 000000000..af4d81244 --- /dev/null +++ b/packages/digit_components/lib/widgets/atoms/selection_card.dart @@ -0,0 +1,216 @@ +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/material.dart'; + +class SelectionBox extends StatefulWidget { + final double? width; + final String? errorMessage; + final List options; + final String? title; + final Function(List) onSelectionChanged; + final List? initialSelection; + final bool allowMultipleSelection; + final String Function(T) valueMapper; + final bool isRequired; + final bool equalWidthOptions; + + const SelectionBox({ + Key? key, + this.width, + this.title, + this.errorMessage, + required this.options, + required this.onSelectionChanged, + this.initialSelection, + this.allowMultipleSelection = true, + required this.valueMapper, + this.isRequired = false, + this.equalWidthOptions = false, + }) : super(key: key); + + @override + _SelectionBoxState createState() => _SelectionBoxState(); +} + +class _SelectionBoxState extends State> { + final List _selectedOptions = []; + double? _maxOptionWidth; + + @override + void initState() { + super.initState(); + if (widget.initialSelection != null) { + _selectedOptions.addAll(widget.initialSelection!); + } + + if (widget.equalWidthOptions) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _calculateMaxOptionWidth(); + }); + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (widget.equalWidthOptions) { + WidgetsBinding.instance.addPostFrameCallback((_) { + _calculateMaxOptionWidth(); + }); + } + } + @override + void didUpdateWidget(covariant SelectionBox oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.initialSelection != oldWidget.initialSelection) { + setState(() { + _selectedOptions.clear(); + _selectedOptions.addAll(widget.initialSelection ?? []); + }); + } + } + + void _calculateMaxOptionWidth() { + double maxWidth = 0; + final textTheme = Theme.of(context).textTheme; + + for (var option in widget.options) { + final textPainter = TextPainter( + text: TextSpan( + text: widget.valueMapper(option), + style: textTheme.bodyLarge?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + textDirection: TextDirection.ltr, + ); + textPainter.layout(); + if (textPainter.size.width > maxWidth) { + maxWidth = textPainter.size.width; + } + } + + setState(() { + _maxOptionWidth = maxWidth + kPadding * 5; /// Add padding + }); + } + + void _onOptionTap(T option) { + setState(() { + if (widget.allowMultipleSelection) { + if (_selectedOptions.contains(option)) { + _selectedOptions.remove(option); + } else { + _selectedOptions.add(option); + } + } else { + if (_selectedOptions.contains(option)) { + _selectedOptions.clear(); + } else { + _selectedOptions.clear(); + _selectedOptions.add(option); + } + } + }); + widget.onSelectionChanged(_selectedOptions); + } + + Widget _buildOption(T option) { + final theme = Theme.of(context); + final textTheme = theme.textTheme; + final isSelected = _selectedOptions.contains(option); + + return GestureDetector( + onTap: () => _onOptionTap(option), + child: Container( + width: widget.equalWidthOptions ? _maxOptionWidth : widget.width, + padding: const EdgeInsets.symmetric( + vertical: kPadding, horizontal: kPadding * 2), + decoration: BoxDecoration( + color: isSelected + ? const DigitColors().burningOrange + : const DigitColors().white, + borderRadius: BorderRadius.circular(kPadding / 2), + border: Border.all( + color: const DigitColors().quillGray, + width: 1, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Flexible( + child: Text( + widget.valueMapper(option), + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: isSelected + ? textTheme.bodyLarge?.copyWith( + color: const DigitColors().white, + fontWeight: FontWeight.w700, + ) + : textTheme.bodyLarge?.copyWith( + color: const DigitColors().woodsmokeBlack, + ), + ), + ), + ], + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final textTheme = theme.textTheme; + + return Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + LabeledField( + label: widget.title, + isRequired: widget.isRequired, + child: Container( + width: MediaQuery.of(context).size.width, + padding: const EdgeInsets.all(kPadding * 2), + decoration: BoxDecoration( + color: const DigitColors().alabasterWhite, + borderRadius: BorderRadius.circular(kPadding / 2), + border: Border.all( + color: widget.errorMessage != null ?const DigitColors().lavaRed: const DigitColors().quillGray, + width: 1, + ), + ), + child: Wrap( + alignment: WrapAlignment.center, + spacing: kPadding * 3, + runSpacing: kPadding * 3, + children: widget.options.map(_buildOption).toList(), + ), + ), + ), + const SizedBox(height: kPadding / 2), + if (widget.errorMessage != null) + Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Flexible( + fit: FlexFit.tight, + child: Text( + widget.errorMessage!, + style: textTheme.bodySmall?.copyWith( + color: const DigitColors().lavaRed, + ), + ), + ), + ], + ), + ], + ); + } +} diff --git a/packages/digit_components/lib/widgets/atoms/text_block.dart b/packages/digit_components/lib/widgets/atoms/text_block.dart new file mode 100644 index 000000000..124bb352b --- /dev/null +++ b/packages/digit_components/lib/widgets/atoms/text_block.dart @@ -0,0 +1,83 @@ +import 'package:digit_components/theme/digit_theme.dart'; +import 'package:flutter/material.dart'; +import '../../theme/colors.dart'; + +class TextBlock extends StatelessWidget { + final String? caption; + final TextStyle? captionStyle; + final String? heading; + final TextStyle? headingStyle; + final String? subHeading; + final TextStyle? subHeadingStyle; + final String? body; + final TextStyle? bodyStyle; + final EdgeInsets? padding; + final double spacing; + + const TextBlock({ + Key? key, + this.caption, + this.heading, + this.subHeading, + this.body, + this.captionStyle, + this.headingStyle, + this.subHeadingStyle, + this.bodyStyle, + this.padding, + this.spacing = kPadding, + }) : super(key: key); + + List _conditionalRender(String? text, TextStyle? style, {bool addSpacing = false}) { + if (text == null) return []; + List children = [ + Text( + text, + style: style, + ), + ]; + if (addSpacing) children.add(SizedBox(height: spacing)); + return children; + } + + List _buildTextBlocks(BuildContext context) { + final theme = Theme.of(context); + final List blocks = []; + + blocks.addAll(_conditionalRender( + caption, + captionStyle ?? theme.textTheme.labelSmall?.copyWith(color: const DigitColors().davyGray), + addSpacing: caption != null && (heading != null || subHeading != null || body != null), + )); + + blocks.addAll(_conditionalRender( + heading, + headingStyle ?? theme.textTheme.displayMedium?.copyWith(color: const DigitColors().woodsmokeBlack), + addSpacing: heading != null && (subHeading != null || body != null), + )); + + blocks.addAll(_conditionalRender( + subHeading, + subHeadingStyle ?? theme.textTheme.headlineMedium?.copyWith(color: const DigitColors().davyGray), + addSpacing: subHeading != null && body != null, + )); + + blocks.addAll(_conditionalRender( + body, + bodyStyle ?? theme.textTheme.bodyLarge?.copyWith(color: const DigitColors().davyGray), + )); + + return blocks; + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: padding ?? const EdgeInsets.symmetric(vertical: kPadding), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: _buildTextBlocks(context), + ), + ); + } +} diff --git a/packages/digit_components/lib/widgets/digit_dialog.dart b/packages/digit_components/lib/widgets/digit_dialog.dart index 913f15020..4d9fe457a 100644 --- a/packages/digit_components/lib/widgets/digit_dialog.dart +++ b/packages/digit_components/lib/widgets/digit_dialog.dart @@ -34,7 +34,7 @@ class DigitDialog extends StatelessWidget { padding: options.dialogPadding != null ? options.dialogPadding! : const EdgeInsets.all(kPadding), - child: options.title, + child: options.title(context), ), content: SizedBox( width: MediaQuery.of(context).size.width, @@ -117,6 +117,7 @@ class DigitDialogOptions { final String? contentText; final Widget? _titleWidget; final Widget? _contentWidget; + final bool isCloseIcon; final DigitDialogActions? primaryAction; final DigitDialogActions? secondaryAction; final bool barrierDismissible; @@ -134,6 +135,7 @@ class DigitDialogOptions { Widget? content, this.primaryAction, this.secondaryAction, + this.isCloseIcon = false, this.barrierDismissible = false, this.enableRecordPast = false, this.isScrollable = false, @@ -148,7 +150,7 @@ class DigitDialogOptions { }) : _titleWidget = title, _contentWidget = content; - Widget? get title { + Widget? title(BuildContext context) { if (_titleWidget != null) return _titleWidget; if (titleText != null) { return Row( @@ -164,6 +166,11 @@ class DigitDialogOptions { style: DigitTheme.instance.mobileTheme.textTheme.headlineMedium, ), ), + if (isCloseIcon) + InkWell( + onTap: () => Navigator.of(context).pop(), + child: const Icon(Icons.close), + ), ], ); } diff --git a/packages/digit_components/lib/widgets/digit_search_bar.dart b/packages/digit_components/lib/widgets/digit_search_bar.dart index 16ab7771f..088f27a48 100644 --- a/packages/digit_components/lib/widgets/digit_search_bar.dart +++ b/packages/digit_components/lib/widgets/digit_search_bar.dart @@ -33,7 +33,7 @@ class DigitSearchBar extends StatelessWidget { shape: RoundedRectangleBorder( side: BorderSide(color: theme.scaffoldBackgroundColor, width: 1), borderRadius: BorderRadius.circular( - borderRadius != null ? (borderRadius! * 3) : 30), + borderRadius != null ? (borderRadius! * 3) : 12), ), margin: margin, child: Padding( @@ -57,17 +57,17 @@ class DigitSearchBar extends StatelessWidget { fillColor: theme.cardColor, contentPadding: contentPadding ?? const EdgeInsets.only( - left: 16.0, + left: 0, bottom: 8.0, top: 8.0, ), focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(borderRadius ?? 10.0), + borderRadius: BorderRadius.circular(borderRadius ?? 0.0), borderSide: BorderSide(color: theme.cardColor), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: theme.scaffoldBackgroundColor), - borderRadius: BorderRadius.circular(borderRadius ?? 10.0), + borderRadius: BorderRadius.circular(borderRadius ?? 0.0), ), ), ), diff --git a/packages/digit_components/lib/widgets/digit_sync_dialog.dart b/packages/digit_components/lib/widgets/digit_sync_dialog.dart index e4d2556e2..fd03a7d5d 100644 --- a/packages/digit_components/lib/widgets/digit_sync_dialog.dart +++ b/packages/digit_components/lib/widgets/digit_sync_dialog.dart @@ -6,8 +6,7 @@ class DigitSyncDialog { BuildContext context, { Key? key, bool barrierDismissible = false, - required DigitSyncDialogType type, - required String label, + required DigitSyncDialogType type, String? label, DigitDialogActions? primaryAction, DigitDialogActions? secondaryAction, }) async { @@ -28,7 +27,7 @@ class DigitSyncDialog { Key? key, bool barrierDismissible = false, required DigitSyncDialogType type, - required String label, + String? label, DigitDialogActions? primaryAction, DigitDialogActions? secondaryAction, }) { @@ -72,7 +71,7 @@ class DigitSyncDialog { } class DigitSyncDialogContent extends StatelessWidget { - final String label; + final String? label; final DigitSyncDialogType type; final DigitDialogActions? primaryAction; @@ -80,7 +79,7 @@ class DigitSyncDialogContent extends StatelessWidget { const DigitSyncDialogContent({ super.key, - required this.label, + this.label, required this.type, this.primaryAction, this.secondaryAction, @@ -115,8 +114,9 @@ class DigitSyncDialogContent extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 32, color: color), - const SizedBox(height: kPadding * 2), - Text(label, style: labelStyle?.copyWith(color: color)), + if(label != null) + ...[ const SizedBox(height: kPadding * 2), + Text(label!, style: labelStyle?.copyWith(color: color)),] ], ); } diff --git a/packages/digit_components/lib/widgets/labeled_field.dart b/packages/digit_components/lib/widgets/labeled_field.dart index 96bb70c5f..04776e0df 100644 --- a/packages/digit_components/lib/widgets/labeled_field.dart +++ b/packages/digit_components/lib/widgets/labeled_field.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; class LabeledField extends StatelessWidget { final Widget child; - final String label; + final String? label; final IconData? icon; final String? tooltipMessage; final TextStyle? labelStyle; @@ -11,11 +11,12 @@ class LabeledField extends StatelessWidget { final bool preferToolTipBelow; final TooltipTriggerMode tooltipTriggerMode; final TextStyle? textStyle; + final bool isRequired; const LabeledField({ super.key, required this.child, - required this.label, + this.label, this.icon, this.tooltipMessage, this.labelStyle, @@ -23,6 +24,7 @@ class LabeledField extends StatelessWidget { this.preferToolTipBelow = false, this.tooltipTriggerMode = TooltipTriggerMode.tap, this.textStyle, + this.isRequired = false, }); @override @@ -32,15 +34,18 @@ class LabeledField extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ + if(label != null) Row( children: [ Flexible( child: Text( - label, + label!, style: labelStyle ?? DigitTheme.instance.mobileTheme.textTheme.labelSmall, ), ), + if(isRequired) Text(' *', style: labelStyle ?? + DigitTheme.instance.mobileTheme.textTheme.labelSmall,), icon != null ? Tooltip( message: tooltipMessage ?? '', @@ -50,6 +55,7 @@ class LabeledField extends StatelessWidget { : const SizedBox.shrink() ], ), + if(label != null) const SizedBox(height: 8), child, ], diff --git a/packages/digit_components/lib/widgets/molecules/digit_table.dart b/packages/digit_components/lib/widgets/molecules/digit_table.dart index 1d51f5033..d966c40cc 100644 --- a/packages/digit_components/lib/widgets/molecules/digit_table.dart +++ b/packages/digit_components/lib/widgets/molecules/digit_table.dart @@ -161,7 +161,7 @@ class DigitTable extends StatelessWidget { } Widget _generateFirstColumnRow(BuildContext context, int index) { - var data = tableData[index].tableRow.first; + var data = tableData[index].tableRow.isNotEmpty ? tableData[index].tableRow.first : TableData(''); final tableCellBorder = DigitTheme.instance.tableCellBorder; final tableCellStrongBorder = DigitTheme.instance.tableCellStrongBorder; return InkWell( diff --git a/packages/digit_components/pubspec.yaml b/packages/digit_components/pubspec.yaml index a3c0bf789..65366bafa 100644 --- a/packages/digit_components/pubspec.yaml +++ b/packages/digit_components/pubspec.yaml @@ -1,6 +1,6 @@ name: digit_components description: Digit UI Design specification Flutter widgets. Import this package by adding digit_components in respective pubspec.yaml dependencies. -version: 1.0.0+2 +version: 1.0.1 homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/master/packages/digit_components repository: https://github.com/egovernments/health-campaign-field-worker-app diff --git a/packages/digit_data_model/CHANGELOG.md b/packages/digit_data_model/CHANGELOG.md index 027280c32..b7dde2faa 100644 --- a/packages/digit_data_model/CHANGELOG.md +++ b/packages/digit_data_model/CHANGELOG.md @@ -1,23 +1,58 @@ -## 0.0.0-dev.1 +## 1.0.4-dev.3 -* Digit Data Model Initial Release +* Updated oplog transactions to synchronous - fix for write transaction lock +* Same change in 1.0.3-hotfix, 1.0.4-dev.3 -## 0.0.0-dev.2 +## 1.0.3 -* Boundary v2 Integrated, to use Boundary v1 0.0.0-dev.1 version can be used +* Added localization table +* Updated individual local search results with user uuid mapping -## 0.0.0-dev.3 +## 1.0.3-dev.4 -* Supports boundary v2 and updated single entities to list for all search models +* Updated individual local search results with user uuid mapping + +## 1.0.3-dev.3 -## 1.0.0 +* Created localization table + - Creation of the localization table. -* Initial stable release +## 1.0.3-dev.2 -## 1.0.1 +* Reverted user_actions db changes to accommodate closed_household flow changes + - Reverted user_actions database changes to support closed_household flow changes. -* Added Service and Service Definition Bloc +## 1.0.3-dev.1 + +* Added new user_actions db + - Added a new user_actions database. ## 1.0.2 * Added try catch for local repository to handle db lock + - Implemented try-catch for local repository to handle database locks. + +## 1.0.1 + +* Added Service and Service Definition Bloc + - Introduction of Service and Service Definition Bloc. + +## 1.0.0 + +* Initial stable release + - First stable release of the Digit Data Model. + +## 0.0.0-dev.3 + +* Supports boundary v2 and updated single entities to list for all search models + - Added support for boundary v2 and updated single entities to lists for all search models. + +## 0.0.0-dev.2 + +* Boundary v2 Integrated, to use Boundary v1 0.0.0-dev.1 version can be used + - Integration of Boundary v2 with the option to use Boundary v1 version 0.0.0-dev.1. + +## 0.0.0-dev.1 + +* Digit Data Model Initial Release + - This marks the initial release of the Digit Data Model. \ No newline at end of file diff --git a/packages/digit_data_model/lib/data/data_repository.dart b/packages/digit_data_model/lib/data/data_repository.dart index 5ceac41ae..17b98e2dc 100644 --- a/packages/digit_data_model/lib/data/data_repository.dart +++ b/packages/digit_data_model/lib/data/data_repository.dart @@ -35,7 +35,7 @@ abstract class DataRepository extends DataRepository { +R extends EntitySearchModel> extends DataRepository { final Dio dio; final String entityName; final bool isPlural; @@ -61,19 +61,19 @@ abstract class RemoteRepository actionMap[ApiOperation.bulkDelete] ?? ''; RemoteRepository( - this.dio, { - required this.actionMap, - required this.entityName, - this.isPlural = false, - this.isSearchResponsePlural = false, - }); + this.dio, { + required this.actionMap, + required this.entityName, + this.isPlural = false, + this.isSearchResponsePlural = false, + }); @override FutureOr> search( - R query, { - int? offSet, - int? limit, - }) async { + R query, { + int? offSet, + int? limit, + }) async { Response response; try { @@ -90,15 +90,15 @@ abstract class RemoteRepository> downSync( - R query, { - int? offSet, - int? limit, - }) async { + R query, { + int? offSet, + int? limit, + }) async { Response response; try { @@ -183,7 +183,7 @@ abstract class RemoteRepository dumpError( - List entities, - DataOperation operation, - ) async { + List entities, + DataOperation operation, + ) async { return executeFuture( future: () async { String url = ""; @@ -348,9 +348,9 @@ abstract class RemoteRepository { } } +class $LocalizationTable extends Localization + with TableInfo<$LocalizationTable, LocalizationData> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $LocalizationTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _localeMeta = const VerificationMeta('locale'); + @override + late final GeneratedColumn locale = GeneratedColumn( + 'locale', aliasedName, false, + additionalChecks: + GeneratedColumn.checkTextLength(minTextLength: 1, maxTextLength: 255), + type: DriftSqlType.string, + requiredDuringInsert: true); + static const VerificationMeta _codeMeta = const VerificationMeta('code'); + @override + late final GeneratedColumn code = GeneratedColumn( + 'code', aliasedName, false, + additionalChecks: + GeneratedColumn.checkTextLength(minTextLength: 1, maxTextLength: 255), + type: DriftSqlType.string, + requiredDuringInsert: true); + static const VerificationMeta _messageMeta = + const VerificationMeta('message'); + @override + late final GeneratedColumn message = GeneratedColumn( + 'message', aliasedName, false, + additionalChecks: + GeneratedColumn.checkTextLength(minTextLength: 1, maxTextLength: 500), + type: DriftSqlType.string, + requiredDuringInsert: true); + static const VerificationMeta _moduleMeta = const VerificationMeta('module'); + @override + late final GeneratedColumn module = GeneratedColumn( + 'module', aliasedName, false, + additionalChecks: + GeneratedColumn.checkTextLength(minTextLength: 1, maxTextLength: 255), + type: DriftSqlType.string, + requiredDuringInsert: true); + @override + List get $columns => [locale, code, message, module]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'localization'; + @override + VerificationContext validateIntegrity(Insertable instance, + {bool isInserting = false}) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('locale')) { + context.handle(_localeMeta, + locale.isAcceptableOrUnknown(data['locale']!, _localeMeta)); + } else if (isInserting) { + context.missing(_localeMeta); + } + if (data.containsKey('code')) { + context.handle( + _codeMeta, code.isAcceptableOrUnknown(data['code']!, _codeMeta)); + } else if (isInserting) { + context.missing(_codeMeta); + } + if (data.containsKey('message')) { + context.handle(_messageMeta, + message.isAcceptableOrUnknown(data['message']!, _messageMeta)); + } else if (isInserting) { + context.missing(_messageMeta); + } + if (data.containsKey('module')) { + context.handle(_moduleMeta, + module.isAcceptableOrUnknown(data['module']!, _moduleMeta)); + } else if (isInserting) { + context.missing(_moduleMeta); + } + return context; + } + + @override + Set get $primaryKey => const {}; + @override + LocalizationData map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return LocalizationData( + locale: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}locale'])!, + code: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}code'])!, + message: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}message'])!, + module: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}module'])!, + ); + } + + @override + $LocalizationTable createAlias(String alias) { + return $LocalizationTable(attachedDatabase, alias); + } +} + +class LocalizationData extends DataClass + implements Insertable { + final String locale; + final String code; + final String message; + final String module; + const LocalizationData( + {required this.locale, + required this.code, + required this.message, + required this.module}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['locale'] = Variable(locale); + map['code'] = Variable(code); + map['message'] = Variable(message); + map['module'] = Variable(module); + return map; + } + + LocalizationCompanion toCompanion(bool nullToAbsent) { + return LocalizationCompanion( + locale: Value(locale), + code: Value(code), + message: Value(message), + module: Value(module), + ); + } + + factory LocalizationData.fromJson(Map json, + {ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return LocalizationData( + locale: serializer.fromJson(json['locale']), + code: serializer.fromJson(json['code']), + message: serializer.fromJson(json['message']), + module: serializer.fromJson(json['module']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'locale': serializer.toJson(locale), + 'code': serializer.toJson(code), + 'message': serializer.toJson(message), + 'module': serializer.toJson(module), + }; + } + + LocalizationData copyWith( + {String? locale, String? code, String? message, String? module}) => + LocalizationData( + locale: locale ?? this.locale, + code: code ?? this.code, + message: message ?? this.message, + module: module ?? this.module, + ); + @override + String toString() { + return (StringBuffer('LocalizationData(') + ..write('locale: $locale, ') + ..write('code: $code, ') + ..write('message: $message, ') + ..write('module: $module') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(locale, code, message, module); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is LocalizationData && + other.locale == this.locale && + other.code == this.code && + other.message == this.message && + other.module == this.module); +} + +class LocalizationCompanion extends UpdateCompanion { + final Value locale; + final Value code; + final Value message; + final Value module; + final Value rowid; + const LocalizationCompanion({ + this.locale = const Value.absent(), + this.code = const Value.absent(), + this.message = const Value.absent(), + this.module = const Value.absent(), + this.rowid = const Value.absent(), + }); + LocalizationCompanion.insert({ + required String locale, + required String code, + required String message, + required String module, + this.rowid = const Value.absent(), + }) : locale = Value(locale), + code = Value(code), + message = Value(message), + module = Value(module); + static Insertable custom({ + Expression? locale, + Expression? code, + Expression? message, + Expression? module, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (locale != null) 'locale': locale, + if (code != null) 'code': code, + if (message != null) 'message': message, + if (module != null) 'module': module, + if (rowid != null) 'rowid': rowid, + }); + } + + LocalizationCompanion copyWith( + {Value? locale, + Value? code, + Value? message, + Value? module, + Value? rowid}) { + return LocalizationCompanion( + locale: locale ?? this.locale, + code: code ?? this.code, + message: message ?? this.message, + module: module ?? this.module, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (locale.present) { + map['locale'] = Variable(locale.value); + } + if (code.present) { + map['code'] = Variable(code.value); + } + if (message.present) { + map['message'] = Variable(message.value); + } + if (module.present) { + map['module'] = Variable(module.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('LocalizationCompanion(') + ..write('locale: $locale, ') + ..write('code: $code, ') + ..write('message: $message, ') + ..write('module: $module, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + abstract class _$LocalSqlDataStore extends GeneratedDatabase { _$LocalSqlDataStore(QueryExecutor e) : super(e); late final $AttendanceRegisterTable attendanceRegister = @@ -38747,6 +39018,7 @@ abstract class _$LocalSqlDataStore extends GeneratedDatabase { late final $TaskResourceTable taskResource = $TaskResourceTable(this); late final $SideEffectTable sideEffect = $SideEffectTable(this); late final $ReferralTable referral = $ReferralTable(this); + late final $LocalizationTable localization = $LocalizationTable(this); late final Index attendanceClientref = Index('attendance_clientref', 'CREATE INDEX attendance_clientref ON attendance (client_reference_id)'); late final Index attendanceIndividualid = Index('attendance_individualid', @@ -38812,6 +39084,8 @@ abstract class _$LocalSqlDataStore extends GeneratedDatabase { late final Index referralProjectbeneficiaryclientref = Index( 'referral_projectbeneficiaryclientref', 'CREATE INDEX referral_projectbeneficiaryclientref ON referral (project_beneficiary_client_reference_id)'); + late final Index localizationModule = Index('localization_module', + 'CREATE INDEX localization_module ON localization (module)'); @override Iterable> get allTables => allSchemaEntities.whereType>(); @@ -38857,6 +39131,7 @@ abstract class _$LocalSqlDataStore extends GeneratedDatabase { taskResource, sideEffect, referral, + localization, attendanceClientref, attendanceIndividualid, projectClinetref, @@ -38885,6 +39160,7 @@ abstract class _$LocalSqlDataStore extends GeneratedDatabase { sideeffectTaskclientref, referralClinetref, referralProjectid, - referralProjectbeneficiaryclientref + referralProjectbeneficiaryclientref, + localizationModule ]; } diff --git a/packages/digit_data_model/lib/data/local_store/sql_store/tables/localization.dart b/packages/digit_data_model/lib/data/local_store/sql_store/tables/localization.dart new file mode 100644 index 000000000..a0b38bbe3 --- /dev/null +++ b/packages/digit_data_model/lib/data/local_store/sql_store/tables/localization.dart @@ -0,0 +1,11 @@ +import 'package:drift/drift.dart'; + +@TableIndex(name: 'localization_module', columns: { + #module, +}) +class Localization extends Table { + TextColumn get locale => text().withLength(min: 1, max: 255)(); + TextColumn get code => text().withLength(min: 1, max: 255)(); + TextColumn get message => text().withLength(min: 1, max: 500)(); + TextColumn get module => text().withLength(min: 1, max: 255)(); +} \ No newline at end of file diff --git a/packages/digit_data_model/lib/data/repositories/local/individual.dart b/packages/digit_data_model/lib/data/repositories/local/individual.dart index 08a4b2420..801e538fd 100644 --- a/packages/digit_data_model/lib/data/repositories/local/individual.dart +++ b/packages/digit_data_model/lib/data/repositories/local/individual.dart @@ -107,6 +107,8 @@ class IndividualLocalRepository clientReferenceId: individual.clientReferenceId, dateOfBirth: individual.dateOfBirth, mobileNumber: individual.mobileNumber, + userUuid: individual.userUuid, + userId: individual.userUuid, isDeleted: individual.isDeleted, rowVersion: individual.rowVersion, clientAuditDetails: (individual.clientCreatedBy != null && diff --git a/packages/digit_data_model/lib/data/repositories/oplog/oplog.dart b/packages/digit_data_model/lib/data/repositories/oplog/oplog.dart index 03d2d0124..3d4349c8e 100644 --- a/packages/digit_data_model/lib/data/repositories/oplog/oplog.dart +++ b/packages/digit_data_model/lib/data/repositories/oplog/oplog.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; import 'package:isar/isar.dart'; import '../../../data_model.dart'; @@ -15,7 +16,7 @@ abstract class OpLogManager { DataModelType type, { required String createdBy, }) async { - final createOpLogs = await isar.opLogs + final createOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .operationEqualTo(DataOperation.create) @@ -23,9 +24,9 @@ abstract class OpLogManager { .syncedUpEqualTo(false) .syncedDownEqualTo(false) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); - final singleCreateOpLogs = await isar.opLogs + final singleCreateOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .operationEqualTo(DataOperation.singleCreate) @@ -33,9 +34,9 @@ abstract class OpLogManager { .syncedUpEqualTo(false) .syncedDownEqualTo(false) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); - final updateOpLogs = await isar.opLogs + final updateOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .operationEqualTo(DataOperation.update) @@ -44,17 +45,17 @@ abstract class OpLogManager { .syncedUpEqualTo(false) .syncedDownEqualTo(false) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); - final errorOpLogs = await isar.opLogs + final errorOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .syncedDownEqualTo(false) .nonRecoverableErrorEqualTo(true) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); - final deleteOpLogs = await isar.opLogs + final deleteOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .operationEqualTo(DataOperation.delete) @@ -62,9 +63,9 @@ abstract class OpLogManager { .syncedUpEqualTo(false) .syncedDownEqualTo(false) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); - final nonRecoverableOpLogs = await isar.opLogs + final nonRecoverableOpLogs = isar.opLogs .filter() .entityTypeEqualTo(type) .syncedUpEqualTo(true) @@ -74,7 +75,7 @@ abstract class OpLogManager { 5 - 1, ) .createdByEqualTo(createdBy) - .findAll(); + .findAllSync(); var entries = [ createOpLogs, @@ -108,13 +109,13 @@ abstract class OpLogManager { DataModelType type, { required String createdBy, }) async { - var oplogs = await isar.opLogs + var oplogs = isar.opLogs .filter() .syncedUpEqualTo(true) .syncDownRetryCountLessThan(5) .syncedDownEqualTo(false) .entityTypeEqualTo(type) - .findAll(); + .findAllSync(); oplogs = oplogs .sortedBy((element) => element.createdAt) @@ -130,16 +131,23 @@ abstract class OpLogManager { } Future put(OpLogEntry entry) async { - await isar.writeTxn(() async { - await isar.opLogs.put(entry - .copyWith( - clientReferenceId: getClientReferenceId(entry.entity), - serverGeneratedId: getServerGeneratedId(entry.entity), - rowVersion: getRowVersion(entry.entity), - nonRecoverableError: getNonRecoverableError(entry.entity), - ) - .oplog); - }); + try { + isar.writeTxnSync(() { + isar.opLogs.putSync(entry + .copyWith( + clientReferenceId: getClientReferenceId(entry.entity), + serverGeneratedId: getServerGeneratedId(entry.entity), + rowVersion: getRowVersion(entry.entity), + nonRecoverableError: getNonRecoverableError(entry.entity), + ) + .oplog); + }); + } catch (e) { + if (kDebugMode) { + print('error in isar ${e}'); + } + rethrow; + } return; } @@ -154,8 +162,8 @@ abstract class OpLogManager { final oplog = await isar.opLogs.filter().idEqualTo(id).findFirst(); if (oplog == null) return; final OpLogEntry fetchedEntry = OpLogEntry.fromOpLog(oplog); - await isar.writeTxn(() async { - await isar.opLogs.put(fetchedEntry + isar.writeTxnSync(() { + isar.opLogs.putSync(fetchedEntry .copyWith( syncedUp: true, syncedDown: true, @@ -207,10 +215,10 @@ abstract class OpLogManager { Future updateServerGeneratedIds({ required UpdateServerGeneratedIdModel model, }) async { - final opLogs = await isar.opLogs + final opLogs = isar.opLogs .filter() .clientReferenceIdEqualTo(model.clientReferenceId) - .findAll(); + .findAllSync(); for (final oplog in opLogs .where( @@ -235,8 +243,8 @@ abstract class OpLogManager { final updatedOplog = updatedEntry.oplog; - await isar.writeTxn(() async { - await isar.opLogs.put(updatedOplog); + isar.writeTxnSync(() { + isar.opLogs.putSync(updatedOplog); }); } @@ -247,11 +255,11 @@ abstract class OpLogManager { String clientReferenceId, DataOperation operation, ) async { - final oplog = await isar.opLogs + final oplog = isar.opLogs .filter() .operationEqualTo(operation) .clientReferenceIdEqualTo(clientReferenceId) - .findAll(); + .findAllSync(); if (oplog.isEmpty) { throw AppException('OpLog not found for id: $clientReferenceId'); @@ -263,10 +271,10 @@ abstract class OpLogManager { Future> getSyncDownRetryList( String clientReferenceId, ) async { - final oplogs = await isar.opLogs + final oplogs = isar.opLogs .filter() .clientReferenceIdEqualTo(clientReferenceId) - .findAll(); + .findAllSync(); return oplogs; } @@ -274,10 +282,10 @@ abstract class OpLogManager { Future updateSyncDownRetry( String clientReferenceId, ) async { - final oplogs = await isar.opLogs + final oplogs = isar.opLogs .filter() .clientReferenceIdEqualTo(clientReferenceId) - .findAll(); + .findAllSync(); if (oplogs.isEmpty) { throw AppException('OpLog not found for id: $clientReferenceId'); @@ -295,8 +303,8 @@ abstract class OpLogManager { updatedEntry = updatedEntry.copyWith(nonRecoverableError: true); } - await isar.writeTxn(() async { - await isar.opLogs.put(updatedEntry.oplog); + isar.writeTxnSync(() { + isar.opLogs.putSync(updatedEntry.oplog); }); } diff --git a/packages/digit_data_model/lib/data/repositories/remote/boundary.dart b/packages/digit_data_model/lib/data/repositories/remote/boundary.dart index a46cbdd45..8f009bc10 100644 --- a/packages/digit_data_model/lib/data/repositories/remote/boundary.dart +++ b/packages/digit_data_model/lib/data/repositories/remote/boundary.dart @@ -5,6 +5,7 @@ import 'dart:async'; import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:dio/dio.dart'; +import 'package:recase/recase.dart'; class BoundaryRemoteRepository extends RemoteRepository { @@ -108,7 +109,7 @@ class BoundaryRemoteRepository materializedPath: [...materializedPath, e.code ?? ''].join('.'), boundaryNum: [...materializedPath, e.code ?? ''].length, label: e.boundaryType, - name: e.code?.split('_').lastOrNull ?? e.code, + name: e.code?.split('_').lastOrNull?.titleCase ?? e.code?.titleCase, ); boundaryModelList.add(boundary.copyWith(children: [])); diff --git a/packages/digit_data_model/lib/data/repositories/remote/facility.dart b/packages/digit_data_model/lib/data/repositories/remote/facility.dart index 9f35c9223..3703e1198 100644 --- a/packages/digit_data_model/lib/data/repositories/remote/facility.dart +++ b/packages/digit_data_model/lib/data/repositories/remote/facility.dart @@ -1,6 +1,10 @@ // Generated using mason. Do not modify by hand +import 'dart:async'; + +import 'package:dart_mappable/dart_mappable.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:dio/dio.dart'; class FacilityRemoteRepository extends RemoteRepository { @@ -11,6 +15,111 @@ class FacilityRemoteRepository extends RemoteRepository> search( + FacilitySearchModel query, { + int? offSet, + int? limit, + }) async { + int defaultBatchSize = limit ?? 100; // Default batch size for fetching data + int currentOffset = offSet ?? 0; + + List allResults = []; + bool hasMoreData = true; + List>? lastResponse; + + while (hasMoreData) { + Response response; + + try { + response = await executeFuture( + future: () async { + return await dio.post( + searchPath, + queryParameters: { + 'offset': currentOffset, + 'limit': defaultBatchSize, + 'tenantId': DigitDataModelSingleton().tenantId, + if (query.isDeleted ?? false) 'includeDeleted': query.isDeleted, + }, + data: entityName == 'User' + ? query.toMap() + : { + isPlural + ? entityNamePlural + : entityName == 'ServiceDefinition' + ? 'ServiceDefinitionCriteria' + : entityName == 'Downsync' + ? 'DownsyncCriteria' + : entityName: + isPlural ? [query.toMap()] : query.toMap(), + }, + ); + }, + ); + } catch (error) { + break; // Break out of the loop if an error occurs + } + + final responseMap = response.data; + + if (responseMap is! Map) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + String key = (isSearchResponsePlural || entityName == 'ServiceDefinition') + ? entityNamePlural + : entityName; + + if (!responseMap.containsKey(key)) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + final entityResponse = await responseMap[key]; + + if (entityResponse is! List) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + final entityList = entityResponse.whereType>().toList(); + + if (lastResponse != null && lastResponse.toString() == entityList.toString()) { + // If the last response is equal to the current response, stop fetching more data + break; + } + + List currentBatch; + + try { + currentBatch = entityList.map((e) => MapperContainer.globals.fromMap(e)).toList(); + } catch (e) { + rethrow; + } + + if (currentBatch.isEmpty) { + hasMoreData = false; // if no more data stop fetching + } else { + allResults.addAll(currentBatch); + currentOffset += defaultBatchSize; + lastResponse = entityList; // Update lastResponse to the current response + } + } + + return allResults; + } + @override DataModelType get type => DataModelType.facility; } diff --git a/packages/digit_data_model/lib/data/repositories/remote/project_facility.dart b/packages/digit_data_model/lib/data/repositories/remote/project_facility.dart index 152204a75..775457f0e 100644 --- a/packages/digit_data_model/lib/data/repositories/remote/project_facility.dart +++ b/packages/digit_data_model/lib/data/repositories/remote/project_facility.dart @@ -1,6 +1,10 @@ // Generated using mason. Do not modify by hand +import 'dart:async'; + +import 'package:dart_mappable/dart_mappable.dart'; import 'package:digit_data_model/data_model.dart'; +import 'package:dio/dio.dart'; class ProjectFacilityRemoteRepository extends RemoteRepository { @@ -11,6 +15,111 @@ class ProjectFacilityRemoteRepository super.isSearchResponsePlural = true, }); + @override + FutureOr> search( + ProjectFacilitySearchModel query, { + int? offSet, + int? limit, + }) async { + int defaultBatchSize = limit ?? 100; + int currentOffset = offSet ?? 0; + + List allResults = []; + bool hasMoreData = true; + List>? lastResponse; + + while (hasMoreData) { + Response response; + + try { + response = await executeFuture( + future: () async { + return await dio.post( + searchPath, + queryParameters: { + 'offset': currentOffset, + 'limit': defaultBatchSize, + 'tenantId': DigitDataModelSingleton().tenantId, + if (query.isDeleted ?? false) 'includeDeleted': query.isDeleted, + }, + data: entityName == 'User' + ? query.toMap() + : { + isPlural + ? entityNamePlural + : entityName == 'ServiceDefinition' + ? 'ServiceDefinitionCriteria' + : entityName == 'Downsync' + ? 'DownsyncCriteria' + : entityName: + isPlural ? [query.toMap()] : query.toMap(), + }, + ); + }, + ); + } catch (error) { + break; // Break out of the loop if an error occurs + } + + final responseMap = response.data; + + if (responseMap is! Map) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + String key = (isSearchResponsePlural || entityName == 'ServiceDefinition') + ? entityNamePlural + : entityName; + + if (!responseMap.containsKey(key)) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + final entityResponse = await responseMap[key]; + + if (entityResponse is! List) { + throw InvalidApiResponseException( + data: query.toMap(), + path: searchPath, + response: responseMap, + ); + } + + final entityList = entityResponse.whereType>().toList(); + + if (lastResponse != null && lastResponse.toString() == entityList.toString()) { + // If the last response is equal to the current response, stop fetching more data + break; + } + + List currentBatch; + + try { + currentBatch = entityList.map((e) => MapperContainer.globals.fromMap(e)).toList(); + } catch (e) { + rethrow; + } + + if (currentBatch.isEmpty) { + hasMoreData = false; // if no more data stop fetching + } else { + allResults.addAll(currentBatch); + currentOffset += defaultBatchSize; + lastResponse = entityList; // Update lastResponse to the current response + } + } + + return allResults; + } + @override DataModelType get type => DataModelType.projectFacility; } diff --git a/packages/digit_data_model/lib/models/entities/project.dart b/packages/digit_data_model/lib/models/entities/project.dart index 9a552bd9c..eabf97622 100644 --- a/packages/digit_data_model/lib/models/entities/project.dart +++ b/packages/digit_data_model/lib/models/entities/project.dart @@ -1,7 +1,6 @@ // Generated using mason. Do not modify by hand import 'package:dart_mappable/dart_mappable.dart'; import 'package:digit_data_model/data_model.dart'; -import 'package:digit_data_model/models/entities/project_type.dart'; import 'package:drift/drift.dart'; part 'project.mapper.dart'; @@ -180,6 +179,7 @@ class ProjectAdditionalFields extends AdditionalFields class ProjectAdditionalDetails with ProjectAdditionalDetailsMappable { final ProjectTypeModel? projectType; + ProjectAdditionalDetails({ this.projectType, }) : super(); diff --git a/packages/digit_data_model/pubspec.lock b/packages/digit_data_model/pubspec.lock index 3f0249b33..a2f7c5b49 100644 --- a/packages/digit_data_model/pubspec.lock +++ b/packages/digit_data_model/pubspec.lock @@ -252,9 +252,11 @@ packages: dart_mappable_builder: dependency: "direct dev" description: - path: "../dart_mappable_builder" - relative: true - source: path + path: "packages/dart_mappable_builder" + ref: master + resolved-ref: "145091c3b5f05ccea22ec7520f5b9f4e50ff6106" + url: "https://github.com/egovernments/health-campaign-field-worker-app/" + source: git version: "4.2.0" dart_style: dependency: transitive diff --git a/packages/digit_data_model/pubspec.yaml b/packages/digit_data_model/pubspec.yaml index bb7434c85..33cc2ddbe 100644 --- a/packages/digit_data_model/pubspec.yaml +++ b/packages/digit_data_model/pubspec.yaml @@ -1,6 +1,6 @@ name: digit_data_model description: The digit_data_model package is a data modeling library. It defines various classes, enums, and functions. -version: 1.0.2 +version: 1.0.4-dev.3 homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/master/packages/digit_data_model repository: https://github.com/egovernments/health-campaign-field-worker-app diff --git a/packages/digit_dss/.gitignore b/packages/digit_dss/.gitignore new file mode 100644 index 000000000..ac5aa9893 --- /dev/null +++ b/packages/digit_dss/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/packages/digit_dss/.metadata b/packages/digit_dss/.metadata new file mode 100644 index 000000000..fe59252be --- /dev/null +++ b/packages/digit_dss/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "78666c8dc57e9f7548ca9f8dd0740fbf0c658dc9" + channel: "stable" + +project_type: package diff --git a/packages/digit_dss/CHANGELOG.md b/packages/digit_dss/CHANGELOG.md new file mode 100644 index 000000000..a9616d31f --- /dev/null +++ b/packages/digit_dss/CHANGELOG.md @@ -0,0 +1,15 @@ +## 1.0.0 +* Initial DSS Dashboard Release supporting metric and table charts + +## 0.0.1-dev.4 +* Added error toast for network failure +* No result card added if no charts available + +## 0.0.1-dev.3 +* Fixed user uuid search for dss charts + +## 0.0.1-dev.2 +* Added userIds and project Id filters for all dss charts + +## 0.0.1-dev.1 +* Initial DSS Dashboard Release diff --git a/packages/digit_dss/LICENSE b/packages/digit_dss/LICENSE new file mode 100644 index 000000000..f7d7ac958 --- /dev/null +++ b/packages/digit_dss/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 eGovernments Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/packages/digit_dss/README.md b/packages/digit_dss/README.md new file mode 100644 index 000000000..351648dfc --- /dev/null +++ b/packages/digit_dss/README.md @@ -0,0 +1,44 @@ +# Digit DSS + +DSS Dashboard for campaign management + +## Features +* Dashboard Metric and Table Charts support + + +## Getting Started + +To use this package, add the following dependency to your `pubspec.yaml` file: + +```yaml +dependencies: + digit_dss: ^any +``` + +## Usage +To Navigate to any screens of the package: + +First add digit_dss_router to your main app router + +Navigate to the required screen using the below code and pass the required data: + +```dart +context.router.push(UserDashboardRoute(),); +``` + +Digit DSS package requires below data to be passed from main app: + +```dart + +String? _tenantId; +String? _projectId; +String? _actionPath; +String? _appVersion; +ProjectModel? _selectedProject; +DashboardConfigSchema? _dashboardConfig; +``` + +To set the required data use: + +```dart +DashboardSingleton().setInitialData(); diff --git a/packages/digit_dss/analysis_options.yaml b/packages/digit_dss/analysis_options.yaml new file mode 100644 index 000000000..a5744c1cf --- /dev/null +++ b/packages/digit_dss/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/digit_dss/lib/blocs/app_localization.dart b/packages/digit_dss/lib/blocs/app_localization.dart new file mode 100644 index 000000000..a9180ab45 --- /dev/null +++ b/packages/digit_dss/lib/blocs/app_localization.dart @@ -0,0 +1,51 @@ +import 'package:flutter/material.dart'; + +import 'dashboard_localization_delegate.dart'; + +// Class responsible for handling attendance localization +class DashboardLocalization { + final Locale locale; + final Future localizedStrings; + final List languages; + + DashboardLocalization(this.locale, this.localizedStrings, this.languages); + + // Method to get the current localization instance from context + static DashboardLocalization of(BuildContext context) { + return Localizations.of( + context, DashboardLocalization)!; + } + + static final List _localizedStrings = []; + + // Method to get the delegate for localization + static LocalizationsDelegate getDelegate( + Future localizedStrings, List languages) => + DashboardLocalizationDelegate(localizedStrings, languages); + + // Method to load localized strings + Future load() async { + _localizedStrings.clear(); + // Iterate over localized strings and filter based on locale + for (var element in await localizedStrings) { + if (element.locale == '${locale.languageCode}_${locale.countryCode}') { + _localizedStrings.add(element); + } + } + + return true; + } + + // Method to translate a given localized value + String translate(String localizedValues) { + if (_localizedStrings.isEmpty) { + return localizedValues; + } else { + final index = _localizedStrings.indexWhere( + (medium) => medium.code == localizedValues, + ); + + return index != -1 ? _localizedStrings[index].message : localizedValues; + } + } +} diff --git a/packages/digit_dss/lib/blocs/dashboard.dart b/packages/digit_dss/lib/blocs/dashboard.dart new file mode 100644 index 000000000..7f69c15e6 --- /dev/null +++ b/packages/digit_dss/lib/blocs/dashboard.dart @@ -0,0 +1,307 @@ +import 'dart:async'; // Import the dart:async library for asynchronous operations + +import 'package:attendance_management/attendance_management.dart'; +import 'package:attendance_management/utils/typedefs.dart'; +import 'package:collection/collection.dart'; // Import the collection package for collection utilities +import 'package:digit_components/models/digit_table_model.dart'; // Import the digit_table_model.dart file from the digit_components package +import 'package:digit_components/theme/colors.dart'; // Import the colors.dart file from the digit_components package +import 'package:digit_components/theme/digit_theme.dart'; // Import the digit_theme.dart file from the digit_components package +import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/digit_dss.dart'; // Import the digit_dss.dart file from the digit_dss package +import 'package:flutter/cupertino.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; // Import the flutter_bloc package for state management +import 'package:freezed_annotation/freezed_annotation.dart'; // Import the freezed_annotation package for code generation +import 'package:isar/isar.dart'; // Import the isar package for database management + +part 'dashboard.freezed.dart'; // Generate the part file for freezed annotations + +typedef DashboardEmitter = Emitter< + DashboardState>; // Define a typedef for the Emitter of DashboardState + +class DashboardBloc extends Bloc { + final Isar isar; // Isar database instance + final DashboardRemoteRepository + dashboardRemoteRepo; // Remote repository for dashboard data + final AttendanceDataRepository attendanceDataRepository; + final IndividualDataRepository individualDataRepository; + + DashboardBloc( + super.initialState, { + required this.isar, + required this.dashboardRemoteRepo, + required this.attendanceDataRepository, + required this.individualDataRepository, + }) { + on(_handleSearch); // Register the _handleSearch event handler + on(_handleRefresh); // Register the _handleRefresh event handler + } + + // Event handler for refreshing the dashboard + FutureOr _handleRefresh( + DashboardRefreshEvent event, + DashboardEmitter emit, + ) async { + emit(const DashboardState.loading()); // Emit loading state + try { + bool enableDashboard = + DashboardSingleton().dashboardConfig?.enableDashboard ?? + false; // Check if dashboard is enabled + final dashboardConfig = DashboardSingleton() + .dashboardConfig + ?.charts; // Get dashboard configuration + if (!enableDashboard || + (dashboardConfig?.where((chart) => + (chart.name ?? '').isNotEmpty && + (chart.chartType ?? '').isNotEmpty) ?? + []) + .toList() + .isEmpty) { + emit( + const DashboardErrorState()); // Emit error state if dashboard is not enabled or config is empty + } else { + final isConnected = + await getIsConnected(); // Check network connectivity + if (isConnected && event.syncFromServer) { + final startDate = DateTime(event.selectedDate.year, + event.selectedDate.month, event.selectedDate.day) + .toLocal() + .millisecondsSinceEpoch; // Get start date in milliseconds + final endDate = DateTime(event.selectedDate.year, + event.selectedDate.month, event.selectedDate.day, 23, 59) + .toLocal() + .millisecondsSinceEpoch; // Get end date in milliseconds + + try { + final registers = await attendanceDataRepository.search( + AttendanceRegisterSearchModel( + staffId: AttendanceSingleton().loggedInIndividualId, + referenceId: AttendanceSingleton().projectId, + ), + ); + List attendeesIndividualIds = []; + registers.forEach((r) { + r.attendees?.where((a) => a.individualId != null).forEach((att) { + attendeesIndividualIds.add(att.individualId.toString()); + }); + }); + final individuals = + await individualDataRepository.search(IndividualSearchModel( + id: attendeesIndividualIds, + )); + final userUUIDList = individuals + .where((ind) => ind.userUuid != null) + .map((i) => i.userUuid.toString()) + .toList(); + await processDashboardConfig( + dashboardConfig + ?.where((chart) => + (chart.name ?? '').isNotEmpty && + (chart.chartType ?? '').isNotEmpty) + .toList() ?? + [], + startDate, + endDate, + isar, + event.selectedDate, + dashboardRemoteRepo, + DashboardSingleton().actionPath, + DashboardSingleton().tenantId, + DashboardSingleton().projectId, + userUUIDList, + ); // Process dashboard configuration + + add(DashboardEvent.handleSearch( + selectedDate: event.selectedDate)); // Trigger search event + } catch (e) { + debugPrint(e.toString()); // Print error + add(const DashboardEvent.handleSearch( + isNetworkError: true, + )); + } + } else if (!isConnected && event.syncFromServer) { + emit( + const DashboardErrorState()); // Emit error state if not connected and sync is required + } else { + add(const DashboardEvent.handleSearch()); // Trigger search event + } + } + } catch (e) { + debugPrint(e.toString()); + } + } + + // Event handler for searching the dashboard + FutureOr _handleSearch( + DashboardSearchEvent event, + DashboardEmitter emit, + ) async { + try { + final metricCharts = await isar.dashboardResponses + .where() + .filter() + .chartTypeEqualTo(DSSEnums.metric.toValue()) + .projectIdEqualTo(DashboardSingleton().projectId) + .findAll(); // Query metric charts from Isar database + Map metrics = {}; // Initialize metrics map + List tableWrapperList = []; // Initialize table wrapper list + DashboardConfigSchema? dashboardConfig = + DashboardSingleton().dashboardConfig; + for (DashboardResponse chart in metricCharts) { + if ((chart.data ?? []).isNotEmpty) { + for (DashboardChartData data in (chart.data ?? [])) { + metrics.addAll({ + data.headerName.toString(): MetricWrapper( + header: data.headerName ?? '', + value: data.headerValue ?? '0', + insight: data.insight, + isHorizontal: dashboardConfig?.charts + ?.where((metric) => + metric.name == chart.visualizationCode && + metric.chartType == + DSSEnums.metric.name.toUpperCase()) + .first + .vizType == + DSSEnums.row.toValue(), + ), + }); // Populate metrics map + } + } + } + final tableCharts = await isar.dashboardResponses + .where() + .filter() + .chartTypeEqualTo(DSSEnums.table.toValue()) + .projectIdEqualTo(DashboardSingleton().projectId) + .findAll(); // Query table charts from Isar database + for (DashboardResponse chart in tableCharts) { + if ((chart.data ?? []).isNotEmpty) { + // Create table headers + final List tableHeaderList = chart.data?.first.plots + ?.where((p) => + p.name != DSSEnums.serialNumber.toValue() && + p.name != DSSEnums.startDate.toValue() && + p.name != DSSEnums.endDate.toValue() && + p.name != null) + .map((e) { + final headerData = transformToLocaleCode(e.name ?? ''); + return TableHeader( + headerData ?? '', + cellKey: e.name, + ); + }).toList() ?? + []; + + // Create table details + final tableDetails = chart.data?.map((e) { + final rowTableData = e.plots + ?.where((p) => + p.name != DSSEnums.serialNumber.toValue() && + p.name != DSSEnums.startDate.toValue() && + p.name != DSSEnums.endDate.toValue()) + .mapIndexed( + (i, plot) => TableData( + plot.symbol == DSSEnums.number.toValue() || + plot.symbol == DSSEnums.percentage.toValue() + ? plot.name == DSSEnums.lastSyncedTime.toValue() && + plot.symbol == DSSEnums.number.toValue() + ? DigitDateUtils.getDateFromTimestamp(int.parse( + double.parse(plot.value.toString()) + .toInt() + .toString())) + : double.parse(plot.value.toString()) == + double.parse(plot.value.toString()).toInt() + ? double.parse(plot.value.toString()) + .toInt() + .toString() + : double.parse(plot.value.toString()) + .toStringAsFixed(2) + : plot.label.toString(), + cellKey: plot.name, + style: DigitTheme.instance.mobileTheme.textTheme.bodyMedium + ?.apply( + color: i == 0 + ? const DigitColors().burningOrange + : const DigitColors().woodsmokeBlack, + ), + ), + ) + .toList(); + return TableDataRow(rowTableData ?? []); + }).toList(); + tableWrapperList.add(TableWrapper( + headerList: tableHeaderList, + tableData: tableDetails ?? [], + )); + } + } + + emit(DashboardFetchedState( + metricData: metrics, + tableData: tableWrapperList, + selectedDate: metricCharts.firstOrNull?.lastSelectedDate ?? + event.selectedDate ?? + DateTime.now(), + isNetworkError: event.isNetworkError, + )); // Emit fetched state with metric and table data + } catch (error) { + rethrow; // Rethrow any caught errors + } + } +} + +// Define DashboardEvent with freezed annotations +@freezed +class DashboardEvent with _$DashboardEvent { + const factory DashboardEvent.handleSearch({ + DateTime? selectedDate, + @Default(false) bool? isNetworkError, + }) = DashboardSearchEvent; // Define handleSearch event + const factory DashboardEvent.handleRefresh({ + required DateTime selectedDate, + required String projectId, + @Default(false) bool syncFromServer, + }) = DashboardRefreshEvent; // Define handleRefresh event +} + +// Define DashboardState with freezed annotations +@freezed +class DashboardState with _$DashboardState { + const factory DashboardState.loading() = + DashboardLoadingState; // Define loading state + const factory DashboardState.initialState() = + DashboardInitialState; // Define initial state + const factory DashboardState.fetched({ + Map? metricData, + List? tableData, + DateTime? selectedDate, + @Default(false) bool? isNetworkError, + }) = DashboardFetchedState; // Define fetched state + const factory DashboardState.error() = + DashboardErrorState; // Define error state +} + +// Class for wrapping metric data +class MetricWrapper { + final String header; // Header of the metric + final String value; // Value of the metric + final Insight? insight; // Insight related to the metric + final bool? isHorizontal; + MetricWrapper({ + required this.header, + required this.value, + this.insight, + this.isHorizontal = true, + }); +} + +// Class for wrapping table data +class TableWrapper { + final List headerList; // List of table headers + final List tableData; // List of table data rows + + TableWrapper({ + required this.headerList, + required this.tableData, + }); +} diff --git a/packages/digit_dss/lib/blocs/dashboard.freezed.dart b/packages/digit_dss/lib/blocs/dashboard.freezed.dart new file mode 100644 index 000000000..70ffcb4ca --- /dev/null +++ b/packages/digit_dss/lib/blocs/dashboard.freezed.dart @@ -0,0 +1,1152 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'dashboard.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +/// @nodoc +mixin _$DashboardEvent { + DateTime? get selectedDate => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function(DateTime? selectedDate, bool? isNetworkError) + handleSearch, + required TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer) + handleRefresh, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult? Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardSearchEvent value) handleSearch, + required TResult Function(DashboardRefreshEvent value) handleRefresh, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardSearchEvent value)? handleSearch, + TResult? Function(DashboardRefreshEvent value)? handleRefresh, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardSearchEvent value)? handleSearch, + TResult Function(DashboardRefreshEvent value)? handleRefresh, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $DashboardEventCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DashboardEventCopyWith<$Res> { + factory $DashboardEventCopyWith( + DashboardEvent value, $Res Function(DashboardEvent) then) = + _$DashboardEventCopyWithImpl<$Res, DashboardEvent>; + @useResult + $Res call({DateTime selectedDate}); +} + +/// @nodoc +class _$DashboardEventCopyWithImpl<$Res, $Val extends DashboardEvent> + implements $DashboardEventCopyWith<$Res> { + _$DashboardEventCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? selectedDate = null, + }) { + return _then(_value.copyWith( + selectedDate: null == selectedDate + ? _value.selectedDate! + : selectedDate // ignore: cast_nullable_to_non_nullable + as DateTime, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DashboardSearchEventImplCopyWith<$Res> + implements $DashboardEventCopyWith<$Res> { + factory _$$DashboardSearchEventImplCopyWith(_$DashboardSearchEventImpl value, + $Res Function(_$DashboardSearchEventImpl) then) = + __$$DashboardSearchEventImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({DateTime? selectedDate, bool? isNetworkError}); +} + +/// @nodoc +class __$$DashboardSearchEventImplCopyWithImpl<$Res> + extends _$DashboardEventCopyWithImpl<$Res, _$DashboardSearchEventImpl> + implements _$$DashboardSearchEventImplCopyWith<$Res> { + __$$DashboardSearchEventImplCopyWithImpl(_$DashboardSearchEventImpl _value, + $Res Function(_$DashboardSearchEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? selectedDate = freezed, + Object? isNetworkError = freezed, + }) { + return _then(_$DashboardSearchEventImpl( + selectedDate: freezed == selectedDate + ? _value.selectedDate + : selectedDate // ignore: cast_nullable_to_non_nullable + as DateTime?, + isNetworkError: freezed == isNetworkError + ? _value.isNetworkError + : isNetworkError // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc + +class _$DashboardSearchEventImpl implements DashboardSearchEvent { + const _$DashboardSearchEventImpl( + {this.selectedDate, this.isNetworkError = false}); + + @override + final DateTime? selectedDate; + @override + @JsonKey() + final bool? isNetworkError; + + @override + String toString() { + return 'DashboardEvent.handleSearch(selectedDate: $selectedDate, isNetworkError: $isNetworkError)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardSearchEventImpl && + (identical(other.selectedDate, selectedDate) || + other.selectedDate == selectedDate) && + (identical(other.isNetworkError, isNetworkError) || + other.isNetworkError == isNetworkError)); + } + + @override + int get hashCode => Object.hash(runtimeType, selectedDate, isNetworkError); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DashboardSearchEventImplCopyWith<_$DashboardSearchEventImpl> + get copyWith => + __$$DashboardSearchEventImplCopyWithImpl<_$DashboardSearchEventImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(DateTime? selectedDate, bool? isNetworkError) + handleSearch, + required TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer) + handleRefresh, + }) { + return handleSearch(selectedDate, isNetworkError); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult? Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + }) { + return handleSearch?.call(selectedDate, isNetworkError); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + required TResult orElse(), + }) { + if (handleSearch != null) { + return handleSearch(selectedDate, isNetworkError); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardSearchEvent value) handleSearch, + required TResult Function(DashboardRefreshEvent value) handleRefresh, + }) { + return handleSearch(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardSearchEvent value)? handleSearch, + TResult? Function(DashboardRefreshEvent value)? handleRefresh, + }) { + return handleSearch?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardSearchEvent value)? handleSearch, + TResult Function(DashboardRefreshEvent value)? handleRefresh, + required TResult orElse(), + }) { + if (handleSearch != null) { + return handleSearch(this); + } + return orElse(); + } +} + +abstract class DashboardSearchEvent implements DashboardEvent { + const factory DashboardSearchEvent( + {final DateTime? selectedDate, + final bool? isNetworkError}) = _$DashboardSearchEventImpl; + + @override + DateTime? get selectedDate; + bool? get isNetworkError; + @override + @JsonKey(ignore: true) + _$$DashboardSearchEventImplCopyWith<_$DashboardSearchEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$DashboardRefreshEventImplCopyWith<$Res> + implements $DashboardEventCopyWith<$Res> { + factory _$$DashboardRefreshEventImplCopyWith( + _$DashboardRefreshEventImpl value, + $Res Function(_$DashboardRefreshEventImpl) then) = + __$$DashboardRefreshEventImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({DateTime selectedDate, String projectId, bool syncFromServer}); +} + +/// @nodoc +class __$$DashboardRefreshEventImplCopyWithImpl<$Res> + extends _$DashboardEventCopyWithImpl<$Res, _$DashboardRefreshEventImpl> + implements _$$DashboardRefreshEventImplCopyWith<$Res> { + __$$DashboardRefreshEventImplCopyWithImpl(_$DashboardRefreshEventImpl _value, + $Res Function(_$DashboardRefreshEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? selectedDate = null, + Object? projectId = null, + Object? syncFromServer = null, + }) { + return _then(_$DashboardRefreshEventImpl( + selectedDate: null == selectedDate + ? _value.selectedDate + : selectedDate // ignore: cast_nullable_to_non_nullable + as DateTime, + projectId: null == projectId + ? _value.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + syncFromServer: null == syncFromServer + ? _value.syncFromServer + : syncFromServer // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc + +class _$DashboardRefreshEventImpl implements DashboardRefreshEvent { + const _$DashboardRefreshEventImpl( + {required this.selectedDate, + required this.projectId, + this.syncFromServer = false}); + + @override + final DateTime selectedDate; + @override + final String projectId; + @override + @JsonKey() + final bool syncFromServer; + + @override + String toString() { + return 'DashboardEvent.handleRefresh(selectedDate: $selectedDate, projectId: $projectId, syncFromServer: $syncFromServer)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardRefreshEventImpl && + (identical(other.selectedDate, selectedDate) || + other.selectedDate == selectedDate) && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + (identical(other.syncFromServer, syncFromServer) || + other.syncFromServer == syncFromServer)); + } + + @override + int get hashCode => + Object.hash(runtimeType, selectedDate, projectId, syncFromServer); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DashboardRefreshEventImplCopyWith<_$DashboardRefreshEventImpl> + get copyWith => __$$DashboardRefreshEventImplCopyWithImpl< + _$DashboardRefreshEventImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(DateTime? selectedDate, bool? isNetworkError) + handleSearch, + required TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer) + handleRefresh, + }) { + return handleRefresh(selectedDate, projectId, syncFromServer); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult? Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + }) { + return handleRefresh?.call(selectedDate, projectId, syncFromServer); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(DateTime? selectedDate, bool? isNetworkError)? + handleSearch, + TResult Function( + DateTime selectedDate, String projectId, bool syncFromServer)? + handleRefresh, + required TResult orElse(), + }) { + if (handleRefresh != null) { + return handleRefresh(selectedDate, projectId, syncFromServer); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardSearchEvent value) handleSearch, + required TResult Function(DashboardRefreshEvent value) handleRefresh, + }) { + return handleRefresh(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardSearchEvent value)? handleSearch, + TResult? Function(DashboardRefreshEvent value)? handleRefresh, + }) { + return handleRefresh?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardSearchEvent value)? handleSearch, + TResult Function(DashboardRefreshEvent value)? handleRefresh, + required TResult orElse(), + }) { + if (handleRefresh != null) { + return handleRefresh(this); + } + return orElse(); + } +} + +abstract class DashboardRefreshEvent implements DashboardEvent { + const factory DashboardRefreshEvent( + {required final DateTime selectedDate, + required final String projectId, + final bool syncFromServer}) = _$DashboardRefreshEventImpl; + + @override + DateTime get selectedDate; + String get projectId; + bool get syncFromServer; + @override + @JsonKey(ignore: true) + _$$DashboardRefreshEventImplCopyWith<_$DashboardRefreshEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$DashboardState { + @optionalTypeArgs + TResult when({ + required TResult Function() loading, + required TResult Function() initialState, + required TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError) + fetched, + required TResult Function() error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loading, + TResult? Function()? initialState, + TResult? Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult? Function()? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loading, + TResult Function()? initialState, + TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult Function()? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardLoadingState value) loading, + required TResult Function(DashboardInitialState value) initialState, + required TResult Function(DashboardFetchedState value) fetched, + required TResult Function(DashboardErrorState value) error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardLoadingState value)? loading, + TResult? Function(DashboardInitialState value)? initialState, + TResult? Function(DashboardFetchedState value)? fetched, + TResult? Function(DashboardErrorState value)? error, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardLoadingState value)? loading, + TResult Function(DashboardInitialState value)? initialState, + TResult Function(DashboardFetchedState value)? fetched, + TResult Function(DashboardErrorState value)? error, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DashboardStateCopyWith<$Res> { + factory $DashboardStateCopyWith( + DashboardState value, $Res Function(DashboardState) then) = + _$DashboardStateCopyWithImpl<$Res, DashboardState>; +} + +/// @nodoc +class _$DashboardStateCopyWithImpl<$Res, $Val extends DashboardState> + implements $DashboardStateCopyWith<$Res> { + _$DashboardStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; +} + +/// @nodoc +abstract class _$$DashboardLoadingStateImplCopyWith<$Res> { + factory _$$DashboardLoadingStateImplCopyWith( + _$DashboardLoadingStateImpl value, + $Res Function(_$DashboardLoadingStateImpl) then) = + __$$DashboardLoadingStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$DashboardLoadingStateImplCopyWithImpl<$Res> + extends _$DashboardStateCopyWithImpl<$Res, _$DashboardLoadingStateImpl> + implements _$$DashboardLoadingStateImplCopyWith<$Res> { + __$$DashboardLoadingStateImplCopyWithImpl(_$DashboardLoadingStateImpl _value, + $Res Function(_$DashboardLoadingStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$DashboardLoadingStateImpl implements DashboardLoadingState { + const _$DashboardLoadingStateImpl(); + + @override + String toString() { + return 'DashboardState.loading()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardLoadingStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loading, + required TResult Function() initialState, + required TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError) + fetched, + required TResult Function() error, + }) { + return loading(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loading, + TResult? Function()? initialState, + TResult? Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult? Function()? error, + }) { + return loading?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loading, + TResult Function()? initialState, + TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult Function()? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardLoadingState value) loading, + required TResult Function(DashboardInitialState value) initialState, + required TResult Function(DashboardFetchedState value) fetched, + required TResult Function(DashboardErrorState value) error, + }) { + return loading(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardLoadingState value)? loading, + TResult? Function(DashboardInitialState value)? initialState, + TResult? Function(DashboardFetchedState value)? fetched, + TResult? Function(DashboardErrorState value)? error, + }) { + return loading?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardLoadingState value)? loading, + TResult Function(DashboardInitialState value)? initialState, + TResult Function(DashboardFetchedState value)? fetched, + TResult Function(DashboardErrorState value)? error, + required TResult orElse(), + }) { + if (loading != null) { + return loading(this); + } + return orElse(); + } +} + +abstract class DashboardLoadingState implements DashboardState { + const factory DashboardLoadingState() = _$DashboardLoadingStateImpl; +} + +/// @nodoc +abstract class _$$DashboardInitialStateImplCopyWith<$Res> { + factory _$$DashboardInitialStateImplCopyWith( + _$DashboardInitialStateImpl value, + $Res Function(_$DashboardInitialStateImpl) then) = + __$$DashboardInitialStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$DashboardInitialStateImplCopyWithImpl<$Res> + extends _$DashboardStateCopyWithImpl<$Res, _$DashboardInitialStateImpl> + implements _$$DashboardInitialStateImplCopyWith<$Res> { + __$$DashboardInitialStateImplCopyWithImpl(_$DashboardInitialStateImpl _value, + $Res Function(_$DashboardInitialStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$DashboardInitialStateImpl implements DashboardInitialState { + const _$DashboardInitialStateImpl(); + + @override + String toString() { + return 'DashboardState.initialState()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardInitialStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loading, + required TResult Function() initialState, + required TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError) + fetched, + required TResult Function() error, + }) { + return initialState(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loading, + TResult? Function()? initialState, + TResult? Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult? Function()? error, + }) { + return initialState?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loading, + TResult Function()? initialState, + TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult Function()? error, + required TResult orElse(), + }) { + if (initialState != null) { + return initialState(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardLoadingState value) loading, + required TResult Function(DashboardInitialState value) initialState, + required TResult Function(DashboardFetchedState value) fetched, + required TResult Function(DashboardErrorState value) error, + }) { + return initialState(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardLoadingState value)? loading, + TResult? Function(DashboardInitialState value)? initialState, + TResult? Function(DashboardFetchedState value)? fetched, + TResult? Function(DashboardErrorState value)? error, + }) { + return initialState?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardLoadingState value)? loading, + TResult Function(DashboardInitialState value)? initialState, + TResult Function(DashboardFetchedState value)? fetched, + TResult Function(DashboardErrorState value)? error, + required TResult orElse(), + }) { + if (initialState != null) { + return initialState(this); + } + return orElse(); + } +} + +abstract class DashboardInitialState implements DashboardState { + const factory DashboardInitialState() = _$DashboardInitialStateImpl; +} + +/// @nodoc +abstract class _$$DashboardFetchedStateImplCopyWith<$Res> { + factory _$$DashboardFetchedStateImplCopyWith( + _$DashboardFetchedStateImpl value, + $Res Function(_$DashboardFetchedStateImpl) then) = + __$$DashboardFetchedStateImplCopyWithImpl<$Res>; + @useResult + $Res call( + {Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError}); +} + +/// @nodoc +class __$$DashboardFetchedStateImplCopyWithImpl<$Res> + extends _$DashboardStateCopyWithImpl<$Res, _$DashboardFetchedStateImpl> + implements _$$DashboardFetchedStateImplCopyWith<$Res> { + __$$DashboardFetchedStateImplCopyWithImpl(_$DashboardFetchedStateImpl _value, + $Res Function(_$DashboardFetchedStateImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? metricData = freezed, + Object? tableData = freezed, + Object? selectedDate = freezed, + Object? isNetworkError = freezed, + }) { + return _then(_$DashboardFetchedStateImpl( + metricData: freezed == metricData + ? _value._metricData + : metricData // ignore: cast_nullable_to_non_nullable + as Map?, + tableData: freezed == tableData + ? _value._tableData + : tableData // ignore: cast_nullable_to_non_nullable + as List?, + selectedDate: freezed == selectedDate + ? _value.selectedDate + : selectedDate // ignore: cast_nullable_to_non_nullable + as DateTime?, + isNetworkError: freezed == isNetworkError + ? _value.isNetworkError + : isNetworkError // ignore: cast_nullable_to_non_nullable + as bool?, + )); + } +} + +/// @nodoc + +class _$DashboardFetchedStateImpl implements DashboardFetchedState { + const _$DashboardFetchedStateImpl( + {final Map? metricData, + final List? tableData, + this.selectedDate, + this.isNetworkError = false}) + : _metricData = metricData, + _tableData = tableData; + + final Map? _metricData; + @override + Map? get metricData { + final value = _metricData; + if (value == null) return null; + if (_metricData is EqualUnmodifiableMapView) return _metricData; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(value); + } + + final List? _tableData; + @override + List? get tableData { + final value = _tableData; + if (value == null) return null; + if (_tableData is EqualUnmodifiableListView) return _tableData; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + final DateTime? selectedDate; + @override + @JsonKey() + final bool? isNetworkError; + + @override + String toString() { + return 'DashboardState.fetched(metricData: $metricData, tableData: $tableData, selectedDate: $selectedDate, isNetworkError: $isNetworkError)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardFetchedStateImpl && + const DeepCollectionEquality() + .equals(other._metricData, _metricData) && + const DeepCollectionEquality() + .equals(other._tableData, _tableData) && + (identical(other.selectedDate, selectedDate) || + other.selectedDate == selectedDate) && + (identical(other.isNetworkError, isNetworkError) || + other.isNetworkError == isNetworkError)); + } + + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_metricData), + const DeepCollectionEquality().hash(_tableData), + selectedDate, + isNetworkError); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DashboardFetchedStateImplCopyWith<_$DashboardFetchedStateImpl> + get copyWith => __$$DashboardFetchedStateImplCopyWithImpl< + _$DashboardFetchedStateImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loading, + required TResult Function() initialState, + required TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError) + fetched, + required TResult Function() error, + }) { + return fetched(metricData, tableData, selectedDate, isNetworkError); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loading, + TResult? Function()? initialState, + TResult? Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult? Function()? error, + }) { + return fetched?.call(metricData, tableData, selectedDate, isNetworkError); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loading, + TResult Function()? initialState, + TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult Function()? error, + required TResult orElse(), + }) { + if (fetched != null) { + return fetched(metricData, tableData, selectedDate, isNetworkError); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardLoadingState value) loading, + required TResult Function(DashboardInitialState value) initialState, + required TResult Function(DashboardFetchedState value) fetched, + required TResult Function(DashboardErrorState value) error, + }) { + return fetched(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardLoadingState value)? loading, + TResult? Function(DashboardInitialState value)? initialState, + TResult? Function(DashboardFetchedState value)? fetched, + TResult? Function(DashboardErrorState value)? error, + }) { + return fetched?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardLoadingState value)? loading, + TResult Function(DashboardInitialState value)? initialState, + TResult Function(DashboardFetchedState value)? fetched, + TResult Function(DashboardErrorState value)? error, + required TResult orElse(), + }) { + if (fetched != null) { + return fetched(this); + } + return orElse(); + } +} + +abstract class DashboardFetchedState implements DashboardState { + const factory DashboardFetchedState( + {final Map? metricData, + final List? tableData, + final DateTime? selectedDate, + final bool? isNetworkError}) = _$DashboardFetchedStateImpl; + + Map? get metricData; + List? get tableData; + DateTime? get selectedDate; + bool? get isNetworkError; + @JsonKey(ignore: true) + _$$DashboardFetchedStateImplCopyWith<_$DashboardFetchedStateImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$DashboardErrorStateImplCopyWith<$Res> { + factory _$$DashboardErrorStateImplCopyWith(_$DashboardErrorStateImpl value, + $Res Function(_$DashboardErrorStateImpl) then) = + __$$DashboardErrorStateImplCopyWithImpl<$Res>; +} + +/// @nodoc +class __$$DashboardErrorStateImplCopyWithImpl<$Res> + extends _$DashboardStateCopyWithImpl<$Res, _$DashboardErrorStateImpl> + implements _$$DashboardErrorStateImplCopyWith<$Res> { + __$$DashboardErrorStateImplCopyWithImpl(_$DashboardErrorStateImpl _value, + $Res Function(_$DashboardErrorStateImpl) _then) + : super(_value, _then); +} + +/// @nodoc + +class _$DashboardErrorStateImpl implements DashboardErrorState { + const _$DashboardErrorStateImpl(); + + @override + String toString() { + return 'DashboardState.error()'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardErrorStateImpl); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() loading, + required TResult Function() initialState, + required TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError) + fetched, + required TResult Function() error, + }) { + return error(); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? loading, + TResult? Function()? initialState, + TResult? Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult? Function()? error, + }) { + return error?.call(); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? loading, + TResult Function()? initialState, + TResult Function( + Map? metricData, + List? tableData, + DateTime? selectedDate, + bool? isNetworkError)? + fetched, + TResult Function()? error, + required TResult orElse(), + }) { + if (error != null) { + return error(); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(DashboardLoadingState value) loading, + required TResult Function(DashboardInitialState value) initialState, + required TResult Function(DashboardFetchedState value) fetched, + required TResult Function(DashboardErrorState value) error, + }) { + return error(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DashboardLoadingState value)? loading, + TResult? Function(DashboardInitialState value)? initialState, + TResult? Function(DashboardFetchedState value)? fetched, + TResult? Function(DashboardErrorState value)? error, + }) { + return error?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DashboardLoadingState value)? loading, + TResult Function(DashboardInitialState value)? initialState, + TResult Function(DashboardFetchedState value)? fetched, + TResult Function(DashboardErrorState value)? error, + required TResult orElse(), + }) { + if (error != null) { + return error(this); + } + return orElse(); + } +} + +abstract class DashboardErrorState implements DashboardState { + const factory DashboardErrorState() = _$DashboardErrorStateImpl; +} diff --git a/packages/digit_dss/lib/blocs/dashboard_localization_delegate.dart b/packages/digit_dss/lib/blocs/dashboard_localization_delegate.dart new file mode 100644 index 000000000..cb21306dd --- /dev/null +++ b/packages/digit_dss/lib/blocs/dashboard_localization_delegate.dart @@ -0,0 +1,34 @@ +import 'package:flutter/material.dart'; + +import 'app_localization.dart'; + +class DashboardLocalizationDelegate + extends LocalizationsDelegate { + final Future localizedStrings; + final List languages; + + const DashboardLocalizationDelegate(this.localizedStrings, this.languages); + + @override + bool isSupported(Locale locale) { + return languages.map((e) { + final results = e.value.split('_'); + if (results.isNotEmpty) return results.first; + }).contains(locale.languageCode); + } + + @override + Future load(Locale locale) async { + DashboardLocalization localization = + DashboardLocalization(locale, localizedStrings, languages); + await localization.load(); + + return localization; + } + + @override + bool shouldReload( + covariant LocalizationsDelegate old) { + return true; + } +} diff --git a/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.dart b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.dart new file mode 100644 index 000000000..854e32156 --- /dev/null +++ b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.dart @@ -0,0 +1,29 @@ +import 'package:isar/isar.dart'; + +part 'dashboard_config_schema.g.dart'; + +@Collection() +class DashboardConfigSchema { + Id id = Isar.autoIncrement; + + @Name("enableDashboard") + late bool? enableDashboard; + + @Name("charts") + late List? charts; +} + +@embedded +class DashboardChartConfigSchema { + @Name("name") + late String? name; + + @Name("vizType") + late String? vizType; + + @Name("active") + late bool? active; + + @Name("chartType") + late String? chartType; +} diff --git a/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.g.dart b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.g.dart new file mode 100644 index 000000000..723c4c6b0 --- /dev/null +++ b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_config_schema.g.dart @@ -0,0 +1,1121 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'dashboard_config_schema.dart'; + +// ************************************************************************** +// IsarCollectionGenerator +// ************************************************************************** + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +extension GetDashboardConfigSchemaCollection on Isar { + IsarCollection get dashboardConfigSchemas => + this.collection(); +} + +const DashboardConfigSchemaSchema = CollectionSchema( + name: r'DashboardConfigSchema', + id: 5327278717036238119, + properties: { + r'charts': PropertySchema( + id: 0, + name: r'charts', + type: IsarType.objectList, + target: r'DashboardChartConfigSchema', + ), + r'enableDashboard': PropertySchema( + id: 1, + name: r'enableDashboard', + type: IsarType.bool, + ) + }, + estimateSize: _dashboardConfigSchemaEstimateSize, + serialize: _dashboardConfigSchemaSerialize, + deserialize: _dashboardConfigSchemaDeserialize, + deserializeProp: _dashboardConfigSchemaDeserializeProp, + idName: r'id', + indexes: {}, + links: {}, + embeddedSchemas: { + r'DashboardChartConfigSchema': DashboardChartConfigSchemaSchema + }, + getId: _dashboardConfigSchemaGetId, + getLinks: _dashboardConfigSchemaGetLinks, + attach: _dashboardConfigSchemaAttach, + version: '3.1.0+1', +); + +int _dashboardConfigSchemaEstimateSize( + DashboardConfigSchema object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final list = object.charts; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[DashboardChartConfigSchema]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += DashboardChartConfigSchemaSchema.estimateSize( + value, offsets, allOffsets); + } + } + } + } + return bytesCount; +} + +void _dashboardConfigSchemaSerialize( + DashboardConfigSchema object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeObjectList( + offsets[0], + allOffsets, + DashboardChartConfigSchemaSchema.serialize, + object.charts, + ); + writer.writeBool(offsets[1], object.enableDashboard); +} + +DashboardConfigSchema _dashboardConfigSchemaDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = DashboardConfigSchema(); + object.charts = reader.readObjectList( + offsets[0], + DashboardChartConfigSchemaSchema.deserialize, + allOffsets, + DashboardChartConfigSchema(), + ); + object.enableDashboard = reader.readBoolOrNull(offsets[1]); + object.id = id; + return object; +} + +P _dashboardConfigSchemaDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readObjectList( + offset, + DashboardChartConfigSchemaSchema.deserialize, + allOffsets, + DashboardChartConfigSchema(), + )) as P; + case 1: + return (reader.readBoolOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +Id _dashboardConfigSchemaGetId(DashboardConfigSchema object) { + return object.id; +} + +List> _dashboardConfigSchemaGetLinks( + DashboardConfigSchema object) { + return []; +} + +void _dashboardConfigSchemaAttach( + IsarCollection col, Id id, DashboardConfigSchema object) { + object.id = id; +} + +extension DashboardConfigSchemaQueryWhereSort + on QueryBuilder { + QueryBuilder + anyId() { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(const IdWhereClause.any()); + }); + } +} + +extension DashboardConfigSchemaQueryWhere on QueryBuilder { + QueryBuilder + idEqualTo(Id id) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(IdWhereClause.between( + lower: id, + upper: id, + )); + }); + } + + QueryBuilder + idNotEqualTo(Id id) { + return QueryBuilder.apply(this, (query) { + if (query.whereSort == Sort.asc) { + return query + .addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: false), + ) + .addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: false), + ); + } else { + return query + .addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: false), + ) + .addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: false), + ); + } + }); + } + + QueryBuilder + idGreaterThan(Id id, {bool include = false}) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: include), + ); + }); + } + + QueryBuilder + idLessThan(Id id, {bool include = false}) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: include), + ); + }); + } + + QueryBuilder + idBetween( + Id lowerId, + Id upperId, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(IdWhereClause.between( + lower: lowerId, + includeLower: includeLower, + upper: upperId, + includeUpper: includeUpper, + )); + }); + } +} + +extension DashboardConfigSchemaQueryFilter on QueryBuilder< + DashboardConfigSchema, DashboardConfigSchema, QFilterCondition> { + QueryBuilder chartsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'charts', + )); + }); + } + + QueryBuilder chartsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'charts', + )); + }); + } + + QueryBuilder chartsLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder chartsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder chartsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder chartsLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder chartsLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder chartsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'charts', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + + QueryBuilder enableDashboardIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'enableDashboard', + )); + }); + } + + QueryBuilder enableDashboardIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'enableDashboard', + )); + }); + } + + QueryBuilder enableDashboardEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'enableDashboard', + value: value, + )); + }); + } + + QueryBuilder idEqualTo(Id value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'id', + value: value, + )); + }); + } + + QueryBuilder idGreaterThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder idLessThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder idBetween( + Id lower, + Id upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'id', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + )); + }); + } +} + +extension DashboardConfigSchemaQueryObject on QueryBuilder< + DashboardConfigSchema, DashboardConfigSchema, QFilterCondition> { + QueryBuilder + chartsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'charts'); + }); + } +} + +extension DashboardConfigSchemaQueryLinks on QueryBuilder {} + +extension DashboardConfigSchemaQuerySortBy + on QueryBuilder { + QueryBuilder + sortByEnableDashboard() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'enableDashboard', Sort.asc); + }); + } + + QueryBuilder + sortByEnableDashboardDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'enableDashboard', Sort.desc); + }); + } +} + +extension DashboardConfigSchemaQuerySortThenBy + on QueryBuilder { + QueryBuilder + thenByEnableDashboard() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'enableDashboard', Sort.asc); + }); + } + + QueryBuilder + thenByEnableDashboardDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'enableDashboard', Sort.desc); + }); + } + + QueryBuilder + thenById() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'id', Sort.asc); + }); + } + + QueryBuilder + thenByIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'id', Sort.desc); + }); + } +} + +extension DashboardConfigSchemaQueryWhereDistinct + on QueryBuilder { + QueryBuilder + distinctByEnableDashboard() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'enableDashboard'); + }); + } +} + +extension DashboardConfigSchemaQueryProperty on QueryBuilder< + DashboardConfigSchema, DashboardConfigSchema, QQueryProperty> { + QueryBuilder idProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'id'); + }); + } + + QueryBuilder?, + QQueryOperations> chartsProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'charts'); + }); + } + + QueryBuilder + enableDashboardProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'enableDashboard'); + }); + } +} + +// ************************************************************************** +// IsarEmbeddedGenerator +// ************************************************************************** + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const DashboardChartConfigSchemaSchema = Schema( + name: r'DashboardChartConfigSchema', + id: 6365317819446843132, + properties: { + r'active': PropertySchema( + id: 0, + name: r'active', + type: IsarType.bool, + ), + r'chartType': PropertySchema( + id: 1, + name: r'chartType', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ), + r'vizType': PropertySchema( + id: 3, + name: r'vizType', + type: IsarType.string, + ) + }, + estimateSize: _dashboardChartConfigSchemaEstimateSize, + serialize: _dashboardChartConfigSchemaSerialize, + deserialize: _dashboardChartConfigSchemaDeserialize, + deserializeProp: _dashboardChartConfigSchemaDeserializeProp, +); + +int _dashboardChartConfigSchemaEstimateSize( + DashboardChartConfigSchema object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final value = object.chartType; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.name; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.vizType; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + return bytesCount; +} + +void _dashboardChartConfigSchemaSerialize( + DashboardChartConfigSchema object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeBool(offsets[0], object.active); + writer.writeString(offsets[1], object.chartType); + writer.writeString(offsets[2], object.name); + writer.writeString(offsets[3], object.vizType); +} + +DashboardChartConfigSchema _dashboardChartConfigSchemaDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = DashboardChartConfigSchema(); + object.active = reader.readBoolOrNull(offsets[0]); + object.chartType = reader.readStringOrNull(offsets[1]); + object.name = reader.readStringOrNull(offsets[2]); + object.vizType = reader.readStringOrNull(offsets[3]); + return object; +} + +P _dashboardChartConfigSchemaDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readBoolOrNull(offset)) as P; + case 1: + return (reader.readStringOrNull(offset)) as P; + case 2: + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readStringOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension DashboardChartConfigSchemaQueryFilter on QueryBuilder< + DashboardChartConfigSchema, DashboardChartConfigSchema, QFilterCondition> { + QueryBuilder activeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'active', + )); + }); + } + + QueryBuilder activeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'active', + )); + }); + } + + QueryBuilder activeEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'active', + value: value, + )); + }); + } + + QueryBuilder chartTypeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'chartType', + )); + }); + } + + QueryBuilder chartTypeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'chartType', + )); + }); + } + + QueryBuilder chartTypeEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'chartType', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'chartType', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder chartTypeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chartType', + value: '', + )); + }); + } + + QueryBuilder chartTypeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'chartType', + value: '', + )); + }); + } + + QueryBuilder nameIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'name', + )); + }); + } + + QueryBuilder nameIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'name', + )); + }); + } + + QueryBuilder nameEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder vizTypeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'vizType', + )); + }); + } + + QueryBuilder vizTypeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'vizType', + )); + }); + } + + QueryBuilder vizTypeEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'vizType', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + vizTypeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'vizType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + vizTypeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'vizType', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder vizTypeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'vizType', + value: '', + )); + }); + } + + QueryBuilder vizTypeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'vizType', + value: '', + )); + }); + } +} + +extension DashboardChartConfigSchemaQueryObject on QueryBuilder< + DashboardChartConfigSchema, DashboardChartConfigSchema, QFilterCondition> {} diff --git a/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.dart b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.dart new file mode 100644 index 000000000..3f9214c2e --- /dev/null +++ b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.dart @@ -0,0 +1,76 @@ +import 'package:isar/isar.dart'; + +part 'dashboard_response.g.dart'; + +@Collection() +class DashboardResponse { + Id id = Isar.autoIncrement; + + @Name("drillDownChartId") + late String? drillDownChartId; + + @Name("visualizationCode") + late String? visualizationCode; + + @Name("chartType") + late String? chartType; + + @Name("projectId") + late String? projectId; + + @Name("showLabel") + late bool? showLabel; + + @Name("hideInsights") + late bool? hideInsights; + + @Name("hideHeaderDenomination") + late bool? hideHeaderDenomination; + + @Name("data") + late List? data; + + late DateTime? lastSelectedDate; +} + +@embedded +class DashboardChartData { + @Name("headerName") + late String? headerName; + + @Name("headerSymbol") + late String? headerSymbol; + + @Name("headerValue") + late String? headerValue; + @Name("plots") + late List? plots; + @Name("insight") + late Insight? insight; +} + +@embedded +class DashboardPlot { + @Name("label") + late String? label; + @Name("strValue") + late String? strValue; + @Name("name") + late String? name; + @Name("value") + late String? value; + @Name("symbol") + late String? symbol; +} + +@embedded +class Insight { + @Name("colorCode") + late String? colorCode; + @Name("indicator") + late String? indicator; + @Name("name") + late String? name; + @Name("value") + late String? value; +} diff --git a/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.g.dart b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.g.dart new file mode 100644 index 000000000..0a74ce32f --- /dev/null +++ b/packages/digit_dss/lib/data/local_store/no_sql/schema/dashboard_response.g.dart @@ -0,0 +1,4018 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'dashboard_response.dart'; + +// ************************************************************************** +// IsarCollectionGenerator +// ************************************************************************** + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +extension GetDashboardResponseCollection on Isar { + IsarCollection get dashboardResponses => this.collection(); +} + +const DashboardResponseSchema = CollectionSchema( + name: r'DashboardResponse', + id: -8573620870670679659, + properties: { + r'chartType': PropertySchema( + id: 0, + name: r'chartType', + type: IsarType.string, + ), + r'data': PropertySchema( + id: 1, + name: r'data', + type: IsarType.objectList, + target: r'DashboardChartData', + ), + r'drillDownChartId': PropertySchema( + id: 2, + name: r'drillDownChartId', + type: IsarType.string, + ), + r'hideHeaderDenomination': PropertySchema( + id: 3, + name: r'hideHeaderDenomination', + type: IsarType.bool, + ), + r'hideInsights': PropertySchema( + id: 4, + name: r'hideInsights', + type: IsarType.bool, + ), + r'lastSelectedDate': PropertySchema( + id: 5, + name: r'lastSelectedDate', + type: IsarType.dateTime, + ), + r'projectId': PropertySchema( + id: 6, + name: r'projectId', + type: IsarType.string, + ), + r'showLabel': PropertySchema( + id: 7, + name: r'showLabel', + type: IsarType.bool, + ), + r'visualizationCode': PropertySchema( + id: 8, + name: r'visualizationCode', + type: IsarType.string, + ) + }, + estimateSize: _dashboardResponseEstimateSize, + serialize: _dashboardResponseSerialize, + deserialize: _dashboardResponseDeserialize, + deserializeProp: _dashboardResponseDeserializeProp, + idName: r'id', + indexes: {}, + links: {}, + embeddedSchemas: { + r'DashboardChartData': DashboardChartDataSchema, + r'DashboardPlot': DashboardPlotSchema, + r'Insight': InsightSchema + }, + getId: _dashboardResponseGetId, + getLinks: _dashboardResponseGetLinks, + attach: _dashboardResponseAttach, + version: '3.1.0+1', +); + +int _dashboardResponseEstimateSize( + DashboardResponse object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final value = object.chartType; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final list = object.data; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[DashboardChartData]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += + DashboardChartDataSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } + { + final value = object.drillDownChartId; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.projectId; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.visualizationCode; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + return bytesCount; +} + +void _dashboardResponseSerialize( + DashboardResponse object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeString(offsets[0], object.chartType); + writer.writeObjectList( + offsets[1], + allOffsets, + DashboardChartDataSchema.serialize, + object.data, + ); + writer.writeString(offsets[2], object.drillDownChartId); + writer.writeBool(offsets[3], object.hideHeaderDenomination); + writer.writeBool(offsets[4], object.hideInsights); + writer.writeDateTime(offsets[5], object.lastSelectedDate); + writer.writeString(offsets[6], object.projectId); + writer.writeBool(offsets[7], object.showLabel); + writer.writeString(offsets[8], object.visualizationCode); +} + +DashboardResponse _dashboardResponseDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = DashboardResponse(); + object.chartType = reader.readStringOrNull(offsets[0]); + object.data = reader.readObjectList( + offsets[1], + DashboardChartDataSchema.deserialize, + allOffsets, + DashboardChartData(), + ); + object.drillDownChartId = reader.readStringOrNull(offsets[2]); + object.hideHeaderDenomination = reader.readBoolOrNull(offsets[3]); + object.hideInsights = reader.readBoolOrNull(offsets[4]); + object.id = id; + object.lastSelectedDate = reader.readDateTimeOrNull(offsets[5]); + object.projectId = reader.readStringOrNull(offsets[6]); + object.showLabel = reader.readBoolOrNull(offsets[7]); + object.visualizationCode = reader.readStringOrNull(offsets[8]); + return object; +} + +P _dashboardResponseDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readStringOrNull(offset)) as P; + case 1: + return (reader.readObjectList( + offset, + DashboardChartDataSchema.deserialize, + allOffsets, + DashboardChartData(), + )) as P; + case 2: + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readBoolOrNull(offset)) as P; + case 4: + return (reader.readBoolOrNull(offset)) as P; + case 5: + return (reader.readDateTimeOrNull(offset)) as P; + case 6: + return (reader.readStringOrNull(offset)) as P; + case 7: + return (reader.readBoolOrNull(offset)) as P; + case 8: + return (reader.readStringOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +Id _dashboardResponseGetId(DashboardResponse object) { + return object.id; +} + +List> _dashboardResponseGetLinks( + DashboardResponse object) { + return []; +} + +void _dashboardResponseAttach( + IsarCollection col, Id id, DashboardResponse object) { + object.id = id; +} + +extension DashboardResponseQueryWhereSort + on QueryBuilder { + QueryBuilder anyId() { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(const IdWhereClause.any()); + }); + } +} + +extension DashboardResponseQueryWhere + on QueryBuilder { + QueryBuilder + idEqualTo(Id id) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(IdWhereClause.between( + lower: id, + upper: id, + )); + }); + } + + QueryBuilder + idNotEqualTo(Id id) { + return QueryBuilder.apply(this, (query) { + if (query.whereSort == Sort.asc) { + return query + .addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: false), + ) + .addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: false), + ); + } else { + return query + .addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: false), + ) + .addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: false), + ); + } + }); + } + + QueryBuilder + idGreaterThan(Id id, {bool include = false}) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause( + IdWhereClause.greaterThan(lower: id, includeLower: include), + ); + }); + } + + QueryBuilder + idLessThan(Id id, {bool include = false}) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause( + IdWhereClause.lessThan(upper: id, includeUpper: include), + ); + }); + } + + QueryBuilder + idBetween( + Id lowerId, + Id upperId, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addWhereClause(IdWhereClause.between( + lower: lowerId, + includeLower: includeLower, + upper: upperId, + includeUpper: includeUpper, + )); + }); + } +} + +extension DashboardResponseQueryFilter + on QueryBuilder { + QueryBuilder + chartTypeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'chartType', + )); + }); + } + + QueryBuilder + chartTypeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'chartType', + )); + }); + } + + QueryBuilder + chartTypeEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'chartType', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'chartType', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'chartType', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + chartTypeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'chartType', + value: '', + )); + }); + } + + QueryBuilder + chartTypeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'chartType', + value: '', + )); + }); + } + + QueryBuilder + dataIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'data', + )); + }); + } + + QueryBuilder + dataIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'data', + )); + }); + } + + QueryBuilder + dataLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder + dataIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + dataIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + dataLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + dataLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + dataLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'data', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } + + QueryBuilder + drillDownChartIdIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'drillDownChartId', + )); + }); + } + + QueryBuilder + drillDownChartIdIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'drillDownChartId', + )); + }); + } + + QueryBuilder + drillDownChartIdEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'drillDownChartId', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'drillDownChartId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'drillDownChartId', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + drillDownChartIdIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'drillDownChartId', + value: '', + )); + }); + } + + QueryBuilder + drillDownChartIdIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'drillDownChartId', + value: '', + )); + }); + } + + QueryBuilder + hideHeaderDenominationIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'hideHeaderDenomination', + )); + }); + } + + QueryBuilder + hideHeaderDenominationIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'hideHeaderDenomination', + )); + }); + } + + QueryBuilder + hideHeaderDenominationEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'hideHeaderDenomination', + value: value, + )); + }); + } + + QueryBuilder + hideInsightsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'hideInsights', + )); + }); + } + + QueryBuilder + hideInsightsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'hideInsights', + )); + }); + } + + QueryBuilder + hideInsightsEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'hideInsights', + value: value, + )); + }); + } + + QueryBuilder + idEqualTo(Id value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idGreaterThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idLessThan( + Id value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'id', + value: value, + )); + }); + } + + QueryBuilder + idBetween( + Id lower, + Id upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'id', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + )); + }); + } + + QueryBuilder + lastSelectedDateIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'lastSelectedDate', + )); + }); + } + + QueryBuilder + lastSelectedDateIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'lastSelectedDate', + )); + }); + } + + QueryBuilder + lastSelectedDateEqualTo(DateTime? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'lastSelectedDate', + value: value, + )); + }); + } + + QueryBuilder + lastSelectedDateGreaterThan( + DateTime? value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'lastSelectedDate', + value: value, + )); + }); + } + + QueryBuilder + lastSelectedDateLessThan( + DateTime? value, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'lastSelectedDate', + value: value, + )); + }); + } + + QueryBuilder + lastSelectedDateBetween( + DateTime? lower, + DateTime? upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'lastSelectedDate', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + )); + }); + } + + QueryBuilder + projectIdIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'projectId', + )); + }); + } + + QueryBuilder + projectIdIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'projectId', + )); + }); + } + + QueryBuilder + projectIdEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'projectId', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'projectId', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'projectId', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + projectIdIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'projectId', + value: '', + )); + }); + } + + QueryBuilder + projectIdIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'projectId', + value: '', + )); + }); + } + + QueryBuilder + showLabelIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'showLabel', + )); + }); + } + + QueryBuilder + showLabelIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'showLabel', + )); + }); + } + + QueryBuilder + showLabelEqualTo(bool? value) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'showLabel', + value: value, + )); + }); + } + + QueryBuilder + visualizationCodeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'visualizationCode', + )); + }); + } + + QueryBuilder + visualizationCodeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'visualizationCode', + )); + }); + } + + QueryBuilder + visualizationCodeEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'visualizationCode', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'visualizationCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'visualizationCode', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + visualizationCodeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'visualizationCode', + value: '', + )); + }); + } + + QueryBuilder + visualizationCodeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'visualizationCode', + value: '', + )); + }); + } +} + +extension DashboardResponseQueryObject + on QueryBuilder { + QueryBuilder + dataElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'data'); + }); + } +} + +extension DashboardResponseQueryLinks + on QueryBuilder {} + +extension DashboardResponseQuerySortBy + on QueryBuilder { + QueryBuilder + sortByChartType() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chartType', Sort.asc); + }); + } + + QueryBuilder + sortByChartTypeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chartType', Sort.desc); + }); + } + + QueryBuilder + sortByDrillDownChartId() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'drillDownChartId', Sort.asc); + }); + } + + QueryBuilder + sortByDrillDownChartIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'drillDownChartId', Sort.desc); + }); + } + + QueryBuilder + sortByHideHeaderDenomination() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideHeaderDenomination', Sort.asc); + }); + } + + QueryBuilder + sortByHideHeaderDenominationDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideHeaderDenomination', Sort.desc); + }); + } + + QueryBuilder + sortByHideInsights() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideInsights', Sort.asc); + }); + } + + QueryBuilder + sortByHideInsightsDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideInsights', Sort.desc); + }); + } + + QueryBuilder + sortByLastSelectedDate() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'lastSelectedDate', Sort.asc); + }); + } + + QueryBuilder + sortByLastSelectedDateDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'lastSelectedDate', Sort.desc); + }); + } + + QueryBuilder + sortByProjectId() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'projectId', Sort.asc); + }); + } + + QueryBuilder + sortByProjectIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'projectId', Sort.desc); + }); + } + + QueryBuilder + sortByShowLabel() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'showLabel', Sort.asc); + }); + } + + QueryBuilder + sortByShowLabelDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'showLabel', Sort.desc); + }); + } + + QueryBuilder + sortByVisualizationCode() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'visualizationCode', Sort.asc); + }); + } + + QueryBuilder + sortByVisualizationCodeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'visualizationCode', Sort.desc); + }); + } +} + +extension DashboardResponseQuerySortThenBy + on QueryBuilder { + QueryBuilder + thenByChartType() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chartType', Sort.asc); + }); + } + + QueryBuilder + thenByChartTypeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'chartType', Sort.desc); + }); + } + + QueryBuilder + thenByDrillDownChartId() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'drillDownChartId', Sort.asc); + }); + } + + QueryBuilder + thenByDrillDownChartIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'drillDownChartId', Sort.desc); + }); + } + + QueryBuilder + thenByHideHeaderDenomination() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideHeaderDenomination', Sort.asc); + }); + } + + QueryBuilder + thenByHideHeaderDenominationDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideHeaderDenomination', Sort.desc); + }); + } + + QueryBuilder + thenByHideInsights() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideInsights', Sort.asc); + }); + } + + QueryBuilder + thenByHideInsightsDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'hideInsights', Sort.desc); + }); + } + + QueryBuilder thenById() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'id', Sort.asc); + }); + } + + QueryBuilder + thenByIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'id', Sort.desc); + }); + } + + QueryBuilder + thenByLastSelectedDate() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'lastSelectedDate', Sort.asc); + }); + } + + QueryBuilder + thenByLastSelectedDateDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'lastSelectedDate', Sort.desc); + }); + } + + QueryBuilder + thenByProjectId() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'projectId', Sort.asc); + }); + } + + QueryBuilder + thenByProjectIdDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'projectId', Sort.desc); + }); + } + + QueryBuilder + thenByShowLabel() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'showLabel', Sort.asc); + }); + } + + QueryBuilder + thenByShowLabelDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'showLabel', Sort.desc); + }); + } + + QueryBuilder + thenByVisualizationCode() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'visualizationCode', Sort.asc); + }); + } + + QueryBuilder + thenByVisualizationCodeDesc() { + return QueryBuilder.apply(this, (query) { + return query.addSortBy(r'visualizationCode', Sort.desc); + }); + } +} + +extension DashboardResponseQueryWhereDistinct + on QueryBuilder { + QueryBuilder + distinctByChartType({bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'chartType', caseSensitive: caseSensitive); + }); + } + + QueryBuilder + distinctByDrillDownChartId({bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'drillDownChartId', + caseSensitive: caseSensitive); + }); + } + + QueryBuilder + distinctByHideHeaderDenomination() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'hideHeaderDenomination'); + }); + } + + QueryBuilder + distinctByHideInsights() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'hideInsights'); + }); + } + + QueryBuilder + distinctByLastSelectedDate() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'lastSelectedDate'); + }); + } + + QueryBuilder + distinctByProjectId({bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'projectId', caseSensitive: caseSensitive); + }); + } + + QueryBuilder + distinctByShowLabel() { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'showLabel'); + }); + } + + QueryBuilder + distinctByVisualizationCode({bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addDistinctBy(r'visualizationCode', + caseSensitive: caseSensitive); + }); + } +} + +extension DashboardResponseQueryProperty + on QueryBuilder { + QueryBuilder idProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'id'); + }); + } + + QueryBuilder + chartTypeProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'chartType'); + }); + } + + QueryBuilder?, QQueryOperations> + dataProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'data'); + }); + } + + QueryBuilder + drillDownChartIdProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'drillDownChartId'); + }); + } + + QueryBuilder + hideHeaderDenominationProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'hideHeaderDenomination'); + }); + } + + QueryBuilder + hideInsightsProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'hideInsights'); + }); + } + + QueryBuilder + lastSelectedDateProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'lastSelectedDate'); + }); + } + + QueryBuilder + projectIdProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'projectId'); + }); + } + + QueryBuilder showLabelProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'showLabel'); + }); + } + + QueryBuilder + visualizationCodeProperty() { + return QueryBuilder.apply(this, (query) { + return query.addPropertyName(r'visualizationCode'); + }); + } +} + +// ************************************************************************** +// IsarEmbeddedGenerator +// ************************************************************************** + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const DashboardChartDataSchema = Schema( + name: r'DashboardChartData', + id: -4200617381045034431, + properties: { + r'headerName': PropertySchema( + id: 0, + name: r'headerName', + type: IsarType.string, + ), + r'headerSymbol': PropertySchema( + id: 1, + name: r'headerSymbol', + type: IsarType.string, + ), + r'headerValue': PropertySchema( + id: 2, + name: r'headerValue', + type: IsarType.string, + ), + r'insight': PropertySchema( + id: 3, + name: r'insight', + type: IsarType.object, + target: r'Insight', + ), + r'plots': PropertySchema( + id: 4, + name: r'plots', + type: IsarType.objectList, + target: r'DashboardPlot', + ) + }, + estimateSize: _dashboardChartDataEstimateSize, + serialize: _dashboardChartDataSerialize, + deserialize: _dashboardChartDataDeserialize, + deserializeProp: _dashboardChartDataDeserializeProp, +); + +int _dashboardChartDataEstimateSize( + DashboardChartData object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final value = object.headerName; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.headerSymbol; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.headerValue; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.insight; + if (value != null) { + bytesCount += 3 + + InsightSchema.estimateSize(value, allOffsets[Insight]!, allOffsets); + } + } + { + final list = object.plots; + if (list != null) { + bytesCount += 3 + list.length * 3; + { + final offsets = allOffsets[DashboardPlot]!; + for (var i = 0; i < list.length; i++) { + final value = list[i]; + bytesCount += + DashboardPlotSchema.estimateSize(value, offsets, allOffsets); + } + } + } + } + return bytesCount; +} + +void _dashboardChartDataSerialize( + DashboardChartData object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeString(offsets[0], object.headerName); + writer.writeString(offsets[1], object.headerSymbol); + writer.writeString(offsets[2], object.headerValue); + writer.writeObject( + offsets[3], + allOffsets, + InsightSchema.serialize, + object.insight, + ); + writer.writeObjectList( + offsets[4], + allOffsets, + DashboardPlotSchema.serialize, + object.plots, + ); +} + +DashboardChartData _dashboardChartDataDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = DashboardChartData(); + object.headerName = reader.readStringOrNull(offsets[0]); + object.headerSymbol = reader.readStringOrNull(offsets[1]); + object.headerValue = reader.readStringOrNull(offsets[2]); + object.insight = reader.readObjectOrNull( + offsets[3], + InsightSchema.deserialize, + allOffsets, + ); + object.plots = reader.readObjectList( + offsets[4], + DashboardPlotSchema.deserialize, + allOffsets, + DashboardPlot(), + ); + return object; +} + +P _dashboardChartDataDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readStringOrNull(offset)) as P; + case 1: + return (reader.readStringOrNull(offset)) as P; + case 2: + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readObjectOrNull( + offset, + InsightSchema.deserialize, + allOffsets, + )) as P; + case 4: + return (reader.readObjectList( + offset, + DashboardPlotSchema.deserialize, + allOffsets, + DashboardPlot(), + )) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension DashboardChartDataQueryFilter + on QueryBuilder { + QueryBuilder + headerNameIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'headerName', + )); + }); + } + + QueryBuilder + headerNameIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'headerName', + )); + }); + } + + QueryBuilder + headerNameEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'headerName', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'headerName', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'headerName', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerNameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerName', + value: '', + )); + }); + } + + QueryBuilder + headerNameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'headerName', + value: '', + )); + }); + } + + QueryBuilder + headerSymbolIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'headerSymbol', + )); + }); + } + + QueryBuilder + headerSymbolIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'headerSymbol', + )); + }); + } + + QueryBuilder + headerSymbolEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'headerSymbol', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'headerSymbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'headerSymbol', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerSymbolIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerSymbol', + value: '', + )); + }); + } + + QueryBuilder + headerSymbolIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'headerSymbol', + value: '', + )); + }); + } + + QueryBuilder + headerValueIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'headerValue', + )); + }); + } + + QueryBuilder + headerValueIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'headerValue', + )); + }); + } + + QueryBuilder + headerValueEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'headerValue', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'headerValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'headerValue', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + headerValueIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'headerValue', + value: '', + )); + }); + } + + QueryBuilder + headerValueIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'headerValue', + value: '', + )); + }); + } + + QueryBuilder + insightIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'insight', + )); + }); + } + + QueryBuilder + insightIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'insight', + )); + }); + } + + QueryBuilder + plotsIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'plots', + )); + }); + } + + QueryBuilder + plotsIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'plots', + )); + }); + } + + QueryBuilder + plotsLengthEqualTo(int length) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + length, + true, + length, + true, + ); + }); + } + + QueryBuilder + plotsIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + 0, + true, + 0, + true, + ); + }); + } + + QueryBuilder + plotsIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + 0, + false, + 999999, + true, + ); + }); + } + + QueryBuilder + plotsLengthLessThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + 0, + true, + length, + include, + ); + }); + } + + QueryBuilder + plotsLengthGreaterThan( + int length, { + bool include = false, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + length, + include, + 999999, + true, + ); + }); + } + + QueryBuilder + plotsLengthBetween( + int lower, + int upper, { + bool includeLower = true, + bool includeUpper = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.listLength( + r'plots', + lower, + includeLower, + upper, + includeUpper, + ); + }); + } +} + +extension DashboardChartDataQueryObject + on QueryBuilder { + QueryBuilder + insight(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'insight'); + }); + } + + QueryBuilder + plotsElement(FilterQuery q) { + return QueryBuilder.apply(this, (query) { + return query.object(q, r'plots'); + }); + } +} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const DashboardPlotSchema = Schema( + name: r'DashboardPlot', + id: -4159917448319374876, + properties: { + r'label': PropertySchema( + id: 0, + name: r'label', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 1, + name: r'name', + type: IsarType.string, + ), + r'strValue': PropertySchema( + id: 2, + name: r'strValue', + type: IsarType.string, + ), + r'symbol': PropertySchema( + id: 3, + name: r'symbol', + type: IsarType.string, + ), + r'value': PropertySchema( + id: 4, + name: r'value', + type: IsarType.string, + ) + }, + estimateSize: _dashboardPlotEstimateSize, + serialize: _dashboardPlotSerialize, + deserialize: _dashboardPlotDeserialize, + deserializeProp: _dashboardPlotDeserializeProp, +); + +int _dashboardPlotEstimateSize( + DashboardPlot object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final value = object.label; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.name; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.strValue; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.symbol; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.value; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + return bytesCount; +} + +void _dashboardPlotSerialize( + DashboardPlot object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeString(offsets[0], object.label); + writer.writeString(offsets[1], object.name); + writer.writeString(offsets[2], object.strValue); + writer.writeString(offsets[3], object.symbol); + writer.writeString(offsets[4], object.value); +} + +DashboardPlot _dashboardPlotDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = DashboardPlot(); + object.label = reader.readStringOrNull(offsets[0]); + object.name = reader.readStringOrNull(offsets[1]); + object.strValue = reader.readStringOrNull(offsets[2]); + object.symbol = reader.readStringOrNull(offsets[3]); + object.value = reader.readStringOrNull(offsets[4]); + return object; +} + +P _dashboardPlotDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readStringOrNull(offset)) as P; + case 1: + return (reader.readStringOrNull(offset)) as P; + case 2: + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readStringOrNull(offset)) as P; + case 4: + return (reader.readStringOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension DashboardPlotQueryFilter + on QueryBuilder { + QueryBuilder + labelIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'label', + )); + }); + } + + QueryBuilder + labelIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'label', + )); + }); + } + + QueryBuilder + labelEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'label', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'label', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'label', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + labelIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'label', + value: '', + )); + }); + } + + QueryBuilder + labelIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'label', + value: '', + )); + }); + } + + QueryBuilder + nameIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'name', + )); + }); + } + + QueryBuilder + nameIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'name', + )); + }); + } + + QueryBuilder nameEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder + strValueIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'strValue', + )); + }); + } + + QueryBuilder + strValueIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'strValue', + )); + }); + } + + QueryBuilder + strValueEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'strValue', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'strValue', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'strValue', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + strValueIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'strValue', + value: '', + )); + }); + } + + QueryBuilder + strValueIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'strValue', + value: '', + )); + }); + } + + QueryBuilder + symbolIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'symbol', + )); + }); + } + + QueryBuilder + symbolIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'symbol', + )); + }); + } + + QueryBuilder + symbolEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'symbol', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'symbol', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'symbol', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + symbolIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'symbol', + value: '', + )); + }); + } + + QueryBuilder + symbolIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'symbol', + value: '', + )); + }); + } + + QueryBuilder + valueIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'value', + )); + }); + } + + QueryBuilder + valueIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'value', + )); + }); + } + + QueryBuilder + valueEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'value', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueContains(String value, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueMatches(String pattern, {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'value', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder + valueIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'value', + value: '', + )); + }); + } + + QueryBuilder + valueIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'value', + value: '', + )); + }); + } +} + +extension DashboardPlotQueryObject + on QueryBuilder {} + +// coverage:ignore-file +// ignore_for_file: duplicate_ignore, non_constant_identifier_names, constant_identifier_names, invalid_use_of_protected_member, unnecessary_cast, prefer_const_constructors, lines_longer_than_80_chars, require_trailing_commas, inference_failure_on_function_invocation, unnecessary_parenthesis, unnecessary_raw_strings, unnecessary_null_checks, join_return_with_assignment, prefer_final_locals, avoid_js_rounded_ints, avoid_positional_boolean_parameters, always_specify_types + +const InsightSchema = Schema( + name: r'Insight', + id: -5337822884227880275, + properties: { + r'colorCode': PropertySchema( + id: 0, + name: r'colorCode', + type: IsarType.string, + ), + r'indicator': PropertySchema( + id: 1, + name: r'indicator', + type: IsarType.string, + ), + r'name': PropertySchema( + id: 2, + name: r'name', + type: IsarType.string, + ), + r'value': PropertySchema( + id: 3, + name: r'value', + type: IsarType.string, + ) + }, + estimateSize: _insightEstimateSize, + serialize: _insightSerialize, + deserialize: _insightDeserialize, + deserializeProp: _insightDeserializeProp, +); + +int _insightEstimateSize( + Insight object, + List offsets, + Map> allOffsets, +) { + var bytesCount = offsets.last; + { + final value = object.colorCode; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.indicator; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.name; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + { + final value = object.value; + if (value != null) { + bytesCount += 3 + value.length * 3; + } + } + return bytesCount; +} + +void _insightSerialize( + Insight object, + IsarWriter writer, + List offsets, + Map> allOffsets, +) { + writer.writeString(offsets[0], object.colorCode); + writer.writeString(offsets[1], object.indicator); + writer.writeString(offsets[2], object.name); + writer.writeString(offsets[3], object.value); +} + +Insight _insightDeserialize( + Id id, + IsarReader reader, + List offsets, + Map> allOffsets, +) { + final object = Insight(); + object.colorCode = reader.readStringOrNull(offsets[0]); + object.indicator = reader.readStringOrNull(offsets[1]); + object.name = reader.readStringOrNull(offsets[2]); + object.value = reader.readStringOrNull(offsets[3]); + return object; +} + +P _insightDeserializeProp

( + IsarReader reader, + int propertyId, + int offset, + Map> allOffsets, +) { + switch (propertyId) { + case 0: + return (reader.readStringOrNull(offset)) as P; + case 1: + return (reader.readStringOrNull(offset)) as P; + case 2: + return (reader.readStringOrNull(offset)) as P; + case 3: + return (reader.readStringOrNull(offset)) as P; + default: + throw IsarError('Unknown property with id $propertyId'); + } +} + +extension InsightQueryFilter + on QueryBuilder { + QueryBuilder colorCodeIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'colorCode', + )); + }); + } + + QueryBuilder colorCodeIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'colorCode', + )); + }); + } + + QueryBuilder colorCodeEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'colorCode', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'colorCode', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'colorCode', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder colorCodeIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'colorCode', + value: '', + )); + }); + } + + QueryBuilder colorCodeIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'colorCode', + value: '', + )); + }); + } + + QueryBuilder indicatorIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'indicator', + )); + }); + } + + QueryBuilder indicatorIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'indicator', + )); + }); + } + + QueryBuilder indicatorEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'indicator', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'indicator', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'indicator', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder indicatorIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'indicator', + value: '', + )); + }); + } + + QueryBuilder indicatorIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'indicator', + value: '', + )); + }); + } + + QueryBuilder nameIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'name', + )); + }); + } + + QueryBuilder nameIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'name', + )); + }); + } + + QueryBuilder nameEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'name', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'name', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'name', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder nameIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder nameIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'name', + value: '', + )); + }); + } + + QueryBuilder valueIsNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNull( + property: r'value', + )); + }); + } + + QueryBuilder valueIsNotNull() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(const FilterCondition.isNotNull( + property: r'value', + )); + }); + } + + QueryBuilder valueEqualTo( + String? value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueGreaterThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + include: include, + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueLessThan( + String? value, { + bool include = false, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.lessThan( + include: include, + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueBetween( + String? lower, + String? upper, { + bool includeLower = true, + bool includeUpper = true, + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.between( + property: r'value', + lower: lower, + includeLower: includeLower, + upper: upper, + includeUpper: includeUpper, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueStartsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.startsWith( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueEndsWith( + String value, { + bool caseSensitive = true, + }) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.endsWith( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueContains( + String value, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.contains( + property: r'value', + value: value, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueMatches( + String pattern, + {bool caseSensitive = true}) { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.matches( + property: r'value', + wildcard: pattern, + caseSensitive: caseSensitive, + )); + }); + } + + QueryBuilder valueIsEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.equalTo( + property: r'value', + value: '', + )); + }); + } + + QueryBuilder valueIsNotEmpty() { + return QueryBuilder.apply(this, (query) { + return query.addFilterCondition(FilterCondition.greaterThan( + property: r'value', + value: '', + )); + }); + } +} + +extension InsightQueryObject + on QueryBuilder {} diff --git a/packages/digit_dss/lib/data/remote/dashboard.dart b/packages/digit_dss/lib/data/remote/dashboard.dart new file mode 100644 index 000000000..f601d6037 --- /dev/null +++ b/packages/digit_dss/lib/data/remote/dashboard.dart @@ -0,0 +1,152 @@ +import 'dart:async'; // Import the dart:async library for asynchronous operations +import 'dart:convert'; // Import the dart:convert library for JSON encoding and decoding + +import 'package:digit_components/utils/app_logger.dart'; // Import the app_logger.dart file from the digit_components package +import 'package:digit_dss/data/local_store/no_sql/schema/dashboard_response.dart'; // Import the dashboard_response.dart file from the digit_dss package +import 'package:dio/dio.dart'; // Import the dio package for HTTP client functionality +import 'package:flutter/material.dart'; +import 'package:isar/isar.dart'; // Import the isar package for database management + +import '../../models/entities/dashboard_config.dart'; +import '../../models/entities/dashboard_response_model.dart'; +import '../../models/entities/dss_enums.dart'; +import '../local_store/no_sql/schema/dashboard_config_schema.dart'; // Import the dashboard_response_model.dart file from the models/entities directory + +// DashboardRemoteRepository class handles remote API requests and database transactions +class DashboardRemoteRepository { + final Dio _client; // Dio HTTP client instance + DashboardRemoteRepository( + this._client); // Constructor to initialize the Dio client + + // Method to search data from the API and write it to the Isar database + FutureOr searchAndWriteToDB({ + required String apiEndPoint, // API endpoint URL + Object? query, // Query parameters for the API request + required String projectId, // Project ID for filtering data + DateTime? lastSelectedDate, // Last selected date for filtering data + required Isar isar, // Isar database instance + }) async { + try { + final response = await _client.post( + apiEndPoint, + data: query, + ); // Make a POST request to the API endpoint with the query parameters + + // Map the response data to the DashboardResponseModel + final dashboardResponse = DashboardResponseModelMapper.fromMap( + json.decode(response.data)[DSSEnums.responseData.toValue()], + ); + + if (dashboardResponse.data != null) { + // Write transaction to delete existing data and insert new data + isar.writeTxnSync(() { + isar.dashboardResponses + .where() + .filter() + .projectIdEqualTo(projectId) + .visualizationCodeEqualTo(dashboardResponse.visualizationCode) + .chartTypeEqualTo(dashboardResponse.chartType) + .deleteAll(); // Delete existing data matching the project ID, visualization code, and chart type + }); + + final data = + dashboardResponse; // Assign the dashboard response data to a local variable + final chart = + DashboardResponse(); // Create a new DashboardResponse instance + chart.chartType = data.chartType; // Set chart type + chart.hideHeaderDenomination = + data.hideHeaderDenomination; // Set hide header denomination flag + chart.lastSelectedDate = + lastSelectedDate ?? DateTime.now(); // Set last selected date + chart.visualizationCode = + data.visualizationCode; // Set visualization code + chart.projectId = projectId; // Set project ID + chart.drillDownChartId = + data.drillDownChartId; // Set drill down chart ID + chart.hideInsights = data.hideInsights; // Set hide insights flag + chart.showLabel = data.showLabel; // Set show label flag + + // Map the data plots to the DashboardChartData and DashboardPlot instances + final dataPlots = data.data?.map((c) { + final chartData = DashboardChartData(); + chartData.headerValue = c.headerValue; + chartData.headerName = c.headerName; + chartData.headerSymbol = c.headerSymbol; + chartData.plots = c.plots?.map((p) { + final plot = DashboardPlot(); + plot.label = p.label; + plot.strValue = p.strValue; + plot.name = p.name; + plot.value = p.value; + plot.symbol = p.symbol; + return plot; + }).toList(); + + // Map the insight data to the Insight instance + final insight = Insight(); + insight.value = c.insight?.value; + insight.name = c.insight?.name; + insight.colorCode = c.insight?.colorCode; + insight.indicator = c.insight?.indicator; + chartData.insight = insight; + return chartData; + }).toList(); + chart.data = dataPlots; // Set the data plots + + // Write transaction to insert the new chart data + return isar.writeTxnSync(() { + isar.dashboardResponses.putSync(chart); + }); + } + } on DioException catch (e) { + // Handle Dio exceptions and log the error + debugPrint(e.toString()); + AppLogger.instance.error( + title: 'Dashboard Repository', + message: '$e', + stackTrace: e.stackTrace, + ); + rethrow; // Rethrow the exception + } + } + + Future searchDashboardConfig( + String apiEndPoint, + Map body, + ) async { + try { + final response = await _client.post(apiEndPoint, data: body); + + final appCon = jsonEncode(response.data); + + return appCon; + } on DioException catch (e) { + AppLogger.instance.error( + title: 'MDMS Repository', + message: '$e', + stackTrace: e.stackTrace, + ); + rethrow; + } + } + + FutureOr writeToDashboardConfigDB( + DashboardConfigWrapper dashboardConfigWrapper, + Isar isar, + ) async { + final dashboardConfig = DashboardConfigSchema() + ..enableDashboard = dashboardConfigWrapper.enableDashboard + ..charts = dashboardConfigWrapper.charts?.map((chart) { + final dssChart = DashboardChartConfigSchema() + ..name = chart.name + ..active = chart.active + ..chartType = chart.chartType + ..vizType = chart.vizType; + return dssChart; + }).toList(); + + isar.writeTxnSync(() { + isar.dashboardConfigSchemas.putSync(dashboardConfig); + }); + } +} diff --git a/packages/digit_dss/lib/digit_dss.dart b/packages/digit_dss/lib/digit_dss.dart new file mode 100644 index 000000000..49d02c3f6 --- /dev/null +++ b/packages/digit_dss/lib/digit_dss.dart @@ -0,0 +1,24 @@ +@MappableLib( + generateInitializerForScope: InitializerScope.package, +) +library digit_dss; + +import 'package:dart_mappable/dart_mappable.dart'; + +export 'package:digit_dss/utils/utils.dart'; + +export 'blocs/app_localization.dart'; +export 'blocs/dashboard.dart'; +export 'blocs/dashboard_localization_delegate.dart'; +export 'data/local_store/no_sql/schema/dashboard_response.dart'; +export 'data/local_store/no_sql/schema/dashboard_config_schema.dart'; +export 'data/remote/dashboard.dart'; +export 'digit_dss.init.dart'; +export 'models/entities/chart_data.dart'; +export 'models/entities/dashboard_request.dart'; +export 'models/entities/dashboard_response_model.dart'; +export 'models/entities/dss_enums.dart'; +export 'models/entities/insight.dart'; +export 'models/entities/plots.dart'; +export 'models/entities/dashboard_config.dart'; +export 'pages/dashboard/dashboard.dart'; diff --git a/packages/digit_dss/lib/digit_dss.init.dart b/packages/digit_dss/lib/digit_dss.init.dart new file mode 100644 index 000000000..473c2fcb0 --- /dev/null +++ b/packages/digit_dss/lib/digit_dss.init.dart @@ -0,0 +1,24 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element + +import 'models/entities/chart_data.dart' as p0; +import 'models/entities/dashboard_request.dart' as p1; +import 'models/entities/dashboard_response_model.dart' as p2; +import 'models/entities/dss_enums.dart' as p3; +import 'models/entities/insight.dart' as p4; +import 'models/entities/plots.dart' as p5; + +void initializeMappers() { + p0.DashboardChartDataModelMapper.ensureInitialized(); + p1.DashboardRequestModelMapper.ensureInitialized(); + p1.AggregationRequestDtoMapper.ensureInitialized(); + p1.DSSHeadersMapper.ensureInitialized(); + p1.RequestDateMapper.ensureInitialized(); + p2.DashboardResponseSearchModelMapper.ensureInitialized(); + p2.DashboardResponseModelMapper.ensureInitialized(); + p3.DSSEnumsMapper.ensureInitialized(); + p4.InsightModelMapper.ensureInitialized(); + p5.DashboardPlotModelMapper.ensureInitialized(); +} diff --git a/packages/digit_dss/lib/models/entities/chart_data.dart b/packages/digit_dss/lib/models/entities/chart_data.dart new file mode 100644 index 000000000..5e66310db --- /dev/null +++ b/packages/digit_dss/lib/models/entities/chart_data.dart @@ -0,0 +1,30 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/models/entities/insight.dart'; +import 'package:digit_dss/models/entities/plots.dart'; + +part 'chart_data.mapper.dart'; + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DashboardChartDataModel with DashboardChartDataModelMappable { + final String? headerName; + final String? headerSymbol; + final String? headerValue; + final InsightModel? insight; + final List? plots; + final String? visualizationCode; + final String? chartType; + final String? projectId; + + DashboardChartDataModel({ + this.headerName, + this.headerSymbol, + this.headerValue, + this.projectId, + this.chartType, + this.visualizationCode, + this.insight, + this.plots, + }) : super(); +} diff --git a/packages/digit_dss/lib/models/entities/chart_data.mapper.dart b/packages/digit_dss/lib/models/entities/chart_data.mapper.dart new file mode 100644 index 000000000..9a69bda16 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/chart_data.mapper.dart @@ -0,0 +1,213 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'chart_data.dart'; + +class DashboardChartDataModelMapper + extends ClassMapperBase { + DashboardChartDataModelMapper._(); + + static DashboardChartDataModelMapper? _instance; + static DashboardChartDataModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals + .use(_instance = DashboardChartDataModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'DashboardChartDataModel'; + + static String? _$headerName(DashboardChartDataModel v) => v.headerName; + static const Field _f$headerName = + Field('headerName', _$headerName, opt: true); + static String? _$headerSymbol(DashboardChartDataModel v) => v.headerSymbol; + static const Field _f$headerSymbol = + Field('headerSymbol', _$headerSymbol, opt: true); + static String? _$headerValue(DashboardChartDataModel v) => v.headerValue; + static const Field _f$headerValue = + Field('headerValue', _$headerValue, opt: true); + static String? _$projectId(DashboardChartDataModel v) => v.projectId; + static const Field _f$projectId = + Field('projectId', _$projectId, opt: true); + static String? _$chartType(DashboardChartDataModel v) => v.chartType; + static const Field _f$chartType = + Field('chartType', _$chartType, opt: true); + static String? _$visualizationCode(DashboardChartDataModel v) => + v.visualizationCode; + static const Field _f$visualizationCode = + Field('visualizationCode', _$visualizationCode, opt: true); + static InsightModel? _$insight(DashboardChartDataModel v) => v.insight; + static const Field _f$insight = + Field('insight', _$insight, opt: true); + static List? _$plots(DashboardChartDataModel v) => + v.plots; + static const Field> + _f$plots = Field('plots', _$plots, opt: true); + + @override + final MappableFields fields = const { + #headerName: _f$headerName, + #headerSymbol: _f$headerSymbol, + #headerValue: _f$headerValue, + #projectId: _f$projectId, + #chartType: _f$chartType, + #visualizationCode: _f$visualizationCode, + #insight: _f$insight, + #plots: _f$plots, + }; + @override + final bool ignoreNull = true; + + static DashboardChartDataModel _instantiate(DecodingData data) { + return DashboardChartDataModel( + headerName: data.dec(_f$headerName), + headerSymbol: data.dec(_f$headerSymbol), + headerValue: data.dec(_f$headerValue), + projectId: data.dec(_f$projectId), + chartType: data.dec(_f$chartType), + visualizationCode: data.dec(_f$visualizationCode), + insight: data.dec(_f$insight), + plots: data.dec(_f$plots)); + } + + @override + final Function instantiate = _instantiate; + + static DashboardChartDataModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DashboardChartDataModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DashboardChartDataModelMappable { + String toJson() { + return DashboardChartDataModelMapper.ensureInitialized() + .encodeJson(this as DashboardChartDataModel); + } + + Map toMap() { + return DashboardChartDataModelMapper.ensureInitialized() + .encodeMap(this as DashboardChartDataModel); + } + + DashboardChartDataModelCopyWith + get copyWith => _DashboardChartDataModelCopyWithImpl( + this as DashboardChartDataModel, $identity, $identity); + @override + String toString() { + return DashboardChartDataModelMapper.ensureInitialized() + .stringifyValue(this as DashboardChartDataModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DashboardChartDataModelMapper.ensureInitialized() + .isValueEqual(this as DashboardChartDataModel, other)); + } + + @override + int get hashCode { + return DashboardChartDataModelMapper.ensureInitialized() + .hashValue(this as DashboardChartDataModel); + } +} + +extension DashboardChartDataModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, DashboardChartDataModel, $Out> { + DashboardChartDataModelCopyWith<$R, DashboardChartDataModel, $Out> + get $asDashboardChartDataModel => $base + .as((v, t, t2) => _DashboardChartDataModelCopyWithImpl(v, t, t2)); +} + +abstract class DashboardChartDataModelCopyWith< + $R, + $In extends DashboardChartDataModel, + $Out> implements ClassCopyWith<$R, $In, $Out> { + InsightModelCopyWith<$R, InsightModel, InsightModel>? get insight; + ListCopyWith< + $R, + DashboardPlotModel, + DashboardPlotModelCopyWith<$R, DashboardPlotModel, + DashboardPlotModel>>? get plots; + $R call( + {String? headerName, + String? headerSymbol, + String? headerValue, + String? projectId, + String? chartType, + String? visualizationCode, + InsightModel? insight, + List? plots}); + DashboardChartDataModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _DashboardChartDataModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DashboardChartDataModel, $Out> + implements + DashboardChartDataModelCopyWith<$R, DashboardChartDataModel, $Out> { + _DashboardChartDataModelCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DashboardChartDataModelMapper.ensureInitialized(); + @override + InsightModelCopyWith<$R, InsightModel, InsightModel>? get insight => + $value.insight?.copyWith.$chain((v) => call(insight: v)); + @override + ListCopyWith< + $R, + DashboardPlotModel, + DashboardPlotModelCopyWith<$R, DashboardPlotModel, + DashboardPlotModel>>? get plots => $value.plots != null + ? ListCopyWith( + $value.plots!, (v, t) => v.copyWith.$chain(t), (v) => call(plots: v)) + : null; + @override + $R call( + {Object? headerName = $none, + Object? headerSymbol = $none, + Object? headerValue = $none, + Object? projectId = $none, + Object? chartType = $none, + Object? visualizationCode = $none, + Object? insight = $none, + Object? plots = $none}) => + $apply(FieldCopyWithData({ + if (headerName != $none) #headerName: headerName, + if (headerSymbol != $none) #headerSymbol: headerSymbol, + if (headerValue != $none) #headerValue: headerValue, + if (projectId != $none) #projectId: projectId, + if (chartType != $none) #chartType: chartType, + if (visualizationCode != $none) #visualizationCode: visualizationCode, + if (insight != $none) #insight: insight, + if (plots != $none) #plots: plots + })); + @override + DashboardChartDataModel $make(CopyWithData data) => DashboardChartDataModel( + headerName: data.get(#headerName, or: $value.headerName), + headerSymbol: data.get(#headerSymbol, or: $value.headerSymbol), + headerValue: data.get(#headerValue, or: $value.headerValue), + projectId: data.get(#projectId, or: $value.projectId), + chartType: data.get(#chartType, or: $value.chartType), + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode), + insight: data.get(#insight, or: $value.insight), + plots: data.get(#plots, or: $value.plots)); + + @override + DashboardChartDataModelCopyWith<$R2, DashboardChartDataModel, $Out2> + $chain<$R2, $Out2>(Then<$Out2, $R2> t) => + _DashboardChartDataModelCopyWithImpl($value, $cast, t); +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_config.dart b/packages/digit_dss/lib/models/entities/dashboard_config.dart new file mode 100644 index 000000000..e510ad5aa --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_config.dart @@ -0,0 +1,46 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'dashboard_config.freezed.dart'; +part 'dashboard_config.g.dart'; + +@freezed +class DashboardConfigPrimaryWrapper with _$DashboardConfigPrimaryWrapper { + const factory DashboardConfigPrimaryWrapper({ + @JsonKey(name: 'dashboardConfig') + @Default([]) + List dashboardConfigWrapper, + }) = _DashboardConfigPrimaryWrapper; + + factory DashboardConfigPrimaryWrapper.fromJson( + Map json, + ) => + _$DashboardConfigPrimaryWrapperFromJson(json); +} + +@freezed +class DashboardConfigWrapper with _$DashboardConfigWrapper { + const factory DashboardConfigWrapper({ + @JsonKey(name: 'enableDashboard') required bool enableDashboard, + @JsonKey(name: 'charts') List? charts, + }) = _DashboardConfigWrapper; + + factory DashboardConfigWrapper.fromJson( + Map json, + ) => + _$DashboardConfigWrapperFromJson(json); +} + +@freezed +class ChartConfigModel with _$ChartConfigModel { + const factory ChartConfigModel({ + @JsonKey(name: 'active') required bool active, + @JsonKey(name: 'name') required String name, + @JsonKey(name: 'vizType') String? vizType, + @JsonKey(name: 'chartType') required String chartType, + }) = _ChartConfigModel; + + factory ChartConfigModel.fromJson( + Map json, + ) => + _$ChartConfigModelFromJson(json); +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_config.freezed.dart b/packages/digit_dss/lib/models/entities/dashboard_config.freezed.dart new file mode 100644 index 000000000..ff8cb1285 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_config.freezed.dart @@ -0,0 +1,585 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'dashboard_config.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models'); + +DashboardConfigPrimaryWrapper _$DashboardConfigPrimaryWrapperFromJson( + Map json) { + return _DashboardConfigPrimaryWrapper.fromJson(json); +} + +/// @nodoc +mixin _$DashboardConfigPrimaryWrapper { + @JsonKey(name: 'dashboardConfig') + List get dashboardConfigWrapper => + throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DashboardConfigPrimaryWrapperCopyWith + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DashboardConfigPrimaryWrapperCopyWith<$Res> { + factory $DashboardConfigPrimaryWrapperCopyWith( + DashboardConfigPrimaryWrapper value, + $Res Function(DashboardConfigPrimaryWrapper) then) = + _$DashboardConfigPrimaryWrapperCopyWithImpl<$Res, + DashboardConfigPrimaryWrapper>; + @useResult + $Res call( + {@JsonKey(name: 'dashboardConfig') + List dashboardConfigWrapper}); +} + +/// @nodoc +class _$DashboardConfigPrimaryWrapperCopyWithImpl<$Res, + $Val extends DashboardConfigPrimaryWrapper> + implements $DashboardConfigPrimaryWrapperCopyWith<$Res> { + _$DashboardConfigPrimaryWrapperCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? dashboardConfigWrapper = null, + }) { + return _then(_value.copyWith( + dashboardConfigWrapper: null == dashboardConfigWrapper + ? _value.dashboardConfigWrapper + : dashboardConfigWrapper // ignore: cast_nullable_to_non_nullable + as List, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DashboardConfigPrimaryWrapperImplCopyWith<$Res> + implements $DashboardConfigPrimaryWrapperCopyWith<$Res> { + factory _$$DashboardConfigPrimaryWrapperImplCopyWith( + _$DashboardConfigPrimaryWrapperImpl value, + $Res Function(_$DashboardConfigPrimaryWrapperImpl) then) = + __$$DashboardConfigPrimaryWrapperImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: 'dashboardConfig') + List dashboardConfigWrapper}); +} + +/// @nodoc +class __$$DashboardConfigPrimaryWrapperImplCopyWithImpl<$Res> + extends _$DashboardConfigPrimaryWrapperCopyWithImpl<$Res, + _$DashboardConfigPrimaryWrapperImpl> + implements _$$DashboardConfigPrimaryWrapperImplCopyWith<$Res> { + __$$DashboardConfigPrimaryWrapperImplCopyWithImpl( + _$DashboardConfigPrimaryWrapperImpl _value, + $Res Function(_$DashboardConfigPrimaryWrapperImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? dashboardConfigWrapper = null, + }) { + return _then(_$DashboardConfigPrimaryWrapperImpl( + dashboardConfigWrapper: null == dashboardConfigWrapper + ? _value._dashboardConfigWrapper + : dashboardConfigWrapper // ignore: cast_nullable_to_non_nullable + as List, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DashboardConfigPrimaryWrapperImpl + implements _DashboardConfigPrimaryWrapper { + const _$DashboardConfigPrimaryWrapperImpl( + {@JsonKey(name: 'dashboardConfig') + final List dashboardConfigWrapper = const []}) + : _dashboardConfigWrapper = dashboardConfigWrapper; + + factory _$DashboardConfigPrimaryWrapperImpl.fromJson( + Map json) => + _$$DashboardConfigPrimaryWrapperImplFromJson(json); + + final List _dashboardConfigWrapper; + @override + @JsonKey(name: 'dashboardConfig') + List get dashboardConfigWrapper { + if (_dashboardConfigWrapper is EqualUnmodifiableListView) + return _dashboardConfigWrapper; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_dashboardConfigWrapper); + } + + @override + String toString() { + return 'DashboardConfigPrimaryWrapper(dashboardConfigWrapper: $dashboardConfigWrapper)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardConfigPrimaryWrapperImpl && + const DeepCollectionEquality().equals( + other._dashboardConfigWrapper, _dashboardConfigWrapper)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, + const DeepCollectionEquality().hash(_dashboardConfigWrapper)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DashboardConfigPrimaryWrapperImplCopyWith< + _$DashboardConfigPrimaryWrapperImpl> + get copyWith => __$$DashboardConfigPrimaryWrapperImplCopyWithImpl< + _$DashboardConfigPrimaryWrapperImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DashboardConfigPrimaryWrapperImplToJson( + this, + ); + } +} + +abstract class _DashboardConfigPrimaryWrapper + implements DashboardConfigPrimaryWrapper { + const factory _DashboardConfigPrimaryWrapper( + {@JsonKey(name: 'dashboardConfig') + final List dashboardConfigWrapper}) = + _$DashboardConfigPrimaryWrapperImpl; + + factory _DashboardConfigPrimaryWrapper.fromJson(Map json) = + _$DashboardConfigPrimaryWrapperImpl.fromJson; + + @override + @JsonKey(name: 'dashboardConfig') + List get dashboardConfigWrapper; + @override + @JsonKey(ignore: true) + _$$DashboardConfigPrimaryWrapperImplCopyWith< + _$DashboardConfigPrimaryWrapperImpl> + get copyWith => throw _privateConstructorUsedError; +} + +DashboardConfigWrapper _$DashboardConfigWrapperFromJson( + Map json) { + return _DashboardConfigWrapper.fromJson(json); +} + +/// @nodoc +mixin _$DashboardConfigWrapper { + @JsonKey(name: 'enableDashboard') + bool get enableDashboard => throw _privateConstructorUsedError; + @JsonKey(name: 'charts') + List? get charts => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $DashboardConfigWrapperCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $DashboardConfigWrapperCopyWith<$Res> { + factory $DashboardConfigWrapperCopyWith(DashboardConfigWrapper value, + $Res Function(DashboardConfigWrapper) then) = + _$DashboardConfigWrapperCopyWithImpl<$Res, DashboardConfigWrapper>; + @useResult + $Res call( + {@JsonKey(name: 'enableDashboard') bool enableDashboard, + @JsonKey(name: 'charts') List? charts}); +} + +/// @nodoc +class _$DashboardConfigWrapperCopyWithImpl<$Res, + $Val extends DashboardConfigWrapper> + implements $DashboardConfigWrapperCopyWith<$Res> { + _$DashboardConfigWrapperCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? enableDashboard = null, + Object? charts = freezed, + }) { + return _then(_value.copyWith( + enableDashboard: null == enableDashboard + ? _value.enableDashboard + : enableDashboard // ignore: cast_nullable_to_non_nullable + as bool, + charts: freezed == charts + ? _value.charts + : charts // ignore: cast_nullable_to_non_nullable + as List?, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$DashboardConfigWrapperImplCopyWith<$Res> + implements $DashboardConfigWrapperCopyWith<$Res> { + factory _$$DashboardConfigWrapperImplCopyWith( + _$DashboardConfigWrapperImpl value, + $Res Function(_$DashboardConfigWrapperImpl) then) = + __$$DashboardConfigWrapperImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: 'enableDashboard') bool enableDashboard, + @JsonKey(name: 'charts') List? charts}); +} + +/// @nodoc +class __$$DashboardConfigWrapperImplCopyWithImpl<$Res> + extends _$DashboardConfigWrapperCopyWithImpl<$Res, + _$DashboardConfigWrapperImpl> + implements _$$DashboardConfigWrapperImplCopyWith<$Res> { + __$$DashboardConfigWrapperImplCopyWithImpl( + _$DashboardConfigWrapperImpl _value, + $Res Function(_$DashboardConfigWrapperImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? enableDashboard = null, + Object? charts = freezed, + }) { + return _then(_$DashboardConfigWrapperImpl( + enableDashboard: null == enableDashboard + ? _value.enableDashboard + : enableDashboard // ignore: cast_nullable_to_non_nullable + as bool, + charts: freezed == charts + ? _value._charts + : charts // ignore: cast_nullable_to_non_nullable + as List?, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$DashboardConfigWrapperImpl implements _DashboardConfigWrapper { + const _$DashboardConfigWrapperImpl( + {@JsonKey(name: 'enableDashboard') required this.enableDashboard, + @JsonKey(name: 'charts') final List? charts}) + : _charts = charts; + + factory _$DashboardConfigWrapperImpl.fromJson(Map json) => + _$$DashboardConfigWrapperImplFromJson(json); + + @override + @JsonKey(name: 'enableDashboard') + final bool enableDashboard; + final List? _charts; + @override + @JsonKey(name: 'charts') + List? get charts { + final value = _charts; + if (value == null) return null; + if (_charts is EqualUnmodifiableListView) return _charts; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(value); + } + + @override + String toString() { + return 'DashboardConfigWrapper(enableDashboard: $enableDashboard, charts: $charts)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$DashboardConfigWrapperImpl && + (identical(other.enableDashboard, enableDashboard) || + other.enableDashboard == enableDashboard) && + const DeepCollectionEquality().equals(other._charts, _charts)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => Object.hash(runtimeType, enableDashboard, + const DeepCollectionEquality().hash(_charts)); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$DashboardConfigWrapperImplCopyWith<_$DashboardConfigWrapperImpl> + get copyWith => __$$DashboardConfigWrapperImplCopyWithImpl< + _$DashboardConfigWrapperImpl>(this, _$identity); + + @override + Map toJson() { + return _$$DashboardConfigWrapperImplToJson( + this, + ); + } +} + +abstract class _DashboardConfigWrapper implements DashboardConfigWrapper { + const factory _DashboardConfigWrapper( + {@JsonKey(name: 'enableDashboard') required final bool enableDashboard, + @JsonKey(name: 'charts') + final List? charts}) = _$DashboardConfigWrapperImpl; + + factory _DashboardConfigWrapper.fromJson(Map json) = + _$DashboardConfigWrapperImpl.fromJson; + + @override + @JsonKey(name: 'enableDashboard') + bool get enableDashboard; + @override + @JsonKey(name: 'charts') + List? get charts; + @override + @JsonKey(ignore: true) + _$$DashboardConfigWrapperImplCopyWith<_$DashboardConfigWrapperImpl> + get copyWith => throw _privateConstructorUsedError; +} + +ChartConfigModel _$ChartConfigModelFromJson(Map json) { + return _ChartConfigModel.fromJson(json); +} + +/// @nodoc +mixin _$ChartConfigModel { + @JsonKey(name: 'active') + bool get active => throw _privateConstructorUsedError; + @JsonKey(name: 'name') + String get name => throw _privateConstructorUsedError; + @JsonKey(name: 'vizType') + String? get vizType => throw _privateConstructorUsedError; + @JsonKey(name: 'chartType') + String get chartType => throw _privateConstructorUsedError; + + Map toJson() => throw _privateConstructorUsedError; + @JsonKey(ignore: true) + $ChartConfigModelCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $ChartConfigModelCopyWith<$Res> { + factory $ChartConfigModelCopyWith( + ChartConfigModel value, $Res Function(ChartConfigModel) then) = + _$ChartConfigModelCopyWithImpl<$Res, ChartConfigModel>; + @useResult + $Res call( + {@JsonKey(name: 'active') bool active, + @JsonKey(name: 'name') String name, + @JsonKey(name: 'vizType') String? vizType, + @JsonKey(name: 'chartType') String chartType}); +} + +/// @nodoc +class _$ChartConfigModelCopyWithImpl<$Res, $Val extends ChartConfigModel> + implements $ChartConfigModelCopyWith<$Res> { + _$ChartConfigModelCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? active = null, + Object? name = null, + Object? vizType = freezed, + Object? chartType = null, + }) { + return _then(_value.copyWith( + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + vizType: freezed == vizType + ? _value.vizType + : vizType // ignore: cast_nullable_to_non_nullable + as String?, + chartType: null == chartType + ? _value.chartType + : chartType // ignore: cast_nullable_to_non_nullable + as String, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$ChartConfigModelImplCopyWith<$Res> + implements $ChartConfigModelCopyWith<$Res> { + factory _$$ChartConfigModelImplCopyWith(_$ChartConfigModelImpl value, + $Res Function(_$ChartConfigModelImpl) then) = + __$$ChartConfigModelImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {@JsonKey(name: 'active') bool active, + @JsonKey(name: 'name') String name, + @JsonKey(name: 'vizType') String? vizType, + @JsonKey(name: 'chartType') String chartType}); +} + +/// @nodoc +class __$$ChartConfigModelImplCopyWithImpl<$Res> + extends _$ChartConfigModelCopyWithImpl<$Res, _$ChartConfigModelImpl> + implements _$$ChartConfigModelImplCopyWith<$Res> { + __$$ChartConfigModelImplCopyWithImpl(_$ChartConfigModelImpl _value, + $Res Function(_$ChartConfigModelImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? active = null, + Object? name = null, + Object? vizType = freezed, + Object? chartType = null, + }) { + return _then(_$ChartConfigModelImpl( + active: null == active + ? _value.active + : active // ignore: cast_nullable_to_non_nullable + as bool, + name: null == name + ? _value.name + : name // ignore: cast_nullable_to_non_nullable + as String, + vizType: freezed == vizType + ? _value.vizType + : vizType // ignore: cast_nullable_to_non_nullable + as String?, + chartType: null == chartType + ? _value.chartType + : chartType // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc +@JsonSerializable() +class _$ChartConfigModelImpl implements _ChartConfigModel { + const _$ChartConfigModelImpl( + {@JsonKey(name: 'active') required this.active, + @JsonKey(name: 'name') required this.name, + @JsonKey(name: 'vizType') this.vizType, + @JsonKey(name: 'chartType') required this.chartType}); + + factory _$ChartConfigModelImpl.fromJson(Map json) => + _$$ChartConfigModelImplFromJson(json); + + @override + @JsonKey(name: 'active') + final bool active; + @override + @JsonKey(name: 'name') + final String name; + @override + @JsonKey(name: 'vizType') + final String? vizType; + @override + @JsonKey(name: 'chartType') + final String chartType; + + @override + String toString() { + return 'ChartConfigModel(active: $active, name: $name, vizType: $vizType, chartType: $chartType)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$ChartConfigModelImpl && + (identical(other.active, active) || other.active == active) && + (identical(other.name, name) || other.name == name) && + (identical(other.vizType, vizType) || other.vizType == vizType) && + (identical(other.chartType, chartType) || + other.chartType == chartType)); + } + + @JsonKey(ignore: true) + @override + int get hashCode => + Object.hash(runtimeType, active, name, vizType, chartType); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$ChartConfigModelImplCopyWith<_$ChartConfigModelImpl> get copyWith => + __$$ChartConfigModelImplCopyWithImpl<_$ChartConfigModelImpl>( + this, _$identity); + + @override + Map toJson() { + return _$$ChartConfigModelImplToJson( + this, + ); + } +} + +abstract class _ChartConfigModel implements ChartConfigModel { + const factory _ChartConfigModel( + {@JsonKey(name: 'active') required final bool active, + @JsonKey(name: 'name') required final String name, + @JsonKey(name: 'vizType') final String? vizType, + @JsonKey(name: 'chartType') required final String chartType}) = + _$ChartConfigModelImpl; + + factory _ChartConfigModel.fromJson(Map json) = + _$ChartConfigModelImpl.fromJson; + + @override + @JsonKey(name: 'active') + bool get active; + @override + @JsonKey(name: 'name') + String get name; + @override + @JsonKey(name: 'vizType') + String? get vizType; + @override + @JsonKey(name: 'chartType') + String get chartType; + @override + @JsonKey(ignore: true) + _$$ChartConfigModelImplCopyWith<_$ChartConfigModelImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_config.g.dart b/packages/digit_dss/lib/models/entities/dashboard_config.g.dart new file mode 100644 index 000000000..6996d05b5 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_config.g.dart @@ -0,0 +1,57 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'dashboard_config.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$DashboardConfigPrimaryWrapperImpl + _$$DashboardConfigPrimaryWrapperImplFromJson(Map json) => + _$DashboardConfigPrimaryWrapperImpl( + dashboardConfigWrapper: (json['dashboardConfig'] as List?) + ?.map((e) => DashboardConfigWrapper.fromJson( + e as Map)) + .toList() ?? + const [], + ); + +Map _$$DashboardConfigPrimaryWrapperImplToJson( + _$DashboardConfigPrimaryWrapperImpl instance) => + { + 'dashboardConfig': instance.dashboardConfigWrapper, + }; + +_$DashboardConfigWrapperImpl _$$DashboardConfigWrapperImplFromJson( + Map json) => + _$DashboardConfigWrapperImpl( + enableDashboard: json['enableDashboard'] as bool, + charts: (json['charts'] as List?) + ?.map((e) => ChartConfigModel.fromJson(e as Map)) + .toList(), + ); + +Map _$$DashboardConfigWrapperImplToJson( + _$DashboardConfigWrapperImpl instance) => + { + 'enableDashboard': instance.enableDashboard, + 'charts': instance.charts, + }; + +_$ChartConfigModelImpl _$$ChartConfigModelImplFromJson( + Map json) => + _$ChartConfigModelImpl( + active: json['active'] as bool, + name: json['name'] as String, + vizType: json['vizType'] as String?, + chartType: json['chartType'] as String, + ); + +Map _$$ChartConfigModelImplToJson( + _$ChartConfigModelImpl instance) => + { + 'active': instance.active, + 'name': instance.name, + 'vizType': instance.vizType, + 'chartType': instance.chartType, + }; diff --git a/packages/digit_dss/lib/models/entities/dashboard_request.dart b/packages/digit_dss/lib/models/entities/dashboard_request.dart new file mode 100644 index 000000000..3c6a5589e --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_request.dart @@ -0,0 +1,56 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; + +part 'dashboard_request.mapper.dart'; + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DashboardRequestModel with DashboardRequestModelMappable { + final AggregationRequestDto aggregationRequestDto; + final DSSHeaders headers; + + DashboardRequestModel({ + required this.aggregationRequestDto, + required this.headers, + }) : super(); +} + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class AggregationRequestDto with AggregationRequestDtoMappable { + final String visualizationCode; + final String visualizationType; + final Map? filters; + final RequestDate? requestDate; + final String? moduleLevel; + final String? queryType; + + AggregationRequestDto({ + required this.visualizationCode, + required this.visualizationType, + this.filters, + this.requestDate, + this.moduleLevel, + this.queryType, + }) : super(); +} + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DSSHeaders with DSSHeadersMappable { + final String? tenantId; + DSSHeaders({ + this.tenantId, + }) : super(); +} + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class RequestDate with RequestDateMappable { + final int? startDate; + final int? endDate; + final String? title; + final String? interval; + RequestDate({ + this.startDate, + this.endDate, + this.title, + this.interval, + }) : super(); +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_request.mapper.dart b/packages/digit_dss/lib/models/entities/dashboard_request.mapper.dart new file mode 100644 index 000000000..078f5d311 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_request.mapper.dart @@ -0,0 +1,575 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'dashboard_request.dart'; + +class DashboardRequestModelMapper + extends ClassMapperBase { + DashboardRequestModelMapper._(); + + static DashboardRequestModelMapper? _instance; + static DashboardRequestModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = DashboardRequestModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'DashboardRequestModel'; + + static AggregationRequestDto _$aggregationRequestDto( + DashboardRequestModel v) => + v.aggregationRequestDto; + static const Field + _f$aggregationRequestDto = + Field('aggregationRequestDto', _$aggregationRequestDto); + static DSSHeaders _$headers(DashboardRequestModel v) => v.headers; + static const Field _f$headers = + Field('headers', _$headers); + + @override + final MappableFields fields = const { + #aggregationRequestDto: _f$aggregationRequestDto, + #headers: _f$headers, + }; + @override + final bool ignoreNull = true; + + static DashboardRequestModel _instantiate(DecodingData data) { + return DashboardRequestModel( + aggregationRequestDto: data.dec(_f$aggregationRequestDto), + headers: data.dec(_f$headers)); + } + + @override + final Function instantiate = _instantiate; + + static DashboardRequestModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DashboardRequestModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DashboardRequestModelMappable { + String toJson() { + return DashboardRequestModelMapper.ensureInitialized() + .encodeJson(this as DashboardRequestModel); + } + + Map toMap() { + return DashboardRequestModelMapper.ensureInitialized() + .encodeMap(this as DashboardRequestModel); + } + + DashboardRequestModelCopyWith + get copyWith => _DashboardRequestModelCopyWithImpl( + this as DashboardRequestModel, $identity, $identity); + @override + String toString() { + return DashboardRequestModelMapper.ensureInitialized() + .stringifyValue(this as DashboardRequestModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DashboardRequestModelMapper.ensureInitialized() + .isValueEqual(this as DashboardRequestModel, other)); + } + + @override + int get hashCode { + return DashboardRequestModelMapper.ensureInitialized() + .hashValue(this as DashboardRequestModel); + } +} + +extension DashboardRequestModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, DashboardRequestModel, $Out> { + DashboardRequestModelCopyWith<$R, DashboardRequestModel, $Out> + get $asDashboardRequestModel => + $base.as((v, t, t2) => _DashboardRequestModelCopyWithImpl(v, t, t2)); +} + +abstract class DashboardRequestModelCopyWith< + $R, + $In extends DashboardRequestModel, + $Out> implements ClassCopyWith<$R, $In, $Out> { + AggregationRequestDtoCopyWith<$R, AggregationRequestDto, + AggregationRequestDto> get aggregationRequestDto; + DSSHeadersCopyWith<$R, DSSHeaders, DSSHeaders> get headers; + $R call({AggregationRequestDto? aggregationRequestDto, DSSHeaders? headers}); + DashboardRequestModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _DashboardRequestModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DashboardRequestModel, $Out> + implements DashboardRequestModelCopyWith<$R, DashboardRequestModel, $Out> { + _DashboardRequestModelCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DashboardRequestModelMapper.ensureInitialized(); + @override + AggregationRequestDtoCopyWith<$R, AggregationRequestDto, + AggregationRequestDto> + get aggregationRequestDto => $value.aggregationRequestDto.copyWith + .$chain((v) => call(aggregationRequestDto: v)); + @override + DSSHeadersCopyWith<$R, DSSHeaders, DSSHeaders> get headers => + $value.headers.copyWith.$chain((v) => call(headers: v)); + @override + $R call( + {AggregationRequestDto? aggregationRequestDto, + DSSHeaders? headers}) => + $apply(FieldCopyWithData({ + if (aggregationRequestDto != null) + #aggregationRequestDto: aggregationRequestDto, + if (headers != null) #headers: headers + })); + @override + DashboardRequestModel $make(CopyWithData data) => DashboardRequestModel( + aggregationRequestDto: + data.get(#aggregationRequestDto, or: $value.aggregationRequestDto), + headers: data.get(#headers, or: $value.headers)); + + @override + DashboardRequestModelCopyWith<$R2, DashboardRequestModel, $Out2> + $chain<$R2, $Out2>(Then<$Out2, $R2> t) => + _DashboardRequestModelCopyWithImpl($value, $cast, t); +} + +class AggregationRequestDtoMapper + extends ClassMapperBase { + AggregationRequestDtoMapper._(); + + static AggregationRequestDtoMapper? _instance; + static AggregationRequestDtoMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = AggregationRequestDtoMapper._()); + } + return _instance!; + } + + @override + final String id = 'AggregationRequestDto'; + + static String _$visualizationCode(AggregationRequestDto v) => + v.visualizationCode; + static const Field _f$visualizationCode = + Field('visualizationCode', _$visualizationCode); + static String _$visualizationType(AggregationRequestDto v) => + v.visualizationType; + static const Field _f$visualizationType = + Field('visualizationType', _$visualizationType); + static Map? _$filters(AggregationRequestDto v) => v.filters; + static const Field> _f$filters = + Field('filters', _$filters, opt: true); + static RequestDate? _$requestDate(AggregationRequestDto v) => v.requestDate; + static const Field _f$requestDate = + Field('requestDate', _$requestDate, opt: true); + static String? _$moduleLevel(AggregationRequestDto v) => v.moduleLevel; + static const Field _f$moduleLevel = + Field('moduleLevel', _$moduleLevel, opt: true); + static String? _$queryType(AggregationRequestDto v) => v.queryType; + static const Field _f$queryType = + Field('queryType', _$queryType, opt: true); + + @override + final MappableFields fields = const { + #visualizationCode: _f$visualizationCode, + #visualizationType: _f$visualizationType, + #filters: _f$filters, + #requestDate: _f$requestDate, + #moduleLevel: _f$moduleLevel, + #queryType: _f$queryType, + }; + @override + final bool ignoreNull = true; + + static AggregationRequestDto _instantiate(DecodingData data) { + return AggregationRequestDto( + visualizationCode: data.dec(_f$visualizationCode), + visualizationType: data.dec(_f$visualizationType), + filters: data.dec(_f$filters), + requestDate: data.dec(_f$requestDate), + moduleLevel: data.dec(_f$moduleLevel), + queryType: data.dec(_f$queryType)); + } + + @override + final Function instantiate = _instantiate; + + static AggregationRequestDto fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static AggregationRequestDto fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin AggregationRequestDtoMappable { + String toJson() { + return AggregationRequestDtoMapper.ensureInitialized() + .encodeJson(this as AggregationRequestDto); + } + + Map toMap() { + return AggregationRequestDtoMapper.ensureInitialized() + .encodeMap(this as AggregationRequestDto); + } + + AggregationRequestDtoCopyWith + get copyWith => _AggregationRequestDtoCopyWithImpl( + this as AggregationRequestDto, $identity, $identity); + @override + String toString() { + return AggregationRequestDtoMapper.ensureInitialized() + .stringifyValue(this as AggregationRequestDto); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + AggregationRequestDtoMapper.ensureInitialized() + .isValueEqual(this as AggregationRequestDto, other)); + } + + @override + int get hashCode { + return AggregationRequestDtoMapper.ensureInitialized() + .hashValue(this as AggregationRequestDto); + } +} + +extension AggregationRequestDtoValueCopy<$R, $Out> + on ObjectCopyWith<$R, AggregationRequestDto, $Out> { + AggregationRequestDtoCopyWith<$R, AggregationRequestDto, $Out> + get $asAggregationRequestDto => + $base.as((v, t, t2) => _AggregationRequestDtoCopyWithImpl(v, t, t2)); +} + +abstract class AggregationRequestDtoCopyWith< + $R, + $In extends AggregationRequestDto, + $Out> implements ClassCopyWith<$R, $In, $Out> { + MapCopyWith<$R, dynamic, dynamic, ObjectCopyWith<$R, dynamic, dynamic>>? + get filters; + RequestDateCopyWith<$R, RequestDate, RequestDate>? get requestDate; + $R call( + {String? visualizationCode, + String? visualizationType, + Map? filters, + RequestDate? requestDate, + String? moduleLevel, + String? queryType}); + AggregationRequestDtoCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _AggregationRequestDtoCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, AggregationRequestDto, $Out> + implements AggregationRequestDtoCopyWith<$R, AggregationRequestDto, $Out> { + _AggregationRequestDtoCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + AggregationRequestDtoMapper.ensureInitialized(); + @override + MapCopyWith<$R, dynamic, dynamic, ObjectCopyWith<$R, dynamic, dynamic>>? + get filters => $value.filters != null + ? MapCopyWith( + $value.filters!, + (v, t) => ObjectCopyWith(v, $identity, t), + (v) => call(filters: v)) + : null; + @override + RequestDateCopyWith<$R, RequestDate, RequestDate>? get requestDate => + $value.requestDate?.copyWith.$chain((v) => call(requestDate: v)); + @override + $R call( + {String? visualizationCode, + String? visualizationType, + Object? filters = $none, + Object? requestDate = $none, + Object? moduleLevel = $none, + Object? queryType = $none}) => + $apply(FieldCopyWithData({ + if (visualizationCode != null) #visualizationCode: visualizationCode, + if (visualizationType != null) #visualizationType: visualizationType, + if (filters != $none) #filters: filters, + if (requestDate != $none) #requestDate: requestDate, + if (moduleLevel != $none) #moduleLevel: moduleLevel, + if (queryType != $none) #queryType: queryType + })); + @override + AggregationRequestDto $make(CopyWithData data) => AggregationRequestDto( + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode), + visualizationType: + data.get(#visualizationType, or: $value.visualizationType), + filters: data.get(#filters, or: $value.filters), + requestDate: data.get(#requestDate, or: $value.requestDate), + moduleLevel: data.get(#moduleLevel, or: $value.moduleLevel), + queryType: data.get(#queryType, or: $value.queryType)); + + @override + AggregationRequestDtoCopyWith<$R2, AggregationRequestDto, $Out2> + $chain<$R2, $Out2>(Then<$Out2, $R2> t) => + _AggregationRequestDtoCopyWithImpl($value, $cast, t); +} + +class RequestDateMapper extends ClassMapperBase { + RequestDateMapper._(); + + static RequestDateMapper? _instance; + static RequestDateMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = RequestDateMapper._()); + } + return _instance!; + } + + @override + final String id = 'RequestDate'; + + static int? _$startDate(RequestDate v) => v.startDate; + static const Field _f$startDate = + Field('startDate', _$startDate, opt: true); + static int? _$endDate(RequestDate v) => v.endDate; + static const Field _f$endDate = + Field('endDate', _$endDate, opt: true); + static String? _$title(RequestDate v) => v.title; + static const Field _f$title = + Field('title', _$title, opt: true); + static String? _$interval(RequestDate v) => v.interval; + static const Field _f$interval = + Field('interval', _$interval, opt: true); + + @override + final MappableFields fields = const { + #startDate: _f$startDate, + #endDate: _f$endDate, + #title: _f$title, + #interval: _f$interval, + }; + @override + final bool ignoreNull = true; + + static RequestDate _instantiate(DecodingData data) { + return RequestDate( + startDate: data.dec(_f$startDate), + endDate: data.dec(_f$endDate), + title: data.dec(_f$title), + interval: data.dec(_f$interval)); + } + + @override + final Function instantiate = _instantiate; + + static RequestDate fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static RequestDate fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin RequestDateMappable { + String toJson() { + return RequestDateMapper.ensureInitialized() + .encodeJson(this as RequestDate); + } + + Map toMap() { + return RequestDateMapper.ensureInitialized() + .encodeMap(this as RequestDate); + } + + RequestDateCopyWith get copyWith => + _RequestDateCopyWithImpl(this as RequestDate, $identity, $identity); + @override + String toString() { + return RequestDateMapper.ensureInitialized() + .stringifyValue(this as RequestDate); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + RequestDateMapper.ensureInitialized() + .isValueEqual(this as RequestDate, other)); + } + + @override + int get hashCode { + return RequestDateMapper.ensureInitialized().hashValue(this as RequestDate); + } +} + +extension RequestDateValueCopy<$R, $Out> + on ObjectCopyWith<$R, RequestDate, $Out> { + RequestDateCopyWith<$R, RequestDate, $Out> get $asRequestDate => + $base.as((v, t, t2) => _RequestDateCopyWithImpl(v, t, t2)); +} + +abstract class RequestDateCopyWith<$R, $In extends RequestDate, $Out> + implements ClassCopyWith<$R, $In, $Out> { + $R call({int? startDate, int? endDate, String? title, String? interval}); + RequestDateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t); +} + +class _RequestDateCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, RequestDate, $Out> + implements RequestDateCopyWith<$R, RequestDate, $Out> { + _RequestDateCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + RequestDateMapper.ensureInitialized(); + @override + $R call( + {Object? startDate = $none, + Object? endDate = $none, + Object? title = $none, + Object? interval = $none}) => + $apply(FieldCopyWithData({ + if (startDate != $none) #startDate: startDate, + if (endDate != $none) #endDate: endDate, + if (title != $none) #title: title, + if (interval != $none) #interval: interval + })); + @override + RequestDate $make(CopyWithData data) => RequestDate( + startDate: data.get(#startDate, or: $value.startDate), + endDate: data.get(#endDate, or: $value.endDate), + title: data.get(#title, or: $value.title), + interval: data.get(#interval, or: $value.interval)); + + @override + RequestDateCopyWith<$R2, RequestDate, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t) => + _RequestDateCopyWithImpl($value, $cast, t); +} + +class DSSHeadersMapper extends ClassMapperBase { + DSSHeadersMapper._(); + + static DSSHeadersMapper? _instance; + static DSSHeadersMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = DSSHeadersMapper._()); + } + return _instance!; + } + + @override + final String id = 'DSSHeaders'; + + static String? _$tenantId(DSSHeaders v) => v.tenantId; + static const Field _f$tenantId = + Field('tenantId', _$tenantId, opt: true); + + @override + final MappableFields fields = const { + #tenantId: _f$tenantId, + }; + @override + final bool ignoreNull = true; + + static DSSHeaders _instantiate(DecodingData data) { + return DSSHeaders(tenantId: data.dec(_f$tenantId)); + } + + @override + final Function instantiate = _instantiate; + + static DSSHeaders fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DSSHeaders fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DSSHeadersMappable { + String toJson() { + return DSSHeadersMapper.ensureInitialized() + .encodeJson(this as DSSHeaders); + } + + Map toMap() { + return DSSHeadersMapper.ensureInitialized() + .encodeMap(this as DSSHeaders); + } + + DSSHeadersCopyWith get copyWith => + _DSSHeadersCopyWithImpl(this as DSSHeaders, $identity, $identity); + @override + String toString() { + return DSSHeadersMapper.ensureInitialized() + .stringifyValue(this as DSSHeaders); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DSSHeadersMapper.ensureInitialized() + .isValueEqual(this as DSSHeaders, other)); + } + + @override + int get hashCode { + return DSSHeadersMapper.ensureInitialized().hashValue(this as DSSHeaders); + } +} + +extension DSSHeadersValueCopy<$R, $Out> + on ObjectCopyWith<$R, DSSHeaders, $Out> { + DSSHeadersCopyWith<$R, DSSHeaders, $Out> get $asDSSHeaders => + $base.as((v, t, t2) => _DSSHeadersCopyWithImpl(v, t, t2)); +} + +abstract class DSSHeadersCopyWith<$R, $In extends DSSHeaders, $Out> + implements ClassCopyWith<$R, $In, $Out> { + $R call({String? tenantId}); + DSSHeadersCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t); +} + +class _DSSHeadersCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DSSHeaders, $Out> + implements DSSHeadersCopyWith<$R, DSSHeaders, $Out> { + _DSSHeadersCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DSSHeadersMapper.ensureInitialized(); + @override + $R call({Object? tenantId = $none}) => + $apply(FieldCopyWithData({if (tenantId != $none) #tenantId: tenantId})); + @override + DSSHeaders $make(CopyWithData data) => + DSSHeaders(tenantId: data.get(#tenantId, or: $value.tenantId)); + + @override + DSSHeadersCopyWith<$R2, DSSHeaders, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t) => + _DSSHeadersCopyWithImpl($value, $cast, t); +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_response_model.dart b/packages/digit_dss/lib/models/entities/dashboard_response_model.dart new file mode 100644 index 000000000..046d0439f --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_response_model.dart @@ -0,0 +1,44 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; +import 'package:digit_dss/models/entities/chart_data.dart'; + +part 'dashboard_response_model.mapper.dart'; + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DashboardResponseSearchModel with DashboardResponseSearchModelMappable { + final String? projectId; + final String? visualizationCode; + final String? chartType; + final String? date; + DashboardResponseSearchModel({ + this.projectId, + this.visualizationCode, + this.chartType, + this.date, + }) : super(); +} + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DashboardResponseModel with DashboardResponseModelMappable { + static const schemaName = 'Dashboard'; + + final String? drillDownChartId; + final bool? showLabel; + final bool? hideInsights; + final List? data; + final bool? hideHeaderDenomination; + final String? visualizationCode; + final String? chartType; + final String? projectId; + + DashboardResponseModel({ + this.drillDownChartId, + this.showLabel, + this.hideInsights, + this.hideHeaderDenomination, + this.projectId, + this.chartType, + this.visualizationCode, + this.data, + }) : super(); +} diff --git a/packages/digit_dss/lib/models/entities/dashboard_response_model.mapper.dart b/packages/digit_dss/lib/models/entities/dashboard_response_model.mapper.dart new file mode 100644 index 000000000..3d5f63a52 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dashboard_response_model.mapper.dart @@ -0,0 +1,370 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'dashboard_response_model.dart'; + +class DashboardResponseSearchModelMapper + extends ClassMapperBase { + DashboardResponseSearchModelMapper._(); + + static DashboardResponseSearchModelMapper? _instance; + static DashboardResponseSearchModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals + .use(_instance = DashboardResponseSearchModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'DashboardResponseSearchModel'; + + static String? _$projectId(DashboardResponseSearchModel v) => v.projectId; + static const Field _f$projectId = + Field('projectId', _$projectId, opt: true); + static String? _$visualizationCode(DashboardResponseSearchModel v) => + v.visualizationCode; + static const Field + _f$visualizationCode = + Field('visualizationCode', _$visualizationCode, opt: true); + static String? _$chartType(DashboardResponseSearchModel v) => v.chartType; + static const Field _f$chartType = + Field('chartType', _$chartType, opt: true); + static String? _$date(DashboardResponseSearchModel v) => v.date; + static const Field _f$date = + Field('date', _$date, opt: true); + + @override + final MappableFields fields = const { + #projectId: _f$projectId, + #visualizationCode: _f$visualizationCode, + #chartType: _f$chartType, + #date: _f$date, + }; + @override + final bool ignoreNull = true; + + static DashboardResponseSearchModel _instantiate(DecodingData data) { + return DashboardResponseSearchModel( + projectId: data.dec(_f$projectId), + visualizationCode: data.dec(_f$visualizationCode), + chartType: data.dec(_f$chartType), + date: data.dec(_f$date)); + } + + @override + final Function instantiate = _instantiate; + + static DashboardResponseSearchModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DashboardResponseSearchModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DashboardResponseSearchModelMappable { + String toJson() { + return DashboardResponseSearchModelMapper.ensureInitialized() + .encodeJson( + this as DashboardResponseSearchModel); + } + + Map toMap() { + return DashboardResponseSearchModelMapper.ensureInitialized() + .encodeMap( + this as DashboardResponseSearchModel); + } + + DashboardResponseSearchModelCopyWith + get copyWith => _DashboardResponseSearchModelCopyWithImpl( + this as DashboardResponseSearchModel, $identity, $identity); + @override + String toString() { + return DashboardResponseSearchModelMapper.ensureInitialized() + .stringifyValue(this as DashboardResponseSearchModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DashboardResponseSearchModelMapper.ensureInitialized() + .isValueEqual(this as DashboardResponseSearchModel, other)); + } + + @override + int get hashCode { + return DashboardResponseSearchModelMapper.ensureInitialized() + .hashValue(this as DashboardResponseSearchModel); + } +} + +extension DashboardResponseSearchModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, DashboardResponseSearchModel, $Out> { + DashboardResponseSearchModelCopyWith<$R, DashboardResponseSearchModel, $Out> + get $asDashboardResponseSearchModel => $base.as( + (v, t, t2) => _DashboardResponseSearchModelCopyWithImpl(v, t, t2)); +} + +abstract class DashboardResponseSearchModelCopyWith< + $R, + $In extends DashboardResponseSearchModel, + $Out> implements ClassCopyWith<$R, $In, $Out> { + $R call( + {String? projectId, + String? visualizationCode, + String? chartType, + String? date}); + DashboardResponseSearchModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _DashboardResponseSearchModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DashboardResponseSearchModel, $Out> + implements + DashboardResponseSearchModelCopyWith<$R, DashboardResponseSearchModel, + $Out> { + _DashboardResponseSearchModelCopyWithImpl( + super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DashboardResponseSearchModelMapper.ensureInitialized(); + @override + $R call( + {Object? projectId = $none, + Object? visualizationCode = $none, + Object? chartType = $none, + Object? date = $none}) => + $apply(FieldCopyWithData({ + if (projectId != $none) #projectId: projectId, + if (visualizationCode != $none) #visualizationCode: visualizationCode, + if (chartType != $none) #chartType: chartType, + if (date != $none) #date: date + })); + @override + DashboardResponseSearchModel $make(CopyWithData data) => + DashboardResponseSearchModel( + projectId: data.get(#projectId, or: $value.projectId), + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode), + chartType: data.get(#chartType, or: $value.chartType), + date: data.get(#date, or: $value.date)); + + @override + DashboardResponseSearchModelCopyWith<$R2, DashboardResponseSearchModel, $Out2> + $chain<$R2, $Out2>(Then<$Out2, $R2> t) => + _DashboardResponseSearchModelCopyWithImpl($value, $cast, t); +} + +class DashboardResponseModelMapper + extends ClassMapperBase { + DashboardResponseModelMapper._(); + + static DashboardResponseModelMapper? _instance; + static DashboardResponseModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = DashboardResponseModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'DashboardResponseModel'; + + static String? _$drillDownChartId(DashboardResponseModel v) => + v.drillDownChartId; + static const Field _f$drillDownChartId = + Field('drillDownChartId', _$drillDownChartId, opt: true); + static bool? _$showLabel(DashboardResponseModel v) => v.showLabel; + static const Field _f$showLabel = + Field('showLabel', _$showLabel, opt: true); + static bool? _$hideInsights(DashboardResponseModel v) => v.hideInsights; + static const Field _f$hideInsights = + Field('hideInsights', _$hideInsights, opt: true); + static bool? _$hideHeaderDenomination(DashboardResponseModel v) => + v.hideHeaderDenomination; + static const Field _f$hideHeaderDenomination = + Field('hideHeaderDenomination', _$hideHeaderDenomination, opt: true); + static String? _$projectId(DashboardResponseModel v) => v.projectId; + static const Field _f$projectId = + Field('projectId', _$projectId, opt: true); + static String? _$chartType(DashboardResponseModel v) => v.chartType; + static const Field _f$chartType = + Field('chartType', _$chartType, opt: true); + static String? _$visualizationCode(DashboardResponseModel v) => + v.visualizationCode; + static const Field _f$visualizationCode = + Field('visualizationCode', _$visualizationCode, opt: true); + static List? _$data(DashboardResponseModel v) => + v.data; + static const Field> + _f$data = Field('data', _$data, opt: true); + + @override + final MappableFields fields = const { + #drillDownChartId: _f$drillDownChartId, + #showLabel: _f$showLabel, + #hideInsights: _f$hideInsights, + #hideHeaderDenomination: _f$hideHeaderDenomination, + #projectId: _f$projectId, + #chartType: _f$chartType, + #visualizationCode: _f$visualizationCode, + #data: _f$data, + }; + @override + final bool ignoreNull = true; + + static DashboardResponseModel _instantiate(DecodingData data) { + return DashboardResponseModel( + drillDownChartId: data.dec(_f$drillDownChartId), + showLabel: data.dec(_f$showLabel), + hideInsights: data.dec(_f$hideInsights), + hideHeaderDenomination: data.dec(_f$hideHeaderDenomination), + projectId: data.dec(_f$projectId), + chartType: data.dec(_f$chartType), + visualizationCode: data.dec(_f$visualizationCode), + data: data.dec(_f$data)); + } + + @override + final Function instantiate = _instantiate; + + static DashboardResponseModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DashboardResponseModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DashboardResponseModelMappable { + String toJson() { + return DashboardResponseModelMapper.ensureInitialized() + .encodeJson(this as DashboardResponseModel); + } + + Map toMap() { + return DashboardResponseModelMapper.ensureInitialized() + .encodeMap(this as DashboardResponseModel); + } + + DashboardResponseModelCopyWith + get copyWith => _DashboardResponseModelCopyWithImpl( + this as DashboardResponseModel, $identity, $identity); + @override + String toString() { + return DashboardResponseModelMapper.ensureInitialized() + .stringifyValue(this as DashboardResponseModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DashboardResponseModelMapper.ensureInitialized() + .isValueEqual(this as DashboardResponseModel, other)); + } + + @override + int get hashCode { + return DashboardResponseModelMapper.ensureInitialized() + .hashValue(this as DashboardResponseModel); + } +} + +extension DashboardResponseModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, DashboardResponseModel, $Out> { + DashboardResponseModelCopyWith<$R, DashboardResponseModel, $Out> + get $asDashboardResponseModel => + $base.as((v, t, t2) => _DashboardResponseModelCopyWithImpl(v, t, t2)); +} + +abstract class DashboardResponseModelCopyWith< + $R, + $In extends DashboardResponseModel, + $Out> implements ClassCopyWith<$R, $In, $Out> { + ListCopyWith< + $R, + DashboardChartDataModel, + DashboardChartDataModelCopyWith<$R, DashboardChartDataModel, + DashboardChartDataModel>>? get data; + $R call( + {String? drillDownChartId, + bool? showLabel, + bool? hideInsights, + bool? hideHeaderDenomination, + String? projectId, + String? chartType, + String? visualizationCode, + List? data}); + DashboardResponseModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _DashboardResponseModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DashboardResponseModel, $Out> + implements + DashboardResponseModelCopyWith<$R, DashboardResponseModel, $Out> { + _DashboardResponseModelCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DashboardResponseModelMapper.ensureInitialized(); + @override + ListCopyWith< + $R, + DashboardChartDataModel, + DashboardChartDataModelCopyWith<$R, DashboardChartDataModel, + DashboardChartDataModel>>? get data => $value.data != null + ? ListCopyWith( + $value.data!, (v, t) => v.copyWith.$chain(t), (v) => call(data: v)) + : null; + @override + $R call( + {Object? drillDownChartId = $none, + Object? showLabel = $none, + Object? hideInsights = $none, + Object? hideHeaderDenomination = $none, + Object? projectId = $none, + Object? chartType = $none, + Object? visualizationCode = $none, + Object? data = $none}) => + $apply(FieldCopyWithData({ + if (drillDownChartId != $none) #drillDownChartId: drillDownChartId, + if (showLabel != $none) #showLabel: showLabel, + if (hideInsights != $none) #hideInsights: hideInsights, + if (hideHeaderDenomination != $none) + #hideHeaderDenomination: hideHeaderDenomination, + if (projectId != $none) #projectId: projectId, + if (chartType != $none) #chartType: chartType, + if (visualizationCode != $none) #visualizationCode: visualizationCode, + if (data != $none) #data: data + })); + @override + DashboardResponseModel $make(CopyWithData data) => DashboardResponseModel( + drillDownChartId: + data.get(#drillDownChartId, or: $value.drillDownChartId), + showLabel: data.get(#showLabel, or: $value.showLabel), + hideInsights: data.get(#hideInsights, or: $value.hideInsights), + hideHeaderDenomination: + data.get(#hideHeaderDenomination, or: $value.hideHeaderDenomination), + projectId: data.get(#projectId, or: $value.projectId), + chartType: data.get(#chartType, or: $value.chartType), + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode), + data: data.get(#data, or: $value.data)); + + @override + DashboardResponseModelCopyWith<$R2, DashboardResponseModel, $Out2> + $chain<$R2, $Out2>(Then<$Out2, $R2> t) => + _DashboardResponseModelCopyWithImpl($value, $cast, t); +} diff --git a/packages/digit_dss/lib/models/entities/dss_enums.dart b/packages/digit_dss/lib/models/entities/dss_enums.dart new file mode 100644 index 000000000..cf03db3eb --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dss_enums.dart @@ -0,0 +1,36 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; + +part 'dss_enums.mapper.dart'; + +@MappableEnum(caseStyle: CaseStyle.upperCase) +enum DSSEnums { + @MappableValue("metric") + metric, + @MappableValue("xtable") + table, + @MappableValue("S.N.") + serialNumber, + @MappableValue("startDate") + startDate, + @MappableValue("endDate") + endDate, + @MappableValue("number") + number, + @MappableValue("percentage") + percentage, + @MappableValue("responseData") + responseData, + @MappableValue("day") + day, + @MappableValue("home") + home, + @MappableValue("row") + row, + @MappableValue("uuid") + uuid, + @MappableValue("projectId") + projectId, + @MappableValue("Lastsyncedtime") + lastSyncedTime, +} diff --git a/packages/digit_dss/lib/models/entities/dss_enums.mapper.dart b/packages/digit_dss/lib/models/entities/dss_enums.mapper.dart new file mode 100644 index 000000000..8844c362f --- /dev/null +++ b/packages/digit_dss/lib/models/entities/dss_enums.mapper.dart @@ -0,0 +1,101 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'dss_enums.dart'; + +class DSSEnumsMapper extends EnumMapper { + DSSEnumsMapper._(); + + static DSSEnumsMapper? _instance; + static DSSEnumsMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = DSSEnumsMapper._()); + } + return _instance!; + } + + static DSSEnums fromValue(dynamic value) { + ensureInitialized(); + return MapperContainer.globals.fromValue(value); + } + + @override + DSSEnums decode(dynamic value) { + switch (value) { + case "metric": + return DSSEnums.metric; + case "xtable": + return DSSEnums.table; + case "S.N.": + return DSSEnums.serialNumber; + case "startDate": + return DSSEnums.startDate; + case "endDate": + return DSSEnums.endDate; + case "number": + return DSSEnums.number; + case "percentage": + return DSSEnums.percentage; + case "responseData": + return DSSEnums.responseData; + case "day": + return DSSEnums.day; + case "home": + return DSSEnums.home; + case "row": + return DSSEnums.row; + case "uuid": + return DSSEnums.uuid; + case "projectId": + return DSSEnums.projectId; + case "Lastsyncedtime": + return DSSEnums.lastSyncedTime; + default: + throw MapperException.unknownEnumValue(value); + } + } + + @override + dynamic encode(DSSEnums self) { + switch (self) { + case DSSEnums.metric: + return "metric"; + case DSSEnums.table: + return "xtable"; + case DSSEnums.serialNumber: + return "S.N."; + case DSSEnums.startDate: + return "startDate"; + case DSSEnums.endDate: + return "endDate"; + case DSSEnums.number: + return "number"; + case DSSEnums.percentage: + return "percentage"; + case DSSEnums.responseData: + return "responseData"; + case DSSEnums.day: + return "day"; + case DSSEnums.home: + return "home"; + case DSSEnums.row: + return "row"; + case DSSEnums.uuid: + return "uuid"; + case DSSEnums.projectId: + return "projectId"; + case DSSEnums.lastSyncedTime: + return "Lastsyncedtime"; + } + } +} + +extension DSSEnumsMapperExtension on DSSEnums { + dynamic toValue() { + DSSEnumsMapper.ensureInitialized(); + return MapperContainer.globals.toValue(this); + } +} diff --git a/packages/digit_dss/lib/models/entities/insight.dart b/packages/digit_dss/lib/models/entities/insight.dart new file mode 100644 index 000000000..763711b0d --- /dev/null +++ b/packages/digit_dss/lib/models/entities/insight.dart @@ -0,0 +1,26 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; +import 'package:digit_data_model/data_model.dart'; + +part 'insight.mapper.dart'; + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class InsightModel with InsightModelMappable { + final String? colorCode; + final String? indicator; + final String? name; + final String? value; + final String? visualizationCode; + final String? chartType; + final String? projectId; + + InsightModel({ + this.colorCode, + this.indicator, + this.name, + this.value, + this.chartType, + this.visualizationCode, + this.projectId, + }) : super(); +} diff --git a/packages/digit_dss/lib/models/entities/insight.mapper.dart b/packages/digit_dss/lib/models/entities/insight.mapper.dart new file mode 100644 index 000000000..a260a0986 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/insight.mapper.dart @@ -0,0 +1,175 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'insight.dart'; + +class InsightModelMapper extends ClassMapperBase { + InsightModelMapper._(); + + static InsightModelMapper? _instance; + static InsightModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = InsightModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'InsightModel'; + + static String? _$colorCode(InsightModel v) => v.colorCode; + static const Field _f$colorCode = + Field('colorCode', _$colorCode, opt: true); + static String? _$indicator(InsightModel v) => v.indicator; + static const Field _f$indicator = + Field('indicator', _$indicator, opt: true); + static String? _$name(InsightModel v) => v.name; + static const Field _f$name = + Field('name', _$name, opt: true); + static String? _$value(InsightModel v) => v.value; + static const Field _f$value = + Field('value', _$value, opt: true); + static String? _$chartType(InsightModel v) => v.chartType; + static const Field _f$chartType = + Field('chartType', _$chartType, opt: true); + static String? _$visualizationCode(InsightModel v) => v.visualizationCode; + static const Field _f$visualizationCode = + Field('visualizationCode', _$visualizationCode, opt: true); + static String? _$projectId(InsightModel v) => v.projectId; + static const Field _f$projectId = + Field('projectId', _$projectId, opt: true); + + @override + final MappableFields fields = const { + #colorCode: _f$colorCode, + #indicator: _f$indicator, + #name: _f$name, + #value: _f$value, + #chartType: _f$chartType, + #visualizationCode: _f$visualizationCode, + #projectId: _f$projectId, + }; + @override + final bool ignoreNull = true; + + static InsightModel _instantiate(DecodingData data) { + return InsightModel( + colorCode: data.dec(_f$colorCode), + indicator: data.dec(_f$indicator), + name: data.dec(_f$name), + value: data.dec(_f$value), + chartType: data.dec(_f$chartType), + visualizationCode: data.dec(_f$visualizationCode), + projectId: data.dec(_f$projectId)); + } + + @override + final Function instantiate = _instantiate; + + static InsightModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static InsightModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin InsightModelMappable { + String toJson() { + return InsightModelMapper.ensureInitialized() + .encodeJson(this as InsightModel); + } + + Map toMap() { + return InsightModelMapper.ensureInitialized() + .encodeMap(this as InsightModel); + } + + InsightModelCopyWith get copyWith => + _InsightModelCopyWithImpl(this as InsightModel, $identity, $identity); + @override + String toString() { + return InsightModelMapper.ensureInitialized() + .stringifyValue(this as InsightModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + InsightModelMapper.ensureInitialized() + .isValueEqual(this as InsightModel, other)); + } + + @override + int get hashCode { + return InsightModelMapper.ensureInitialized() + .hashValue(this as InsightModel); + } +} + +extension InsightModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, InsightModel, $Out> { + InsightModelCopyWith<$R, InsightModel, $Out> get $asInsightModel => + $base.as((v, t, t2) => _InsightModelCopyWithImpl(v, t, t2)); +} + +abstract class InsightModelCopyWith<$R, $In extends InsightModel, $Out> + implements ClassCopyWith<$R, $In, $Out> { + $R call( + {String? colorCode, + String? indicator, + String? name, + String? value, + String? chartType, + String? visualizationCode, + String? projectId}); + InsightModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t); +} + +class _InsightModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, InsightModel, $Out> + implements InsightModelCopyWith<$R, InsightModel, $Out> { + _InsightModelCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + InsightModelMapper.ensureInitialized(); + @override + $R call( + {Object? colorCode = $none, + Object? indicator = $none, + Object? name = $none, + Object? value = $none, + Object? chartType = $none, + Object? visualizationCode = $none, + Object? projectId = $none}) => + $apply(FieldCopyWithData({ + if (colorCode != $none) #colorCode: colorCode, + if (indicator != $none) #indicator: indicator, + if (name != $none) #name: name, + if (value != $none) #value: value, + if (chartType != $none) #chartType: chartType, + if (visualizationCode != $none) #visualizationCode: visualizationCode, + if (projectId != $none) #projectId: projectId + })); + @override + InsightModel $make(CopyWithData data) => InsightModel( + colorCode: data.get(#colorCode, or: $value.colorCode), + indicator: data.get(#indicator, or: $value.indicator), + name: data.get(#name, or: $value.name), + value: data.get(#value, or: $value.value), + chartType: data.get(#chartType, or: $value.chartType), + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode), + projectId: data.get(#projectId, or: $value.projectId)); + + @override + InsightModelCopyWith<$R2, InsightModel, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t) => + _InsightModelCopyWithImpl($value, $cast, t); +} diff --git a/packages/digit_dss/lib/models/entities/plots.dart b/packages/digit_dss/lib/models/entities/plots.dart new file mode 100644 index 000000000..526377ef1 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/plots.dart @@ -0,0 +1,28 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; +import 'package:digit_data_model/data_model.dart'; + +part 'plots.mapper.dart'; + +@MappableClass(ignoreNull: true, discriminatorValue: MappableClass.useAsDefault) +class DashboardPlotModel with DashboardPlotModelMappable { + final String? label; + final String? strValue; + final String? name; + final String? value; + final String? symbol; + final String? visualizationCode; + final String? chartType; + final String? projectId; + + DashboardPlotModel({ + this.strValue, + this.label, + this.name, + this.value, + this.symbol, + this.projectId, + this.chartType, + this.visualizationCode, + }) : super(); +} diff --git a/packages/digit_dss/lib/models/entities/plots.mapper.dart b/packages/digit_dss/lib/models/entities/plots.mapper.dart new file mode 100644 index 000000000..7369df595 --- /dev/null +++ b/packages/digit_dss/lib/models/entities/plots.mapper.dart @@ -0,0 +1,189 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'plots.dart'; + +class DashboardPlotModelMapper extends ClassMapperBase { + DashboardPlotModelMapper._(); + + static DashboardPlotModelMapper? _instance; + static DashboardPlotModelMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals.use(_instance = DashboardPlotModelMapper._()); + } + return _instance!; + } + + @override + final String id = 'DashboardPlotModel'; + + static String? _$strValue(DashboardPlotModel v) => v.strValue; + static const Field _f$strValue = + Field('strValue', _$strValue, opt: true); + static String? _$label(DashboardPlotModel v) => v.label; + static const Field _f$label = + Field('label', _$label, opt: true); + static String? _$name(DashboardPlotModel v) => v.name; + static const Field _f$name = + Field('name', _$name, opt: true); + static String? _$value(DashboardPlotModel v) => v.value; + static const Field _f$value = + Field('value', _$value, opt: true); + static String? _$symbol(DashboardPlotModel v) => v.symbol; + static const Field _f$symbol = + Field('symbol', _$symbol, opt: true); + static String? _$projectId(DashboardPlotModel v) => v.projectId; + static const Field _f$projectId = + Field('projectId', _$projectId, opt: true); + static String? _$chartType(DashboardPlotModel v) => v.chartType; + static const Field _f$chartType = + Field('chartType', _$chartType, opt: true); + static String? _$visualizationCode(DashboardPlotModel v) => + v.visualizationCode; + static const Field _f$visualizationCode = + Field('visualizationCode', _$visualizationCode, opt: true); + + @override + final MappableFields fields = const { + #strValue: _f$strValue, + #label: _f$label, + #name: _f$name, + #value: _f$value, + #symbol: _f$symbol, + #projectId: _f$projectId, + #chartType: _f$chartType, + #visualizationCode: _f$visualizationCode, + }; + @override + final bool ignoreNull = true; + + static DashboardPlotModel _instantiate(DecodingData data) { + return DashboardPlotModel( + strValue: data.dec(_f$strValue), + label: data.dec(_f$label), + name: data.dec(_f$name), + value: data.dec(_f$value), + symbol: data.dec(_f$symbol), + projectId: data.dec(_f$projectId), + chartType: data.dec(_f$chartType), + visualizationCode: data.dec(_f$visualizationCode)); + } + + @override + final Function instantiate = _instantiate; + + static DashboardPlotModel fromMap(Map map) { + return ensureInitialized().decodeMap(map); + } + + static DashboardPlotModel fromJson(String json) { + return ensureInitialized().decodeJson(json); + } +} + +mixin DashboardPlotModelMappable { + String toJson() { + return DashboardPlotModelMapper.ensureInitialized() + .encodeJson(this as DashboardPlotModel); + } + + Map toMap() { + return DashboardPlotModelMapper.ensureInitialized() + .encodeMap(this as DashboardPlotModel); + } + + DashboardPlotModelCopyWith + get copyWith => _DashboardPlotModelCopyWithImpl( + this as DashboardPlotModel, $identity, $identity); + @override + String toString() { + return DashboardPlotModelMapper.ensureInitialized() + .stringifyValue(this as DashboardPlotModel); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (runtimeType == other.runtimeType && + DashboardPlotModelMapper.ensureInitialized() + .isValueEqual(this as DashboardPlotModel, other)); + } + + @override + int get hashCode { + return DashboardPlotModelMapper.ensureInitialized() + .hashValue(this as DashboardPlotModel); + } +} + +extension DashboardPlotModelValueCopy<$R, $Out> + on ObjectCopyWith<$R, DashboardPlotModel, $Out> { + DashboardPlotModelCopyWith<$R, DashboardPlotModel, $Out> + get $asDashboardPlotModel => + $base.as((v, t, t2) => _DashboardPlotModelCopyWithImpl(v, t, t2)); +} + +abstract class DashboardPlotModelCopyWith<$R, $In extends DashboardPlotModel, + $Out> implements ClassCopyWith<$R, $In, $Out> { + $R call( + {String? strValue, + String? label, + String? name, + String? value, + String? symbol, + String? projectId, + String? chartType, + String? visualizationCode}); + DashboardPlotModelCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t); +} + +class _DashboardPlotModelCopyWithImpl<$R, $Out> + extends ClassCopyWithBase<$R, DashboardPlotModel, $Out> + implements DashboardPlotModelCopyWith<$R, DashboardPlotModel, $Out> { + _DashboardPlotModelCopyWithImpl(super.value, super.then, super.then2); + + @override + late final ClassMapperBase $mapper = + DashboardPlotModelMapper.ensureInitialized(); + @override + $R call( + {Object? strValue = $none, + Object? label = $none, + Object? name = $none, + Object? value = $none, + Object? symbol = $none, + Object? projectId = $none, + Object? chartType = $none, + Object? visualizationCode = $none}) => + $apply(FieldCopyWithData({ + if (strValue != $none) #strValue: strValue, + if (label != $none) #label: label, + if (name != $none) #name: name, + if (value != $none) #value: value, + if (symbol != $none) #symbol: symbol, + if (projectId != $none) #projectId: projectId, + if (chartType != $none) #chartType: chartType, + if (visualizationCode != $none) #visualizationCode: visualizationCode + })); + @override + DashboardPlotModel $make(CopyWithData data) => DashboardPlotModel( + strValue: data.get(#strValue, or: $value.strValue), + label: data.get(#label, or: $value.label), + name: data.get(#name, or: $value.name), + value: data.get(#value, or: $value.value), + symbol: data.get(#symbol, or: $value.symbol), + projectId: data.get(#projectId, or: $value.projectId), + chartType: data.get(#chartType, or: $value.chartType), + visualizationCode: + data.get(#visualizationCode, or: $value.visualizationCode)); + + @override + DashboardPlotModelCopyWith<$R2, DashboardPlotModel, $Out2> $chain<$R2, $Out2>( + Then<$Out2, $R2> t) => + _DashboardPlotModelCopyWithImpl($value, $cast, t); +} diff --git a/packages/digit_dss/lib/pages/dashboard/dashboard.dart b/packages/digit_dss/lib/pages/dashboard/dashboard.dart new file mode 100644 index 000000000..f81d390c2 --- /dev/null +++ b/packages/digit_dss/lib/pages/dashboard/dashboard.dart @@ -0,0 +1,184 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/models/digit_table_model.dart'; +import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_dss/blocs/dashboard.dart'; +import 'package:digit_dss/widgets/back_navigation_help_header.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../utils/i18_key_constants.dart' as i18; +import '../../utils/utils.dart'; +import '../../widgets/dashboard/dashboard_metric_card.dart'; +import '../../widgets/localized.dart'; +import '../../widgets/no_result_card.dart'; + +@RoutePage() +class UserDashboardPage extends LocalizedStatefulWidget { + const UserDashboardPage({ + super.key, + }); + + @override + State createState() { + return UserDashboardPageState(); + } +} + +class UserDashboardPageState extends LocalizedState { + @override + void initState() { + context.read().add(DashboardRefreshEvent( + projectId: DashboardSingleton().projectId, + syncFromServer: false, + selectedDate: DateTime.now(), + )); + + super.initState(); + } + + bool isLoading = false; + + @override + Widget build(BuildContext context) { + return BlocConsumer( + listener: (context, dashboardState) { + dashboardState.maybeWhen( + orElse: () => false, + loading: () { + if (!isLoading) { + setState(() { + isLoading = true; + }); + Loaders.showLoadingDialog(context); + } + }, + fetched: ( + metricData, + tableData, + selectedDate, + isNetworkError, + ) { + Navigator.of(context, rootNavigator: true).pop(); + if (isNetworkError == true) { + DigitToast.show(context, + options: DigitToastOptions( + localizations.translate(i18.dashboard.someErrorOccured), + true, + DigitTheme.instance.mobileTheme, + )); + } + + setState(() { + isLoading = false; + }); + }, + error: () { + Navigator.of(context, rootNavigator: true).pop(); + setState(() { + isLoading = false; + }); + DigitToast.show(context, + options: DigitToastOptions( + localizations.translate(i18.dashboard.someErrorOccured), + true, + DigitTheme.instance.mobileTheme)); + }); + }, builder: (context, dashboardState) { + return RefreshIndicator( + onRefresh: () { + dashboardState.maybeWhen( + orElse: () => false, + fetched: + (metricData, tableData, selectedDate, isNetworkError) async { + bool isConnected = await getIsConnected(); + if (isConnected) { + context.read().add(DashboardRefreshEvent( + projectId: DashboardSingleton().projectId, + syncFromServer: true, + selectedDate: selectedDate ?? DateTime.now(), + )); + } else { + DigitToast.show(context, + options: DigitToastOptions( + localizations + .translate(i18.dashboard.networkFailureError), + true, + DigitTheme.instance.mobileTheme, + )); + } + }); + + return Future.delayed(const Duration(seconds: 1)); + }, + child: Scaffold( + body: ScrollableContent( + footer: PoweredByDigit( + version: DashboardSingleton().appVersion, + ), + header: const Column(children: [ + BackNavigationHelpHeaderWidget( + showHelp: false, + ), + ]), + children: [ + dashboardState.maybeWhen( + orElse: () => const SizedBox.shrink(), + fetched: + (metricData, tableData, selectedDate, isNetworkError) { + return Column( + children: [ + DashboardMetricCard( + selectedDate: selectedDate ?? DateTime.now(), + ), + if ((metricData ?? {}).isEmpty && + (tableData ?? []).isEmpty) + NoResultCard( + align: Alignment.center, + label: localizations.translate( + i18.common.noResultsFound, + ), + ), + ...(tableData ?? []) + .map((table) => Padding( + padding: const EdgeInsets.all(kPadding), + child: DigitTable( + headerList: table.headerList.map((header) { + return TableHeader( + localizations.translate(header.label), + cellKey: header.cellKey, + ); + }).toList(), + tableData: table.tableData, + height: ((table.tableData.length) + 1) * 65, + columnWidth: + MediaQuery.of(context).size.width / 2, + columnRowFixedHeight: 65, + scrollPhysics: (table.tableData.length ?? + 0) > + 5 + ? const ClampingScrollPhysics() + : const NeverScrollableScrollPhysics(), + ), + )) + .toList(), + if ((tableData ?? []).isNotEmpty) + Align( + alignment: Alignment.center, + child: DigitInfoCard( + title: localizations + .translate(i18.dashboard.noteHeader), + description: localizations + .translate(i18.dashboard.noteDescription), + ), + ) + ], + ); + }), + ], + ), + ), + ); + }); + } +} diff --git a/packages/digit_dss/lib/router/dashboard_router.dart b/packages/digit_dss/lib/router/dashboard_router.dart new file mode 100644 index 000000000..f20ca702e --- /dev/null +++ b/packages/digit_dss/lib/router/dashboard_router.dart @@ -0,0 +1,17 @@ +import 'package:auto_route/auto_route.dart'; + +import 'dashboard_router.gm.dart'; + +@AutoRouterConfig.module() +class DashboardRoute extends $DashboardRoute { + @override + RouteType get defaultRouteType => const RouteType.material(); + + @override + List routes = [ + AutoRoute( + page: UserDashboardRoute.page, + path: 'dashboard', + ), + ]; +} diff --git a/packages/digit_dss/lib/router/dashboard_router.gm.dart b/packages/digit_dss/lib/router/dashboard_router.gm.dart new file mode 100644 index 000000000..652ef7091 --- /dev/null +++ b/packages/digit_dss/lib/router/dashboard_router.gm.dart @@ -0,0 +1,38 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +// ************************************************************************** +// AutoRouterGenerator +// ************************************************************************** + +// ignore_for_file: type=lint +// coverage:ignore-file + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'package:auto_route/auto_route.dart' as _i2; +import 'package:digit_dss/pages/dashboard/dashboard.dart' as _i1; + +abstract class $DashboardRoute extends _i2.AutoRouterModule { + @override + final Map pagesMap = { + UserDashboardRoute.name: (routeData) { + return _i2.AutoRoutePage( + routeData: routeData, + child: const _i1.UserDashboardPage(), + ); + } + }; +} + +/// generated route for +/// [_i1.UserDashboardPage] +class UserDashboardRoute extends _i2.PageRouteInfo { + const UserDashboardRoute({List<_i2.PageRouteInfo>? children}) + : super( + UserDashboardRoute.name, + initialChildren: children, + ); + + static const String name = 'UserDashboardRoute'; + + static const _i2.PageInfo page = _i2.PageInfo(name); +} diff --git a/packages/digit_dss/lib/utils/i18_key_constants.dart b/packages/digit_dss/lib/utils/i18_key_constants.dart new file mode 100644 index 000000000..47bfc3a66 --- /dev/null +++ b/packages/digit_dss/lib/utils/i18_key_constants.dart @@ -0,0 +1,68 @@ +const common = Common(); +const dashboard = Dashboard(); + +class Common { + const Common(); + + String get coreCommonContinue => 'CORE_COMMON_CONTINUE'; + + String get coreCommonAge => 'CORE_COMMON_AGE'; + + String get coreCommonName => 'CORE_COMMON_NAME'; + + String get coreCommonEmailId => 'CORE_COMMON_EMAIL_ID'; + + String get coreCommonGender => 'CORE_COMMON_GENDER'; + + String get coreCommonMobileNumber => 'CORE_COMMON_MOBILE_NUMBER'; + + String get coreCommonSubmit => 'CORE_COMMON_SUBMIT'; + + String get coreCommonSave => 'CORE_COMMON_SAVE'; + + String get coreCommonCancel => 'CORE_COMMON_CANCEL'; + + String get coreCommonRequired => 'CORE_COMMON_REQUIRED'; + + String get searchByName => 'CORE_COMMON_SEARCH_BY_NAME'; + + String get coreCommonReasonRequired => 'CORE_COMMON_REASON_REQUIRED'; + + String get coreCommonClose => 'CORE_COMMON_CLOSE'; + + String get coreCommonOk => 'CORE_COMMON_OK'; + + String get coreCommonNA => 'CORE_COMMON_NA'; + + String get coreCommonBack => 'CORE_COMMON_BACK'; + + String get coreCommonHelp => 'CORE_COMMON_HELP'; + + String get coreCommonHome => 'CORE_COMMON_HOME'; + String get coreCommonlanguage => 'CORE_COMMON_LANGUAGE'; + + String get coreCommonSkip => 'CORE_COMMON_SKIP'; + + String get coreCommonNext => 'CORE_COMMON_NEXT'; + + String get coreCommonYes => 'CORE_COMMON_YES'; + + String get coreCommonNo => 'CORE_COMMON_NO'; + String get coreCommonGoback => 'CORE_COMMON_GO_BACK'; + + String get coreCommonDownload => 'CORE_COMMON_DOWNLOAD'; + + String get coreCommonDownloadFailed => 'CORE_COMMON_DOWNLOAD_FAILED'; + + String get noResultsFound => 'NO_RESULTS_FOUND'; +} + +class Dashboard { + const Dashboard(); + + String get dashboardLabel => 'HOME_DASHBOARD_LABEL'; + String get noteHeader => 'DSS_NOTE_TITLE'; + String get noteDescription => 'DSS_NOTE_DESCRIPTION'; + String get networkFailureError => 'DSS_NETWORK_FAILURE_ERROR'; + String get someErrorOccured => 'DSS_SOME_ERROR_OCCURED'; +} diff --git a/packages/digit_dss/lib/utils/utils.dart b/packages/digit_dss/lib/utils/utils.dart new file mode 100644 index 000000000..08334cf1d --- /dev/null +++ b/packages/digit_dss/lib/utils/utils.dart @@ -0,0 +1,200 @@ +import 'dart:io'; + +import 'package:digit_components/digit_components.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:digit_dss/blocs/app_localization.dart'; +import 'package:digit_dss/data/local_store/no_sql/schema/dashboard_config_schema.dart'; +import 'package:digit_dss/data/remote/dashboard.dart'; +import 'package:digit_dss/models/entities/dashboard_request.dart'; +import 'package:flutter/material.dart'; +import 'package:isar/isar.dart'; + +import '../models/entities/dss_enums.dart'; + +const dashboardAPIPath = '/dashboard-analytics/dashboard/getChartV2'; + +Future getIsConnected() async { + try { + final result = await InternetAddress.lookup('example.com'); + if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) { + return true; + } + + return false; + } on SocketException catch (_) { + return false; + } +} + +Widget buildMetric( + BuildContext context, + String label, + String value, + int index, + DashboardLocalization localizations, +) { + return Column( + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.spaceAround, + mainAxisSize: MainAxisSize.max, + children: [ + if (index > 2) + SizedBox( + width: MediaQuery.of(context).size.width / 3.6, + child: Divider( + indent: 0, + height: kPadding, + endIndent: 0, + thickness: 2, + color: DigitTheme.instance.mobileTheme.colorScheme.outline, + ), + ), + ConstrainedBox( + constraints: + BoxConstraints(maxWidth: MediaQuery.of(context).size.width / 5), + child: Text( + value, + style: DigitTheme.instance.mobileTheme.textTheme.bodyLarge, + maxLines: 2, + textAlign: TextAlign.center, + ), + ), + ConstrainedBox( + constraints: + BoxConstraints(maxWidth: MediaQuery.of(context).size.width / 3.6), + child: Align( + alignment: Alignment.center, + child: Text( + localizations.translate( + label, + ), + textAlign: TextAlign.center, + style: DigitTheme.instance.mobileTheme.textTheme.bodyMedium, + ), + ), + ), + ], + ); +} + +DashboardRequestModel getRequestModel({ + required String visualizationCode, + required String visualizationType, + required int startDate, + required int endDate, +}) { + return DashboardRequestModel( + aggregationRequestDto: AggregationRequestDto( + visualizationCode: visualizationCode, + visualizationType: visualizationType, + requestDate: RequestDate( + startDate: startDate, + endDate: endDate, + interval: DSSEnums.day.toValue(), + title: DSSEnums.home.toValue(), + )), + headers: DSSHeaders( + tenantId: DashboardSingleton().tenantId, + ), + ); +} + +Future processDashboardConfig( + List dashboardConfig, + int startDate, + int endDate, + Isar isar, + DateTime lastSelectedDate, + DashboardRemoteRepository dashboardRemoteRepo, + String actionPath, + String tenantId, + String projectId, + List userList, +) async { + if (dashboardConfig.isNotEmpty) { + for (var entry in dashboardConfig) { + String visualizationType = entry.chartType ?? ''; + String visualizationCode = entry.name ?? ''; + await dashboardRemoteRepo.searchAndWriteToDB( + apiEndPoint: actionPath, + lastSelectedDate: lastSelectedDate, + query: DashboardRequestModel( + aggregationRequestDto: AggregationRequestDto( + visualizationType: visualizationType, + visualizationCode: visualizationCode, + filters: { + DSSEnums.uuid.toValue(): userList, + DSSEnums.projectId.toValue(): projectId + }, + moduleLevel: "", + queryType: "", + requestDate: RequestDate( + startDate: startDate, + endDate: endDate, + interval: DSSEnums.day.toValue(), + title: DSSEnums.home.toValue(), + )), + headers: DSSHeaders( + tenantId: tenantId, + )).toMap(), + projectId: projectId, + isar: isar, + ); + } + } +} + +String transformToLocaleCode(String input) { + // Replace spaces with underscores and convert to uppercase + return input.replaceAll(' ', '_').toUpperCase(); +} + +// create a singleton class for Dashboard package where set data and get data methods are defined + +class DashboardSingleton { + static final DashboardSingleton _singleton = DashboardSingleton._internal(); + + factory DashboardSingleton() { + return _singleton; + } + + DashboardSingleton._internal(); + + String? _tenantId; + String? _projectId; + String? _actionPath; + String? _appVersion; + ProjectModel? _selectedProject; + DashboardConfigSchema? _dashboardConfig; + + void setInitialData({ + required String projectId, + required String tenantId, + required String actionPath, + required String appVersion, + required ProjectModel selectedProject, + DashboardConfigSchema? dashboardConfig, + }) { + _projectId = projectId; + _tenantId = tenantId; + _actionPath = actionPath.trim().isNotEmpty + ? actionPath + : dashboardAPIPath; //[TODO: To be added to MDMS Service registry + _appVersion = appVersion; + _selectedProject = selectedProject; + _dashboardConfig = dashboardConfig; + } + + String get tenantId => _tenantId ?? ''; + + String get projectId => _projectId ?? ''; + + String get appVersion => _appVersion ?? ''; + + String get actionPath => + _actionPath ?? + dashboardAPIPath; //[TODO: To be added to MDMS Service registry + ProjectModel? get selectedProject => _selectedProject; + + DashboardConfigSchema? get dashboardConfig => _dashboardConfig; +} diff --git a/packages/digit_dss/lib/widgets/back_navigation_help_header.dart b/packages/digit_dss/lib/widgets/back_navigation_help_header.dart new file mode 100644 index 000000000..c374ca8bb --- /dev/null +++ b/packages/digit_dss/lib/widgets/back_navigation_help_header.dart @@ -0,0 +1,80 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_dss/blocs/app_localization.dart'; +import 'package:flutter/material.dart'; + +import '../../utils/i18_key_constants.dart' as i18; + +class BackNavigationHelpHeaderWidget extends StatelessWidget { + final bool showHelp; + final bool showBackNavigation; + final bool showLogoutCTA; + final VoidCallback? helpClicked; + final VoidCallback? handleBack; + + const BackNavigationHelpHeaderWidget({ + super.key, + this.showHelp = false, //hiding help + this.showBackNavigation = true, + this.showLogoutCTA = false, + this.helpClicked, + this.handleBack, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Padding( + padding: const EdgeInsets.all(kPadding / 2), + child: Row( + children: [ + Expanded( + child: Row( + children: [ + if (showBackNavigation) + Flexible( + child: TextButton.icon( + style: TextButton.styleFrom( + foregroundColor: theme.colorScheme.onBackground, + padding: EdgeInsets.zero, + ), + onPressed: () { + context.router.maybePop(); + handleBack != null ? handleBack!() : null; + }, + icon: const Icon(Icons.arrow_left_sharp), + label: Text( + DashboardLocalization.of(context).translate( + i18.common.coreCommonBack, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ), + ], + ), + ), + SizedBox(width: showHelp ? kPadding * 2 : 0), + if (showHelp) + TextButton( + style: TextButton.styleFrom(padding: EdgeInsets.zero), + onPressed: helpClicked, + child: Row( + children: [ + Text( + DashboardLocalization.of(context) + .translate(i18.common.coreCommonHelp), + overflow: TextOverflow.ellipsis, + ), + const Icon( + Icons.help_outline_outlined, + ), // Add the icon to the right + ], + ), + ), + ], + ), + ); + } +} diff --git a/packages/digit_dss/lib/widgets/dashboard/dashboard_metric_card.dart b/packages/digit_dss/lib/widgets/dashboard/dashboard_metric_card.dart new file mode 100644 index 000000000..ab9ae35be --- /dev/null +++ b/packages/digit_dss/lib/widgets/dashboard/dashboard_metric_card.dart @@ -0,0 +1,191 @@ +import 'package:collection/collection.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_dss/widgets/localized.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../blocs/dashboard.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../utils/utils.dart'; + +class DashboardMetricCard extends LocalizedStatefulWidget { + final DateTime? selectedDate; + const DashboardMetricCard({ + super.key, + super.appLocalizations, + this.selectedDate, + }); + + @override + State createState() => _DashboardMetricCardState(); +} + +class _DashboardMetricCardState extends LocalizedState { + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = DigitTheme.instance.mobileTheme; + + return BlocBuilder( + builder: (context, dashboardState) { + return DigitCard( + child: Column( + mainAxisAlignment: MainAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: kPadding * 2, + vertical: kPadding * 2, + ), + child: Text( + localizations.translate( + i18.dashboard.dashboardLabel, + ), + style: theme.textTheme.displayMedium, + ), + ), + Expanded( + child: InkWell( + onTap: () async { + bool isConnected = await getIsConnected(); + if (isConnected) { + DateTime? pickedDate = await showDatePicker( + context: context, + initialDate: DateTime.now(), + firstDate: DateTime(1900), + lastDate: DateTime.now(), + ); + + if (pickedDate != null && pickedDate != DateTime.now()) { + final dashboardBloc = context.read(); + dashboardBloc.add(DashboardRefreshEvent( + selectedDate: pickedDate.toLocal(), + projectId: DashboardSingleton().projectId, + syncFromServer: true, + )); + } + } else { + DigitToast.show(context, + options: DigitToastOptions( + localizations + .translate(i18.dashboard.networkFailureError), + true, + DigitTheme.instance.mobileTheme)); + } + }, + child: Container( + alignment: Alignment.centerRight, + padding: const EdgeInsets.only(bottom: 12), + child: Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + dashboardState.maybeWhen( + orElse: () => '', + fetched: (metricData, tableData, selectedDate, + isNetworkError) => + '${DigitDateUtils.getMonth(selectedDate?.toLocal() ?? DateTime.now())} - ${(selectedDate?.toLocal() ?? DateTime.now()).day}, ${(selectedDate?.toLocal() ?? DateTime.now()).year}'), + style: theme.textTheme.bodyMedium + ?.apply(color: theme.colorScheme.secondary), + ), + const Padding( + padding: EdgeInsets.only(right: 3.0), + child: Visibility( + child: Icon(Icons.arrow_drop_down), + ), + ) + ]), + ), + ), + ) + ], + ), + Padding( + padding: const EdgeInsets.only(top: kPadding, bottom: kPadding), + child: Wrap( + spacing: 2.0, // Space between items + runSpacing: 2.0, // Space between lines + alignment: WrapAlignment.start, + children: [ + ...dashboardState.maybeWhen( + orElse: () => [], + fetched: + (metricData, tableData, selectedDate, isNetworkError) { + return metricData != null + ? metricData.entries + .where((m) => m.value.isHorizontal == true) + .mapIndexed(( + i, + entry, + ) { + return SizedBox( + height: MediaQuery.of(context).size.width / 3.8, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + buildMetric( + context, + entry.key, + entry.value.value, + i, + localizations, + ), + if (entry.key != + metricData.entries.last.key) + VerticalDivider( + width: kPadding, + color: DigitTheme.instance.mobileTheme + .colorScheme.outline, + thickness: 2, + ), + ], + ), + ); + }).toList() + : []; + }), + ...dashboardState.maybeWhen( + orElse: () => [], + fetched: + (metricData, tableData, selectedDate, isNetworkError) { + return metricData != null + ? metricData.entries + .where((m) => m.value.isHorizontal == false) + .mapIndexed(( + i, + entry, + ) { + return Align( + alignment: Alignment.centerLeft, + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: kPadding), + child: Text( + '${entry.value.value} ${localizations.translate(entry.value.header)}', + textAlign: TextAlign.start, + style: DigitTheme.instance.mobileTheme + .textTheme.bodyMedium, + ), + ), + ); + }).toList() + : []; + }), + ], + ), + ), + ], + )); + }); + } +} diff --git a/packages/digit_dss/lib/widgets/localized.dart b/packages/digit_dss/lib/widgets/localized.dart new file mode 100644 index 000000000..a35c9b95e --- /dev/null +++ b/packages/digit_dss/lib/widgets/localized.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; + +import '../blocs/app_localization.dart'; + +abstract class LocalizedStatefulWidget extends StatefulWidget { + final DashboardLocalization? appLocalizations; + + const LocalizedStatefulWidget({ + super.key, + this.appLocalizations, + }); +} + +abstract class LocalizedState + extends State { + late DashboardLocalization _localizations; + + DashboardLocalization get localizations => _localizations; + + set localizations(DashboardLocalization localizations) { + if (mounted) { + setState(() { + _localizations = localizations; + }); + } + } + + @override + @mustCallSuper + void didChangeDependencies() { + _localizations = + widget.appLocalizations ?? DashboardLocalization.of(context); + super.didChangeDependencies(); + } +} diff --git a/packages/digit_dss/lib/widgets/no_result_card.dart b/packages/digit_dss/lib/widgets/no_result_card.dart new file mode 100644 index 000000000..f63d1eb56 --- /dev/null +++ b/packages/digit_dss/lib/widgets/no_result_card.dart @@ -0,0 +1,34 @@ +import 'package:attendance_management/utils/constants.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_svg/svg.dart'; + +class NoResultCard extends StatelessWidget { + final AlignmentGeometry align; + final String? label; + + const NoResultCard({ + super.key, + this.align = Alignment.centerLeft, + this.label, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Align( + alignment: align, + child: Padding( + padding: const EdgeInsets.all(kPadding), + child: Column( + children: [ + SvgPicture.asset(noResultSvg), + Text( + label ?? '', + style: theme.textTheme.bodyMedium, + ) + ], + ))); + } +} diff --git a/packages/digit_dss/pubspec.yaml b/packages/digit_dss/pubspec.yaml new file mode 100644 index 000000000..2ead774a0 --- /dev/null +++ b/packages/digit_dss/pubspec.yaml @@ -0,0 +1,85 @@ +name: digit_dss +description: "DSS Dashboard for campaign management" +version: 1.0.1 +homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/develop/packages/digit_dss +repository: https://github.com/egovernments/health-campaign-field-worker-app + +environment: + sdk: '>=3.2.3 <4.0.0' + flutter: ">=1.17.0" + +dependencies: + flutter: + sdk: flutter + digit_components: ^1.0.0+9 + flutter_bloc: ^8.1.1 + reactive_forms: ^14.1.0 + intl: ^0.18.0 + freezed_annotation: ^2.1.0 + flutter_svg: ^2.0.8 + dart_mappable: ^4.2.0 + auto_route: ^7.8.4 + digit_data_model: ^1.0.3 + package_info_plus: ^5.0.1 + collection: ^1.16.0 + async: ^2.11.0 + dio: ^5.4.2+1 + isar: ^3.0.5 + isar_flutter_libs: ^3.0.5 + attendance_management: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + dart_code_metrics: ^5.7.6 + freezed: ^2.1.0+1 + json_serializable: ^6.4.0 + drift_dev: ^2.14.1 + build_runner: ^2.4.7 + bloc_test: ^9.1.0 + mocktail: ^1.0.2 + dart_mappable_builder: + git: + url: https://github.com/egovernments/health-campaign-field-worker-app/ + ref: master + path: ./packages/dart_mappable_builder + auto_route_generator: ^7.3.2 + isar_generator: ^3.0.5 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + +# To add assets to your package, add an assets section, like this: +# assets: +# - images/a_dot_burr.jpeg +# - images/a_dot_ham.jpeg +# +# For details regarding assets in packages, see +# https://flutter.dev/assets-and-images/#from-packages +# +# An image asset can refer to one or more resolution-specific "variants", see +# https://flutter.dev/assets-and-images/#resolution-aware + +# To add custom fonts to your package, add a fonts section here, +# in this "flutter" section. Each entry in this list should have a +# "family" key with the font family name, and a "fonts" key with a +# list giving the asset and other descriptors for the font. For +# example: +# fonts: +# - family: Schyler +# fonts: +# - asset: fonts/Schyler-Regular.ttf +# - asset: fonts/Schyler-Italic.ttf +# style: italic +# - family: Trajan Pro +# fonts: +# - asset: fonts/TrajanPro.ttf +# - asset: fonts/TrajanPro_Bold.ttf +# weight: 700 +# +# For details regarding fonts in packages, see +# https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/digit_dss/test/digit_dss_test.dart b/packages/digit_dss/test/digit_dss_test.dart new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/packages/digit_dss/test/digit_dss_test.dart @@ -0,0 +1 @@ + diff --git a/packages/digit_scanner/CHANGELOG.md b/packages/digit_scanner/CHANGELOG.md index 3a21adb11..398996315 100644 --- a/packages/digit_scanner/CHANGELOG.md +++ b/packages/digit_scanner/CHANGELOG.md @@ -1,44 +1,48 @@ -## 0.0.0-dev.1 +## 1.0.3 +* Manual code entry fixes with stable version -Digit Scanner Package Setup and Initialization - -## 0.0.0-dev.2 +## 1.0.3-dev.1 +* Fix for manual entry result not reflecting -Added Flutter version constraints - -## 0.0.0-dev.3 +## 1.0.2 -Removed flutter localizations dependency +* UI Fixes +* Added audio to correct scan and invalid scan -## 0.0.0-dev.4 +## 1.0.1 -Updated repository and homepage url +* Updated digit_components to latest version -## 0.0.0-dev.5 +## 1.0.0+1 -Updated digit_components version for dropdown fix +* Initial stable Release -## 0.0.0-dev.6 +## 1.0.0 -Disabled Submit button for manual code not entered +* GS1 Barcodes-Removed Enter Manual Code ## 0.0.0-dev.7 Reverted disable button change -## 1.0.0 +## 0.0.0-dev.6 -Initial stable Release +Updated digit_components version for dropdown fix -## 1.0.0+1 +## 0.0.0-dev.5 -* Updated digit_components to latest version +Updated repository and homepage url -## 1.0.1 +## 0.0.0-dev.4 -* GS1 Barcodes-Removed Enter Manual Code +Removed flutter localizations dependency -## 1.0.2 +## 0.0.0-dev.3 -* UI Fixes -* Added audio to correct scan and invalid scan +Added Flutter version constraints + +## 0.0.0-dev.2 + +Digit Scanner Package Setup and Initialization + +## 0.0.0-dev.1 \ No newline at end of file diff --git a/packages/digit_scanner/example/ios/Podfile b/packages/digit_scanner/example/ios/Podfile new file mode 100644 index 000000000..fdcc671eb --- /dev/null +++ b/packages/digit_scanner/example/ios/Podfile @@ -0,0 +1,44 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/packages/digit_scanner/example/pubspec.lock b/packages/digit_scanner/example/pubspec.lock index 1bd5fd661..dea8707d4 100644 --- a/packages/digit_scanner/example/pubspec.lock +++ b/packages/digit_scanner/example/pubspec.lock @@ -306,19 +306,20 @@ packages: source: hosted version: "2.3.6" digit_components: - dependency: "direct overridden" + dependency: transitive description: - path: "../../digit_components" - relative: true - source: path - version: "1.0.0+2" + name: digit_components + sha256: "01320d4c72829045e789d1a56e23ff2bd85dad6a1831d27bd507a1acaceae17e" + url: "https://pub.dev" + source: hosted + version: "1.0.1" digit_scanner: dependency: "direct main" description: path: ".." relative: true source: path - version: "1.0.2" + version: "1.0.3" easy_stepper: dependency: transitive description: diff --git a/packages/digit_scanner/lib/blocs/scanner.dart b/packages/digit_scanner/lib/blocs/scanner.dart index 11284ed4d..1aafa54c3 100644 --- a/packages/digit_scanner/lib/blocs/scanner.dart +++ b/packages/digit_scanner/lib/blocs/scanner.dart @@ -20,7 +20,9 @@ class DigitScannerBloc extends Bloc { DigitScannerEmitter emit, ) async { try { - emit(state.copyWith(barCodes: event.barCode, qrCodes: event.qrCode)); + emit(state.copyWith(loading: true)); + emit(state.copyWith( + barCodes: event.barCode, qrCodes: event.qrCode)); } catch (error) { rethrow; } finally { diff --git a/packages/digit_scanner/lib/pages/qr_scanner.dart b/packages/digit_scanner/lib/pages/qr_scanner.dart index 9512feb5e..c4e4b037e 100644 --- a/packages/digit_scanner/lib/pages/qr_scanner.dart +++ b/packages/digit_scanner/lib/pages/qr_scanner.dart @@ -4,12 +4,14 @@ import 'package:audioplayers/audioplayers.dart'; import 'package:auto_route/auto_route.dart'; import 'package:camera/camera.dart'; import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/digit_toaster.dart'; import 'package:digit_scanner/utils/scanner_utils.dart'; import 'package:digit_scanner/widgets/localized.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:google_mlkit_barcode_scanning/google_mlkit_barcode_scanning.dart'; import 'package:gs1_barcode_parser/gs1_barcode_parser.dart'; +import 'package:reactive_forms/reactive_forms.dart'; import '../../utils/i18_key_constants.dart' as i18; import '../blocs/scanner.dart'; @@ -51,7 +53,7 @@ class _DigitScannerPageState extends LocalizedState { bool manualCode = false; bool flashStatus = false; final GlobalKey qrKey = GlobalKey(debugLabel: 'QR'); - final _resourceController = TextEditingController(); + static const _manualCodeFormKey = 'manualCode'; @override void initState() { @@ -184,8 +186,6 @@ class _DigitScannerPageState extends LocalizedState { ); setState(() { manualCode = true; - _resourceController.value = - const TextEditingValue(); }); }, child: Padding( @@ -402,77 +402,100 @@ class _DigitScannerPageState extends LocalizedState { ), ], ) - : DigitCard( - child: ScrollableContent( - backgroundColor: theme.colorScheme.onError, - header: GestureDetector( - onTap: () { - setState(() { - manualCode = false; - initializeCameras(); - }); - }, - child: const Align( - alignment: Alignment.topRight, - child: Icon(Icons.close), - ), - ), - footer: DigitElevatedButton( - onPressed: () async { - final bloc = context.read(); - codes.add(_resourceController.value.text); - bloc.add( - DigitScannerEvent.handleScanner( - barCode: state.barCodes, - qrCode: codes, - ), - ); - if (widget.isGS1code && - result.length < widget.quantity) { - DigitScannerUtils().buildDialog( - context, - localizations, - widget.quantity, - ); - } + : BlocBuilder( + builder: (context, state) { + return ReactiveFormBuilder( + form: () => buildForm(), + builder: (context, form, child) { + return DigitCard( + child: ScrollableContent( + backgroundColor: theme.colorScheme.onError, + header: GestureDetector( + onTap: () { + setState(() { + manualCode = false; + initializeCameras(); + }); + }, + child: const Align( + alignment: Alignment.topRight, + child: Icon(Icons.close), + ), + ), + footer: DigitElevatedButton( + onPressed: () async { + if (form + .control(_manualCodeFormKey) + .value == + null || + form + .control(_manualCodeFormKey) + .value + .toString() + .trim() + .isEmpty) { + DigitToast.show(context, + options: DigitToastOptions( + localizations.translate( + i18.scanner.enterManualCode), + true, + theme, + )); + } else { + final bloc = + context.read(); + codes.add(form + .control(_manualCodeFormKey) + .value); + bloc.add( + DigitScannerEvent.handleScanner( + barCode: state.barCodes, + qrCode: codes, + ), + ); + if (widget.isGS1code && + result.length < widget.quantity) { + DigitScannerUtils().buildDialog( + context, + localizations, + widget.quantity, + ); + } - setState(() { - manualCode = false; - initializeCameras(); - }); - }, - child: Text(localizations.translate( - i18.common.coreCommonSubmit, - )), - ), - children: [ - Align( - alignment: Alignment.topLeft, - child: Text( - localizations.translate( - i18.scanner.enterManualCode, + setState(() { + manualCode = false; + initializeCameras(); + }); + } + }, + child: Text(localizations.translate( + i18.common.coreCommonSubmit, + )), + ), + children: [ + Align( + alignment: Alignment.topLeft, + child: Text( + localizations.translate( + i18.scanner.enterManualCode, + ), + style: theme.textTheme.headlineLarge, + ), + ), + const SizedBox( + height: kPadding * 2, + ), + DigitTextFormField( + formControlName: _manualCodeFormKey, + label: localizations.translate( + i18.scanner.resourceCode, + ), + ), + ], ), - style: theme.textTheme.headlineLarge, - ), - ), - const SizedBox( - height: kPadding * 2, - ), - Text(localizations.translate( - i18.scanner.manualCodeDescription, - )), - const SizedBox( - height: kPadding * 2, - ), - DigitTextField( - label: localizations.translate( - i18.scanner.resourceCode, - ), - controller: _resourceController, - ), - ], - ), - ) + ); + }); + }) : const Center( child: CircularProgressIndicator(), ); @@ -577,4 +600,9 @@ class _DigitScannerPageState extends LocalizedState { : ImageFormatGroup.bgra8888, ); } + + FormGroup buildForm() { + return fb + .group({_manualCodeFormKey: FormControl()}); + } } diff --git a/packages/digit_scanner/pubspec.lock b/packages/digit_scanner/pubspec.lock index a84587afb..4f77af87f 100644 --- a/packages/digit_scanner/pubspec.lock +++ b/packages/digit_scanner/pubspec.lock @@ -17,14 +17,6 @@ packages: url: "https://pub.dev" source: hosted version: "6.2.0" - ansicolor: - dependency: transitive - description: - name: ansicolor - sha256: "8bf17a8ff6ea17499e40a2d2542c2f481cd7615760c6d34065cb22bfd22e6880" - url: "https://pub.dev" - source: hosted - version: "2.0.2" archive: dependency: transitive description: @@ -329,21 +321,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" - dart_mappable: - dependency: transitive - description: - name: dart_mappable - sha256: "47269caf2060533c29b823ff7fa9706502355ffcb61e7f2a374e3a0fb2f2c3f0" - url: "https://pub.dev" - source: hosted - version: "4.2.2" - dart_mappable_builder: - dependency: "direct overridden" - description: - path: "../dart_mappable_builder" - relative: true - source: path - version: "4.2.0" dart_style: dependency: transitive description: @@ -952,7 +929,7 @@ packages: source: hosted version: "0.8.1" reactive_forms: - dependency: transitive + dependency: "direct main" description: name: reactive_forms sha256: "5aa9c48a0626c20d00a005e597cb10efbdebbfeecb9c4227b03a5945fbb91ec4" @@ -1132,14 +1109,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.1" - type_plus: - dependency: transitive - description: - name: type_plus - sha256: d5d1019471f0d38b91603adb9b5fd4ce7ab903c879d2fbf1a3f80a630a03fcc9 - url: "https://pub.dev" - source: hosted - version: "2.1.1" typed_data: dependency: transitive description: diff --git a/packages/digit_scanner/pubspec.yaml b/packages/digit_scanner/pubspec.yaml index 5ca4ebb43..bd1f19549 100644 --- a/packages/digit_scanner/pubspec.yaml +++ b/packages/digit_scanner/pubspec.yaml @@ -17,7 +17,7 @@ repository: https://github.com/egovernments/health-campaign-field-worker-app # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.2 +version: 1.0.3 environment: sdk: '>=2.19.4 <3.9.0' @@ -38,7 +38,7 @@ dependencies: google_mlkit_barcode_scanning: ^0.10.0 camera: ^0.10.5+7 gs1_barcode_parser: ^1.0.5 - digit_components: ^1.0.0+2 + digit_components: ^1.0.0+9 flutter_bloc: ^8.1.1 freezed_annotation: ^2.1.0 overlay_builder: ^1.1.0 @@ -48,6 +48,7 @@ dependencies: path_provider: ^2.0.11 path: ^1.8.2 google_mlkit_commons: ^0.6.0 + reactive_forms: ^14.1.0 dev_dependencies: flutter_test: diff --git a/packages/inventory_management/CHANGELOG.md b/packages/inventory_management/CHANGELOG.md index 1e9156c4a..e4659fe04 100644 --- a/packages/inventory_management/CHANGELOG.md +++ b/packages/inventory_management/CHANGELOG.md @@ -1,50 +1,78 @@ -## 0.0.0-dev.1 +## 1.0.3+1 -* Inventory Management Initial Release +* Updated scanner package -## 0.0.0-dev.2 +## 1.0.3 -* Removed unused package dependencies from pubspec.yaml +* Added missing DeliveryTeam Facility in record stock screen +* Added missing scanned resources to additional fields during entry +* Added name of logged user to additional fields during entry -## 0.0.0-dev.3 +## 1.0.3-dev.2 -* Updated intl package version +* Added name of logged user to additional fields during entry -## 0.0.0-dev.4 +## 1.0.3-dev.1 -* Removed fonts references from pubspec.yaml +* Added missing DeliveryTeam Facility in record stock screen +* Added missing scanned resources to additional fields during entry -## 0.0.0-dev.5 +## 0.0.0-dev.10 -* Updated digit_components version for dropdown fix +* Updated PageState class to public for customization +* Updated digit_components -## 0.0.0-dev.6 +## 1.0.2+1 -* Updated digit_data_model to latest version -* Fixed Report Type mapping to value +* Get Precise location on Submitting latitude longitude details -## 0.0.0-dev.7 +## 1.0.2 -* Fixed Lost report type mapping to value +* Localization support added for missing fields +* Added try catch for local repository to handle db lock -## 0.0.0-dev.8 +## 1.0.1 -* Updated digit_scanner to latest version +* Bug fixes and enhancements +* Updated digit_components and digit_scanner to latest versions + +## 1.0.0 + +* Initial stable Release ## 0.0.0-dev.9 * Updated digit_scanner to latest version -## 1.0.0 +## 0.0.0-dev.8 -* Initial stable Release +* Updated digit_scanner to latest version -## 1.0.1 +## 0.0.0-dev.7 -* Bug fixes and enhancements -* Updated digit_components and digit_scanner to latest versions +* Fixed Lost report type mapping to value -## 1.0.2 +## 0.0.0-dev.6 -* Localization support added for missing fields -* Added try catch for local repository to handle db lock +* Updated digit_data_model to latest version +* Fixed Report Type mapping to value + +## 0.0.0-dev.5 + +* Updated digit_components version for dropdown fix + +## 0.0.0-dev.4 + +* Removed fonts references from pubspec.yaml + +## 0.0.0-dev.3 + +* Updated intl package version + +## 0.0.0-dev.2 + +* Removed unused package dependencies from pubspec.yaml + +## 0.0.0-dev.1 + +* Inventory Management Initial Release \ No newline at end of file diff --git a/packages/inventory_management/lib/inventory_management.dart b/packages/inventory_management/lib/inventory_management.dart index d7b229509..00fef8f19 100644 --- a/packages/inventory_management/lib/inventory_management.dart +++ b/packages/inventory_management/lib/inventory_management.dart @@ -12,6 +12,8 @@ export 'data/repositories/local/stock_reconciliation.dart'; export 'data/repositories/oplog/oplog.dart'; export 'data/repositories/remote/stock.dart'; export 'data/repositories/remote/stock_reconciliation.dart'; +export 'inventory_management.init.dart'; +export 'models/entities/inventory_enums.dart'; export 'models/entities/inventory_transport_type.dart'; export 'models/entities/stock.dart'; export 'models/entities/stock_reconciliation.dart'; @@ -28,4 +30,3 @@ export 'pages/reports/report_selection.dart'; export 'pages/stock_reconciliation/stock_reconciliation.dart'; export 'router/inventory_router.dart'; export 'utils/utils.dart'; -export 'inventory_management.init.dart'; diff --git a/packages/inventory_management/lib/inventory_management.init.dart b/packages/inventory_management/lib/inventory_management.init.dart index dac254b1d..de275eed8 100644 --- a/packages/inventory_management/lib/inventory_management.init.dart +++ b/packages/inventory_management/lib/inventory_management.init.dart @@ -3,18 +3,20 @@ // ignore_for_file: type=lint // ignore_for_file: unused_element -import 'models/entities/stock.dart' as p0; -import 'models/entities/stock_reconciliation.dart' as p1; -import 'models/entities/transaction_reason.dart' as p2; -import 'models/entities/transaction_type.dart' as p3; +import 'models/entities/inventory_enums.dart' as p0; +import 'models/entities/stock.dart' as p1; +import 'models/entities/stock_reconciliation.dart' as p2; +import 'models/entities/transaction_reason.dart' as p3; +import 'models/entities/transaction_type.dart' as p4; void initializeMappers() { - p0.StockSearchModelMapper.ensureInitialized(); - p0.StockModelMapper.ensureInitialized(); - p0.StockAdditionalFieldsMapper.ensureInitialized(); - p1.StockReconciliationSearchModelMapper.ensureInitialized(); - p1.StockReconciliationModelMapper.ensureInitialized(); - p1.StockReconciliationAdditionalFieldsMapper.ensureInitialized(); - p2.TransactionReasonMapper.ensureInitialized(); - p3.TransactionTypeMapper.ensureInitialized(); + p0.InventoryManagementEnumsMapper.ensureInitialized(); + p1.StockSearchModelMapper.ensureInitialized(); + p1.StockModelMapper.ensureInitialized(); + p1.StockAdditionalFieldsMapper.ensureInitialized(); + p2.StockReconciliationSearchModelMapper.ensureInitialized(); + p2.StockReconciliationModelMapper.ensureInitialized(); + p2.StockReconciliationAdditionalFieldsMapper.ensureInitialized(); + p3.TransactionReasonMapper.ensureInitialized(); + p4.TransactionTypeMapper.ensureInitialized(); } diff --git a/packages/inventory_management/lib/models/entities/inventory_enums.dart b/packages/inventory_management/lib/models/entities/inventory_enums.dart new file mode 100644 index 000000000..088580334 --- /dev/null +++ b/packages/inventory_management/lib/models/entities/inventory_enums.dart @@ -0,0 +1,24 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; + +part 'inventory_enums.mapper.dart'; + +@MappableEnum(caseStyle: CaseStyle.upperCase) +enum InventoryManagementEnums { + @MappableValue("waybill_quantity") + waybill_quantity, + @MappableValue("vehicle_number") + vehicle_number, + @MappableValue("comments") + comments, + @MappableValue("deliveryTeam") + deliveryTeam, + @MappableValue("lat") + lat, + @MappableValue("lng") + lng, + @MappableValue("name") + name, + @MappableValue("userName") + userName, +} diff --git a/packages/inventory_management/lib/models/entities/inventory_enums.mapper.dart b/packages/inventory_management/lib/models/entities/inventory_enums.mapper.dart new file mode 100644 index 000000000..30e88ba7d --- /dev/null +++ b/packages/inventory_management/lib/models/entities/inventory_enums.mapper.dart @@ -0,0 +1,79 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'inventory_enums.dart'; + +class InventoryManagementEnumsMapper + extends EnumMapper { + InventoryManagementEnumsMapper._(); + + static InventoryManagementEnumsMapper? _instance; + static InventoryManagementEnumsMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals + .use(_instance = InventoryManagementEnumsMapper._()); + } + return _instance!; + } + + static InventoryManagementEnums fromValue(dynamic value) { + ensureInitialized(); + return MapperContainer.globals.fromValue(value); + } + + @override + InventoryManagementEnums decode(dynamic value) { + switch (value) { + case "waybill_quantity": + return InventoryManagementEnums.waybill_quantity; + case "vehicle_number": + return InventoryManagementEnums.vehicle_number; + case "comments": + return InventoryManagementEnums.comments; + case "deliveryTeam": + return InventoryManagementEnums.deliveryTeam; + case "lat": + return InventoryManagementEnums.lat; + case "lng": + return InventoryManagementEnums.lng; + case "name": + return InventoryManagementEnums.name; + case "userName": + return InventoryManagementEnums.userName; + default: + throw MapperException.unknownEnumValue(value); + } + } + + @override + dynamic encode(InventoryManagementEnums self) { + switch (self) { + case InventoryManagementEnums.waybill_quantity: + return "waybill_quantity"; + case InventoryManagementEnums.vehicle_number: + return "vehicle_number"; + case InventoryManagementEnums.comments: + return "comments"; + case InventoryManagementEnums.deliveryTeam: + return "deliveryTeam"; + case InventoryManagementEnums.lat: + return "lat"; + case InventoryManagementEnums.lng: + return "lng"; + case InventoryManagementEnums.name: + return "name"; + case InventoryManagementEnums.userName: + return "userName"; + } + } +} + +extension InventoryManagementEnumsMapperExtension on InventoryManagementEnums { + dynamic toValue() { + InventoryManagementEnumsMapper.ensureInitialized(); + return MapperContainer.globals.toValue(this); + } +} diff --git a/packages/inventory_management/lib/pages/acknowledgement.dart b/packages/inventory_management/lib/pages/acknowledgement.dart index bf58f383b..2b48899f4 100644 --- a/packages/inventory_management/lib/pages/acknowledgement.dart +++ b/packages/inventory_management/lib/pages/acknowledgement.dart @@ -21,10 +21,10 @@ class InventoryAcknowledgementPage extends LocalizedStatefulWidget { @override State createState() => - _AcknowledgementPageState(); + AcknowledgementPageState(); } -class _AcknowledgementPageState +class AcknowledgementPageState extends LocalizedState { @override Widget build(BuildContext context) { diff --git a/packages/inventory_management/lib/pages/facility_selection.dart b/packages/inventory_management/lib/pages/facility_selection.dart index 90a968fa4..08b6d667f 100644 --- a/packages/inventory_management/lib/pages/facility_selection.dart +++ b/packages/inventory_management/lib/pages/facility_selection.dart @@ -22,10 +22,10 @@ class InventoryFacilitySelectionPage extends LocalizedStatefulWidget { @override State createState() => - _InventoryFacilitySelectionPageState(); + InventoryFacilitySelectionPageState(); } -class _InventoryFacilitySelectionPageState +class InventoryFacilitySelectionPageState extends LocalizedState { static const _facilityName = 'facilityKey'; static const _selectedFacility = 'selectedFacilityKey'; diff --git a/packages/inventory_management/lib/pages/manage_stocks.dart b/packages/inventory_management/lib/pages/manage_stocks.dart index 7649edb23..8730c8634 100644 --- a/packages/inventory_management/lib/pages/manage_stocks.dart +++ b/packages/inventory_management/lib/pages/manage_stocks.dart @@ -16,10 +16,10 @@ class ManageStocksPage extends LocalizedStatefulWidget { }); @override - State createState() => _ManageStocksPageState(); + State createState() => ManageStocksPageState(); } -class _ManageStocksPageState extends LocalizedState { +class ManageStocksPageState extends LocalizedState { @override initState() { super.initState(); diff --git a/packages/inventory_management/lib/pages/record_stock/stock_details.dart b/packages/inventory_management/lib/pages/record_stock/stock_details.dart index f509436f5..66c1bcae9 100644 --- a/packages/inventory_management/lib/pages/record_stock/stock_details.dart +++ b/packages/inventory_management/lib/pages/record_stock/stock_details.dart @@ -1,25 +1,22 @@ import 'package:auto_route/auto_route.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:digit_scanner/blocs/scanner.dart'; import 'package:digit_scanner/pages/qr_scanner.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:gs1_barcode_parser/gs1_barcode_parser.dart'; +import 'package:inventory_management/inventory_management.dart'; import 'package:inventory_management/router/inventory_router.gm.dart'; import 'package:inventory_management/utils/extensions/extensions.dart'; import 'package:reactive_forms/reactive_forms.dart'; import '../../../utils/i18_key_constants.dart' as i18; -import '../../../utils/utils.dart'; import '../../../widgets/localized.dart'; import '../../blocs/product_variant.dart'; import '../../blocs/record_stock.dart'; -import '../../models/entities/inventory_transport_type.dart'; -import '../../models/entities/stock.dart'; -import '../../models/entities/transaction_reason.dart'; -import '../../models/entities/transaction_type.dart'; import '../../widgets/back_navigation_help_header.dart'; @RoutePage() @@ -30,10 +27,10 @@ class StockDetailsPage extends LocalizedStatefulWidget { }); @override - State createState() => _StockDetailsPageState(); + State createState() => StockDetailsPageState(); } -class _StockDetailsPageState extends LocalizedState { +class StockDetailsPageState extends LocalizedState { static const _productVariantKey = 'productVariant'; static const _secondaryPartyKey = 'secondaryParty'; static const _transactionQuantityKey = 'quantity'; @@ -48,6 +45,8 @@ class _StockDetailsPageState extends LocalizedState { String? selectedFacilityId; List transportTypes = []; + List scannedResources = []; + FormGroup _form(StockRecordEntryType stockType) { return fb.group({ _productVariantKey: FormControl(), @@ -76,6 +75,7 @@ class _StockDetailsPageState extends LocalizedState { void initState() { clearQRCodes(); transportTypes = InventorySingleton().transportType; + context.read().add(const LoadLocationEvent()); super.initState(); } @@ -182,6 +182,11 @@ class _StockDetailsPageState extends LocalizedState { builder: (context, form, child) { return BlocBuilder( builder: (context, scannerState) { + if (scannerState.barCodes.isNotEmpty) { + scannedResources.clear(); + scannedResources.addAll(scannerState.barCodes); + } + return ScrollableContent( header: Column(children: [ BackNavigationHelpHeaderWidget( @@ -211,8 +216,20 @@ class _StockDetailsPageState extends LocalizedState { 0, ), child: ReactiveFormConsumer( - builder: (context, form, child) => - DigitElevatedButton( + builder: (context, form, child) { + if (form + .control(_deliveryTeamKey) + .value + .toString() + .isEmpty || + form.control(_deliveryTeamKey).value == null || + scannerState.qrCodes.isNotEmpty) { + form.control(_deliveryTeamKey).value = + scannerState.qrCodes.isNotEmpty + ? scannerState.qrCodes.last + : ''; + } + return DigitElevatedButton( onPressed: !form.valid ? null : () async { @@ -275,246 +292,280 @@ class _StockDetailsPageState extends LocalizedState { } else { FocusManager.instance.primaryFocus ?.unfocus(); + context + .read() + .add(const LoadLocationEvent()); + DigitComponentsUtils() + .showLocationCapturingDialog( + context, + localizations.translate(i18 + .common.locationCapturing), + DigitSyncDialogType.inProgress); + Future.delayed( + const Duration(seconds: 2), + () async { + DigitComponentsUtils() + .hideLocationDialog(context); + final bloc = + context.read(); - final bloc = - context.read(); - - final productVariant = form - .control(_productVariantKey) - .value as ProductVariantModel; - - switch (entryType) { - case StockRecordEntryType.receipt: - transactionReason = - TransactionReason.received - .toValue(); - break; - case StockRecordEntryType.dispatch: - transactionReason = null; - break; - case StockRecordEntryType.returned: - transactionReason = - TransactionReason.returned - .toValue(); - break; - default: - transactionReason = form - .control( - _transactionReasonKey, - ) - .value as String?; - break; - } + final productVariant = form + .control(_productVariantKey) + .value as ProductVariantModel; - final quantity = form - .control(_transactionQuantityKey) - .value; + switch (entryType) { + case StockRecordEntryType.receipt: + transactionReason = + TransactionReason.received + .toValue(); + break; + case StockRecordEntryType.dispatch: + transactionReason = null; + break; + case StockRecordEntryType.returned: + transactionReason = + TransactionReason.returned + .toValue(); + break; + default: + transactionReason = form + .control( + _transactionReasonKey, + ) + .value as String?; + break; + } - final waybillNumber = form - .control(_waybillNumberKey) - .value as String?; + final quantity = form + .control(_transactionQuantityKey) + .value; - final waybillQuantity = form - .control(_waybillQuantityKey) - .value as String?; + final waybillNumber = form + .control(_waybillNumberKey) + .value as String?; - final vehicleNumber = form - .control(_vehicleNumberKey) - .value as String?; + final waybillQuantity = form + .control(_waybillQuantityKey) + .value as String?; - final lat = locationState.latitude; - final lng = locationState.longitude; + final vehicleNumber = form + .control(_vehicleNumberKey) + .value as String?; - final hasLocationData = - lat != null && lng != null; + final lat = locationState.latitude; + final lng = locationState.longitude; - final comments = form - .control(_commentsKey) - .value as String?; + final hasLocationData = + lat != null && lng != null; - final deliveryTeamName = form - .control(_deliveryTeamKey) - .value as String?; + final comments = form + .control(_commentsKey) + .value as String?; - String? senderId; - String? senderType; - String? receiverId; - String? receiverType; + final deliveryTeamName = form + .control(_deliveryTeamKey) + .value as String?; - final primaryType = - BlocProvider.of( - context, - ).state.primaryType; + String? senderId; + String? senderType; + String? receiverId; + String? receiverType; - final primaryId = - BlocProvider.of( - context, - ).state.primaryId; - - switch (entryType) { - case StockRecordEntryType.receipt: - case StockRecordEntryType.loss: - case StockRecordEntryType.damaged: - if (deliveryTeamSelected) { - senderId = deliveryTeamName; - senderType = "STAFF"; - } else { - senderId = secondaryParty?.id; - senderType = "WAREHOUSE"; - } - receiverId = primaryId; - receiverType = primaryType; - - break; - case StockRecordEntryType.dispatch: - case StockRecordEntryType.returned: - if (deliveryTeamSelected) { - receiverId = deliveryTeamName; - receiverType = "STAFF"; - } else { - receiverId = secondaryParty?.id; - receiverType = "WAREHOUSE"; - } - senderId = primaryId; - senderType = primaryType; - break; - } + final primaryType = + BlocProvider.of( + context, + ).state.primaryType; - final stockModel = StockModel( - clientReferenceId: IdGen.i.identifier, - productVariantId: productVariant.id, - transactionReason: transactionReason, - transactionType: transactionType, - referenceId: stockState.projectId, - referenceIdType: 'PROJECT', - quantity: quantity.toString(), - waybillNumber: waybillNumber, - receiverId: receiverId, - receiverType: receiverType, - senderId: senderId, - senderType: senderType, - auditDetails: AuditDetails( - createdBy: InventorySingleton() - .loggedInUserUuid, - createdTime: context - .millisecondsSinceEpoch(), - ), - clientAuditDetails: - ClientAuditDetails( - createdBy: InventorySingleton() - .loggedInUserUuid, - createdTime: context - .millisecondsSinceEpoch(), - lastModifiedBy: InventorySingleton() - .loggedInUserUuid, - lastModifiedTime: context - .millisecondsSinceEpoch(), - ), - additionalFields: [ - waybillQuantity, - vehicleNumber, - comments, - ].any((element) => - element != null) || - hasLocationData - ? StockAdditionalFields( - version: 1, - fields: [ - if (waybillQuantity != - null && - waybillQuantity - .trim() - .isNotEmpty) - AdditionalField( - 'waybill_quantity', - waybillQuantity, - ), - if (vehicleNumber != null && - vehicleNumber - .trim() - .isNotEmpty) - AdditionalField( - 'vehicle_number', - vehicleNumber, - ), - if (comments != null && - comments - .trim() - .isNotEmpty) - AdditionalField( - 'comments', - comments, - ), - if (deliveryTeamName != - null && - deliveryTeamName - .trim() - .isNotEmpty) - AdditionalField( - 'deliveryTeam', - deliveryTeamName, - ), - if (hasLocationData) ...[ - AdditionalField( - 'lat', - lat, - ), + final primaryId = + BlocProvider.of( + context, + ).state.primaryId; + + switch (entryType) { + case StockRecordEntryType.receipt: + case StockRecordEntryType.loss: + case StockRecordEntryType.damaged: + if (deliveryTeamSelected) { + senderId = deliveryTeamName; + senderType = "STAFF"; + } else { + senderId = secondaryParty?.id; + senderType = "WAREHOUSE"; + } + receiverId = primaryId; + receiverType = primaryType; + + break; + case StockRecordEntryType.dispatch: + case StockRecordEntryType.returned: + if (deliveryTeamSelected) { + receiverId = deliveryTeamName; + receiverType = "STAFF"; + } else { + receiverId = secondaryParty?.id; + receiverType = "WAREHOUSE"; + } + senderId = primaryId; + senderType = primaryType; + break; + } + + final stockModel = StockModel( + clientReferenceId: + IdGen.i.identifier, + productVariantId: productVariant.id, + transactionReason: + transactionReason, + transactionType: transactionType, + referenceId: stockState.projectId, + referenceIdType: 'PROJECT', + quantity: quantity.toString(), + waybillNumber: waybillNumber, + receiverId: receiverId, + receiverType: receiverType, + senderId: senderId, + senderType: senderType, + auditDetails: AuditDetails( + createdBy: InventorySingleton() + .loggedInUserUuid, + createdTime: context + .millisecondsSinceEpoch(), + ), + clientAuditDetails: + ClientAuditDetails( + createdBy: InventorySingleton() + .loggedInUserUuid, + createdTime: context + .millisecondsSinceEpoch(), + lastModifiedBy: + InventorySingleton() + .loggedInUserUuid, + lastModifiedTime: context + .millisecondsSinceEpoch(), + ), + additionalFields: [ + waybillQuantity, + vehicleNumber, + comments, + ].any((element) => + element != null) || + hasLocationData + ? StockAdditionalFields( + version: 1, + fields: [ AdditionalField( - 'lng', - lng, + InventoryManagementEnums + .name + .toValue(), + InventorySingleton() + .loggedInUser + ?.name, ), + if (waybillQuantity != + null && + waybillQuantity + .trim() + .isNotEmpty) + AdditionalField( + 'waybill_quantity', + waybillQuantity, + ), + if (vehicleNumber != + null && + vehicleNumber + .trim() + .isNotEmpty) + AdditionalField( + 'vehicle_number', + vehicleNumber, + ), + if (comments != null && + comments + .trim() + .isNotEmpty) + AdditionalField( + 'comments', + comments, + ), + if (deliveryTeamName != + null && + deliveryTeamName + .trim() + .isNotEmpty) + AdditionalField( + 'deliveryTeam', + deliveryTeamName, + ), + if (hasLocationData) ...[ + AdditionalField( + 'lat', + lat, + ), + AdditionalField( + 'lng', + lng, + ), + ], + if (scannerState + .barCodes.isNotEmpty) + addBarCodesToFields( + scannerState + .barCodes), ], - ], - ) - : null, - ); - - bloc.add( - RecordStockSaveStockDetailsEvent( - stockModel: stockModel, - ), - ); + ) + : null, + ); - final submit = - await DigitDialog.show( - context, - options: DigitDialogOptions( - key: const Key('submitDialog'), - titleText: localizations.translate( - i18.stockDetails.dialogTitle, - ), - contentText: - localizations.translate( - i18.stockDetails.dialogContent, + bloc.add( + RecordStockSaveStockDetailsEvent( + stockModel: stockModel, ), - primaryAction: DigitDialogActions( - label: localizations.translate( - i18.common.coreCommonSubmit, + ); + + final submit = + await DigitDialog.show( + context, + options: DigitDialogOptions( + key: const Key('submitDialog'), + titleText: + localizations.translate( + i18.stockDetails.dialogTitle, + ), + contentText: + localizations.translate( + i18.stockDetails.dialogContent, + ), + primaryAction: DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonSubmit, + ), + action: (context) { + Navigator.of( + context, + rootNavigator: true, + ).pop(true); + }, ), - action: (context) { - Navigator.of( + secondaryAction: + DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonCancel, + ), + action: (context) => + Navigator.of( context, rootNavigator: true, - ).pop(true); - }, - ), - secondaryAction: DigitDialogActions( - label: localizations.translate( - i18.common.coreCommonCancel, + ).pop(false), ), - action: (context) => Navigator.of( - context, - rootNavigator: true, - ).pop(false), ), - ), - ); - - if (submit ?? false) { - bloc.add( - const RecordStockCreateStockEntryEvent(), ); - } + + if (submit ?? false) { + bloc.add( + const RecordStockCreateStockEntryEvent(), + ); + } + }); } }, child: Center( @@ -523,8 +574,8 @@ class _StockDetailsPageState extends LocalizedState { .translate(i18.common.coreCommonSubmit), ), ), - ), - ), + ); + }), ), children: [ DigitCard( @@ -608,7 +659,7 @@ class _StockDetailsPageState extends LocalizedState { await context.router.push( InventoryFacilitySelectionRoute( facilities: - facilities)) + allFacilities)) as FacilityModel?; if (facility == null) return; @@ -664,7 +715,7 @@ class _StockDetailsPageState extends LocalizedState { final facility = await context.router.push( InventoryFacilitySelectionRoute( - facilities: facilities, + facilities: allFacilities, ), ) as FacilityModel?; @@ -926,14 +977,12 @@ class _StockDetailsPageState extends LocalizedState { ), ], ), - ...scannerState.barCodes - .map((e) => Align( - alignment: - Alignment.centerLeft, - child: Text(e.elements.values - .first.data - .toString()), - )) + ...scannedResources.map((e) => Align( + alignment: Alignment.centerLeft, + child: Text(e + .elements.values.first.data + .toString()), + )) ]) ], ), @@ -973,7 +1022,7 @@ class _StockDetailsPageState extends LocalizedState { /// /// @param barCodes The list of GS1Barcode objects to be processed. /// @return A map where the keys and values are joined by '|'. - Map addBarCodesToFields(List barCodes) { + AdditionalField addBarCodesToFields(List barCodes) { List keys = []; List values = []; for (var element in barCodes) { @@ -982,8 +1031,6 @@ class _StockDetailsPageState extends LocalizedState { values.add(e.value.data.toString()); } } - return { - keys.join('|'): values.join('|'), - }; + return AdditionalField(keys.join('|'), values.join('|')); } } diff --git a/packages/inventory_management/lib/pages/record_stock/warehouse_details.dart b/packages/inventory_management/lib/pages/record_stock/warehouse_details.dart index 209a131eb..de24d5850 100644 --- a/packages/inventory_management/lib/pages/record_stock/warehouse_details.dart +++ b/packages/inventory_management/lib/pages/record_stock/warehouse_details.dart @@ -25,10 +25,10 @@ class WarehouseDetailsPage extends LocalizedStatefulWidget { }); @override - State createState() => _WarehouseDetailsPageState(); + State createState() => WarehouseDetailsPageState(); } -class _WarehouseDetailsPageState extends LocalizedState { +class WarehouseDetailsPageState extends LocalizedState { static const _dateOfEntryKey = 'dateOfReceipt'; static const _administrativeUnitKey = 'administrativeUnit'; static const _warehouseKey = 'warehouse'; @@ -421,7 +421,7 @@ class _WarehouseDetailsPageState extends LocalizedState { builder: (context) => const DigitScannerPage( quantity: 1, - isGS1code: true, + isGS1code: false, singleValue: false, ), settings: const RouteSettings( diff --git a/packages/inventory_management/lib/pages/reports/report_details.dart b/packages/inventory_management/lib/pages/reports/report_details.dart index caec94613..19b1aef9d 100644 --- a/packages/inventory_management/lib/pages/reports/report_details.dart +++ b/packages/inventory_management/lib/pages/reports/report_details.dart @@ -35,10 +35,10 @@ class InventoryReportDetailsPage extends LocalizedStatefulWidget { @override State createState() => - _InventoryReportDetailsPageState(); + InventoryReportDetailsPageState(); } -class _InventoryReportDetailsPageState +class InventoryReportDetailsPageState extends LocalizedState { static const _productVariantKey = 'productVariant'; static const _facilityKey = 'facilityKey'; @@ -239,9 +239,6 @@ class _InventoryReportDetailsPageState selectedFacilityId = facility.id; }); - form - .control(_facilityKey) - .value = facility; stockReconciliationBloc.add( StockReconciliationSelectFacilityEvent( facility, diff --git a/packages/inventory_management/lib/pages/reports/report_selection.dart b/packages/inventory_management/lib/pages/reports/report_selection.dart index d5c364a3f..5f7cfd145 100644 --- a/packages/inventory_management/lib/pages/reports/report_selection.dart +++ b/packages/inventory_management/lib/pages/reports/report_selection.dart @@ -17,10 +17,10 @@ class InventoryReportSelectionPage extends LocalizedStatefulWidget { @override State createState() => - _InventoryReportSelectionPageState(); + InventoryReportSelectionPageState(); } -class _InventoryReportSelectionPageState +class InventoryReportSelectionPageState extends LocalizedState { @override void initState() { diff --git a/packages/inventory_management/lib/pages/stock_reconciliation/stock_reconciliation.dart b/packages/inventory_management/lib/pages/stock_reconciliation/stock_reconciliation.dart index af56c4331..54fce335d 100644 --- a/packages/inventory_management/lib/pages/stock_reconciliation/stock_reconciliation.dart +++ b/packages/inventory_management/lib/pages/stock_reconciliation/stock_reconciliation.dart @@ -28,10 +28,10 @@ class StockReconciliationPage extends LocalizedStatefulWidget { @override State createState() => - _StockReconciliationPageState(); + StockReconciliationPageState(); } -class _StockReconciliationPageState +class StockReconciliationPageState extends LocalizedState { static const _facilityKey = 'facility'; static const _productVariantKey = 'productVariant'; diff --git a/packages/inventory_management/lib/utils/i18_key_constants.dart b/packages/inventory_management/lib/utils/i18_key_constants.dart index f3f237bcc..b6fdc6cd4 100644 --- a/packages/inventory_management/lib/utils/i18_key_constants.dart +++ b/packages/inventory_management/lib/utils/i18_key_constants.dart @@ -103,6 +103,10 @@ class Common { String get scanBales => 'CORE_COMMON_SCAN_BALES'; String get ageInMonths => 'AGE_IN_MONTHS_LABEL'; + + String get locationCapturing => 'CAPTURING_LOCATION'; + String get locationCaptured => 'LOCATION_CAPTURED'; + String get ctaProceed => 'PROCEED'; } class AcknowledgementSuccess { diff --git a/packages/inventory_management/lib/utils/utils.dart b/packages/inventory_management/lib/utils/utils.dart index a6f676f55..ffc04f933 100644 --- a/packages/inventory_management/lib/utils/utils.dart +++ b/packages/inventory_management/lib/utils/utils.dart @@ -42,6 +42,7 @@ class InventorySingleton { // Various properties related to the inventory. String _projectId = ''; + UserModel? _loggedInUser; String? _loggedInUserUuid = ''; String? _boundaryName = ''; String? _tenantId = ''; @@ -52,18 +53,21 @@ class InventorySingleton { .offlineFirst; // Default to offline first persistence configuration // Sets the initial data for the inventory. - void setInitialData( - {String? loggedInUserUuid, - required String projectId, - required bool isDistributor, - required bool isWareHouseMgr, - List? transportTypes}) { + void setInitialData({ + String? loggedInUserUuid, + required String projectId, + required bool isDistributor, + required bool isWareHouseMgr, + List? transportTypes, + UserModel? loggedInUser, + }) { _projectId = projectId; _loggedInUserUuid = loggedInUserUuid; _transportType = transportTypes; _isDistributor = isDistributor; _isWareHouseMgr = isWareHouseMgr; _transportType = transportTypes; + _loggedInUser = loggedInUser; } void setPersistenceConfiguration(PersistenceConfiguration configuration) { @@ -87,4 +91,5 @@ class InventorySingleton { get transportType => _transportType; get tenantId => _tenantId; get persistenceConfiguration => _persistenceConfiguration; + UserModel? get loggedInUser => _loggedInUser; } diff --git a/packages/inventory_management/lib/widgets/reports/readonly_pluto_grid.dart b/packages/inventory_management/lib/widgets/reports/readonly_pluto_grid.dart index 75b789d1f..fd5d36d7d 100644 --- a/packages/inventory_management/lib/widgets/reports/readonly_pluto_grid.dart +++ b/packages/inventory_management/lib/widgets/reports/readonly_pluto_grid.dart @@ -28,11 +28,11 @@ class ReadonlyDigitGrid extends LocalizedStatefulWidget { /// Creating the state for ReadonlyDigitGrid @override - State createState() => _ReadonlyDigitGridState(); + State createState() => ReadonlyDigitGridState(); } /// State class for ReadonlyDigitGrid -class _ReadonlyDigitGridState extends LocalizedState { +class ReadonlyDigitGridState extends LocalizedState { @override Widget build(BuildContext context) { // Returns a PlutoGrid with the given configuration and data diff --git a/packages/inventory_management/pubspec.lock b/packages/inventory_management/pubspec.lock index d496c6efe..2773eed0f 100644 --- a/packages/inventory_management/pubspec.lock +++ b/packages/inventory_management/pubspec.lock @@ -420,26 +420,26 @@ packages: dependency: "direct main" description: name: digit_components - sha256: "53ee8c0a7c992c0e8d1c9c867b6cf1d52e1728200f4b4436943a5d6c5e4984c3" + sha256: "90e12017934343a197a0c25bec00e5fc28e19cfbf11e522798cc39719609612c" url: "https://pub.dev" source: hosted - version: "1.0.0+2" + version: "1.0.0+9" digit_data_model: dependency: "direct main" description: name: digit_data_model - sha256: "0e1ec8e4d2776fcc4a8118ac85043b8876466ec7399c14880f3d585ad3586ef6" + sha256: e1ea907e9cb7d521341325ac1b1b98fad8bd5e5ca1bab7f7c18ed02ccd2f2c2b url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" digit_scanner: dependency: "direct main" description: name: digit_scanner - sha256: a040c9c413436aeb953fdea3bc99ef618641189b06e8f155d84ac83ba8d40fd1 + sha256: "1f1fe3ca8f038a3c93cd52491cf72c0b0e45c88b14580243d47eac59672e67ea" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" dio: dependency: transitive description: diff --git a/packages/inventory_management/pubspec.yaml b/packages/inventory_management/pubspec.yaml index 5898cc07f..ce46fe227 100644 --- a/packages/inventory_management/pubspec.yaml +++ b/packages/inventory_management/pubspec.yaml @@ -1,6 +1,6 @@ name: inventory_management description: This package offers inventory management features, allowing users to view stock reports and perform inventory resource reconciliation. -version: 1.0.2 +version: 1.0.3+1 homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/master/packages/inventory_management repository: https://github.com/egovernments/health-campaign-field-worker-app @@ -11,7 +11,7 @@ environment: dependencies: flutter: sdk: flutter - digit_components: ^1.0.0+2 + digit_components: ^1.0.0+9 flutter_bloc: ^8.1.1 freezed_annotation: ^2.1.0 build_runner: ^2.2.1 @@ -29,10 +29,10 @@ dependencies: uuid: ^3.0.6 recase: ^4.1.0 pluto_grid: ^7.0.1 - digit_scanner: ^1.0.2 + digit_scanner: ^1.0.3 gs1_barcode_parser: ^1.0.5 auto_route: ^7.8.4 - digit_data_model: ^1.0.2 + digit_data_model: ^1.0.3 collection: ^1.16.0 dev_dependencies: diff --git a/packages/referral_reconciliation/pubspec.lock b/packages/referral_reconciliation/pubspec.lock index ae925fcfa..fc9b2461d 100644 --- a/packages/referral_reconciliation/pubspec.lock +++ b/packages/referral_reconciliation/pubspec.lock @@ -419,11 +419,10 @@ packages: digit_components: dependency: "direct main" description: - name: digit_components - sha256: "53ee8c0a7c992c0e8d1c9c867b6cf1d52e1728200f4b4436943a5d6c5e4984c3" - url: "https://pub.dev" - source: hosted - version: "1.0.0+2" + path: "../digit_components" + relative: true + source: path + version: "1.0.0+3" digit_data_model: dependency: "direct main" description: diff --git a/packages/registration_delivery/CHANGELOG.md b/packages/registration_delivery/CHANGELOG.md index fa5188825..1fb632260 100644 --- a/packages/registration_delivery/CHANGELOG.md +++ b/packages/registration_delivery/CHANGELOG.md @@ -1,38 +1,89 @@ -## 0.0.0-dev.1 +## 1.0.3 -* Registration and Delivery Initial Release +* IRS Campaign changes +* New HouseDetails screen to capture structure of the house +* New Summary page for registration and delivery +* Introduced Filter search which can be configured through MDMS +* Constructed a global query executor based on project type - Household and Individual +* Getting precise location on registry and delivery +* Updated digit_scanner, data_model package -## 0.0.0-dev.2 +## 1.0.3-dev.11 -* Boundary v2 Integrated, to use Boundary v1 0.0.0-dev.1 version can be used +* Updated search to include project id for individual and household -## 0.0.0-dev.3 +## 1.0.3-dev.10 -* Updated digit_data_model to latest version +* Removed stepper if number of deliveries is greater than 1 -## 0.0.0-dev.4 +## 1.0.3-dev.9 -* Added null check for fetching product variants +* Updated localization key +* Resolved taskStatus key from task table entity -## 0.0.0-dev.5 +## 1.0.3-dev.8 -* Facility dialog empty pop up fix on initial load +* Reverted 1.0.3-dev.7 -## 0.0.0-dev.6 +## 1.0.3-dev.7 -* Updated digit_scanner to latest version +* Updated status to taskStatus in Task model -## 0.0.0-dev.7 +## 1.0.3-dev.6 -* Fixed Duplicate routing issue +* Updated delivery status enums -## 1.0.0 +## 1.0.3-dev.5 -* Initial stable version +* Added count for filter search +* Bug fixes -## 1.0.0+1 +## 1.0.3-dev.4 -* Updated digit_showcase to latest version +* Cache build fix for registration_bloc + +## 1.0.3-dev.3 + +* Closed household flow change + + +## 1.0.3-dev.2 + +* Closed household search fixes +* Tasks status fixes on beneficiary card and overview page +* Updated digit_components and digit_scanner versions + +## 1.0.3-dev.1 + +* Fixed filter search bug fixes and improvements +* Updated task status on view_beneficiary card +* Implemented closed household flow filter and update + +## 0.0.0-dev.10 + +* Added pagination for filter search +* Updated PageState class to public for customization +* Updated digit_components + +## 0.0.0-dev.9 + +* Updated individual details file for exposing individual state +* Updated household_overview for BeneficiaryChecklistRoute + +## 0.0.0-dev.8 + +* Added query builder and registry updated changes +* Added New screens - house details + +## 1.0.2+1 + +* Get Precise location on Submitting latitude longitude details + +## 1.0.2 + +* Added try catch for local repository to handle db lock +* Localisation support added for missing fields +* Bug fixes and enhancements ## 1.0.1 @@ -41,8 +92,38 @@ * Added HouseholdDetailsBloc in registration_delivery_wrapper page * Updated digit_data_model to latest version -## 1.0.2 +## 1.0.0+1 -* Added try catch for local repository to handle db lock -* Localisation support added for missing fields -* Bug fixes and enhancements \ No newline at end of file +* Updated digit_showcase to latest version + +## 1.0.0 + +* Initial stable version + +## 0.0.0-dev.7 + +* Fixed Duplicate routing issue + +## 0.0.0-dev.6 + +* Updated digit_scanner to latest version + +## 0.0.0-dev.5 + +* Facility dialog empty pop up fix on initial load + +## 0.0.0-dev.4 + +* Added null check for fetching product variants + +## 0.0.0-dev.3 + +* Updated digit_data_model to latest version + +## 0.0.0-dev.2 + +* Boundary v2 Integrated, to use Boundary v1 0.0.0-dev.1 version can be used + +## 0.0.0-dev.1 + +* Registration and Delivery Initial Release \ No newline at end of file diff --git a/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.dart b/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.dart index 5f494565f..fce9aa60a 100644 --- a/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.dart +++ b/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.dart @@ -6,11 +6,13 @@ import 'package:digit_data_model/utils/typedefs.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:registration_delivery/models/entities/household_member.dart'; +import 'package:registration_delivery/models/entities/task.dart'; import '../../models/entities/household.dart'; import '../../models/entities/project_beneficiary.dart'; -import '../../utils/utils.dart'; +import '../../models/entities/status.dart'; import '../../utils/typedefs.dart'; +import '../../utils/utils.dart'; part 'beneficiary_registration.freezed.dart'; @@ -27,6 +29,8 @@ class BeneficiaryRegistrationBloc final ProjectBeneficiaryDataRepository projectBeneficiaryRepository; + final TaskDataRepository taskDataRepository; + final BeneficiaryType beneficiaryType; BeneficiaryRegistrationBloc( @@ -35,15 +39,18 @@ class BeneficiaryRegistrationBloc required this.householdRepository, required this.householdMemberRepository, required this.projectBeneficiaryRepository, + required this.taskDataRepository, required this.beneficiaryType, }) { on(_handleSaveAddress); + on(_handleSaveHouseDetails); on(_handleSaveHouseholdDetails); on(_handleSaveIndividualDetails); on(_handleCreate); on(_handleUpdateHousehold); on(_handleUpdateIndividual); on(_handleAddMember); + on(_handleSummary); } //_handleSaveAddress event can be used for saving address details to the form @@ -64,6 +71,24 @@ class BeneficiaryRegistrationBloc ); } + //_handleSaveHouseDetails event can be used for saving house details to the form + FutureOr _handleSaveHouseDetails( + BeneficiaryRegistrationSaveHouseDetailsEvent event, + BeneficiaryRegistrationEmitter emit, + ) async { + state.maybeMap( + orElse: () { + throw const InvalidRegistrationStateException(); + }, + editHousehold: (value) { + emit(value.copyWith(householdModel: event.model)); + }, + create: (value) { + emit(value.copyWith(householdModel: event.model)); + }, + ); + } + FutureOr _handleSaveHouseholdDetails( BeneficiaryRegistrationSaveHouseholdDetailsEvent event, BeneficiaryRegistrationEmitter emit, @@ -83,6 +108,12 @@ class BeneficiaryRegistrationBloc registrationDate: event.registrationDate, )); }, + summary: (value) { + emit(value.copyWith( + householdModel: event.household, + registrationDate: event.registrationDate, + )); + }, ); } @@ -108,6 +139,60 @@ class BeneficiaryRegistrationBloc ); } + FutureOr _handleSummary( + BeneficiaryRegistrationSummaryEvent event, + BeneficiaryRegistrationEmitter emit, + ) async { + await state.maybeMap( + orElse: () { + throw const InvalidRegistrationStateException(); + }, + create: (value) async { + final individual = value.individualModel; + final household = value.householdModel; + final address = value.addressModel; + final code = event.boundary.code; + final name = event.boundary.name; + final locality = code == null || name == null + ? null + : LocalityModel(code: code, name: name); + emit(BeneficiaryRegistrationSummaryState( + navigateToRoot: false, + householdModel: household?.copyWith( + address: address?.copyWith( + relatedClientReferenceId: household.clientReferenceId, + auditDetails: individual?.auditDetails, + clientAuditDetails: individual?.clientAuditDetails, + locality: locality, + )), + individualModel: individual, + projectBeneficiaryModel: ProjectBeneficiaryModel( + tag: event.tag, + rowVersion: 1, + tenantId: RegistrationDeliverySingleton().tenantId, + clientReferenceId: IdGen.i.identifier, + dateOfRegistration: DateTime.now().millisecondsSinceEpoch, + projectId: event.projectId, + beneficiaryClientReferenceId: + beneficiaryType == BeneficiaryType.individual + ? individual?.clientReferenceId + : household?.clientReferenceId, + clientAuditDetails: ClientAuditDetails( + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: event.userUuid, + createdBy: event.userUuid, + ), + auditDetails: AuditDetails( + createdBy: event.userUuid, + createdTime: DateTime.now().millisecondsSinceEpoch, + ), + ), + isHeadOfHousehold: value.isHeadOfHousehold)); + }, + ); + } + FutureOr _handleCreate( BeneficiaryRegistrationCreateEvent event, BeneficiaryRegistrationEmitter emit, @@ -116,6 +201,102 @@ class BeneficiaryRegistrationBloc orElse: () { throw const InvalidRegistrationStateException(); }, + persisted: (value) {}, + summary: (value) async { + if (event.navigateToSummary) { + emit(BeneficiaryRegistrationState.create( + addressModel: value.householdModel?.address, + householdModel: value.householdModel, + individualModel: value.individualModel, + projectBeneficiaryModel: value.projectBeneficiaryModel)); + } else { + final individual = value.individualModel; + final household = value.householdModel; + final address = value.householdModel?.address; + + if (individual == null) { + throw const InvalidRegistrationStateException( + 'Individual cannot be null', + ); + } else if (household == null) { + throw const InvalidRegistrationStateException( + 'Household cannot be null', + ); + } + + try { + final createdAt = DateTime.now().millisecondsSinceEpoch; + + emit(value.copyWith(loading: true)); + + final code = event.boundary.code; + final name = event.boundary.name; + + final locality = code == null || name == null + ? null + : LocalityModel(code: code, name: name); + await householdRepository.create( + household.copyWith( + address: address?.copyWith( + relatedClientReferenceId: household.clientReferenceId, + auditDetails: individual.auditDetails, + clientAuditDetails: individual.clientAuditDetails, + locality: locality, + ), + ), + ); + final initialModifiedAt = DateTime.now().millisecondsSinceEpoch; + await individualRepository.create( + individual.copyWith( + address: [ + address!.copyWith( + relatedClientReferenceId: individual.clientReferenceId, + auditDetails: individual.auditDetails, + clientAuditDetails: individual.clientAuditDetails, + locality: locality, + ), + ], + ), + ); + + await projectBeneficiaryRepository.create( + value.projectBeneficiaryModel!, + ); + + await householdMemberRepository.create( + HouseholdMemberModel( + householdClientReferenceId: household.clientReferenceId, + individualClientReferenceId: individual.clientReferenceId, + isHeadOfHousehold: value.isHeadOfHousehold, + tenantId: RegistrationDeliverySingleton().tenantId, + rowVersion: 1, + clientReferenceId: IdGen.i.identifier, + clientAuditDetails: ClientAuditDetails( + createdTime: createdAt, + lastModifiedTime: initialModifiedAt, + lastModifiedBy: event.userUuid, + createdBy: event.userUuid, + ), + auditDetails: AuditDetails( + createdBy: event.userUuid, + createdTime: createdAt, + ), + ), + ); + } catch (error) { + rethrow; + } finally { + emit( + BeneficiaryRegistrationPersistedState( + navigateToRoot: false, + householdModel: household, + addressModel: address, + individualModel: individual, + ), + ); + } + } + }, create: (value) async { final individual = value.individualModel; final household = value.householdModel; @@ -140,18 +321,17 @@ class BeneficiaryRegistrationBloc ); } - final createdAt = DateTime.now().millisecondsSinceEpoch; + try { + final createdAt = DateTime.now().millisecondsSinceEpoch; - emit(value.copyWith(loading: true)); + emit(value.copyWith(loading: true)); - try { final code = event.boundary.code; final name = event.boundary.name; final locality = code == null || name == null ? null : LocalityModel(code: code, name: name); - await householdRepository.create( household.copyWith( address: address.copyWith( @@ -177,28 +357,7 @@ class BeneficiaryRegistrationBloc ); await projectBeneficiaryRepository.create( - ProjectBeneficiaryModel( - tag: event.tag, - rowVersion: 1, - tenantId: RegistrationDeliverySingleton().tenantId, - clientReferenceId: IdGen.i.identifier, - dateOfRegistration: dateOfRegistration.millisecondsSinceEpoch, - projectId: event.projectId, - beneficiaryClientReferenceId: - beneficiaryType == BeneficiaryType.individual - ? individual.clientReferenceId - : household.clientReferenceId, - clientAuditDetails: ClientAuditDetails( - createdTime: createdAt, - lastModifiedTime: initialModifiedAt, - lastModifiedBy: event.userUuid, - createdBy: event.userUuid, - ), - auditDetails: AuditDetails( - createdBy: event.userUuid, - createdTime: createdAt, - ), - ), + value.projectBeneficiaryModel!, ); await householdMemberRepository.create( @@ -229,6 +388,8 @@ class BeneficiaryRegistrationBloc BeneficiaryRegistrationPersistedState( navigateToRoot: false, householdModel: household, + addressModel: address, + individualModel: individual, ), ); } @@ -248,13 +409,15 @@ class BeneficiaryRegistrationBloc emit(value.copyWith(loading: true)); try { await householdRepository.update( - value.householdModel.copyWith( + event.household.copyWith( clientAuditDetails: ClientAuditDetails( - createdBy: value.householdModel.clientAuditDetails!.createdBy, + createdBy: value.householdModel.clientAuditDetails?.createdBy ?? + value.householdModel.auditDetails!.createdBy.toString(), createdTime: - value.householdModel.clientAuditDetails!.createdTime, + value.householdModel.clientAuditDetails?.createdTime ?? + value.householdModel.auditDetails!.createdTime, lastModifiedBy: - value.householdModel.clientAuditDetails!.lastModifiedBy, + RegistrationDeliverySingleton().loggedInUserUuid, lastModifiedTime: DateTime.now().millisecondsSinceEpoch, ), memberCount: event.household.memberCount, @@ -266,7 +429,12 @@ class BeneficiaryRegistrationBloc ); final projectBeneficiary = await projectBeneficiaryRepository.search( ProjectBeneficiarySearchModel( - beneficiaryClientReferenceId: [event.household.clientReferenceId], + projectId: [RegistrationDeliverySingleton().projectId.toString()], + beneficiaryClientReferenceId: beneficiaryType == + BeneficiaryType + .individual ? getIndividualBeneficiaryClientReferenceId( + value.individualModel) + : [event.household.clientReferenceId], ), ); @@ -275,6 +443,49 @@ class BeneficiaryRegistrationBloc await projectBeneficiaryRepository .update(projectBeneficiary.first.copyWith(tag: event.tag)); } + + var task = await taskDataRepository.search(TaskSearchModel( + projectBeneficiaryClientReferenceId: + projectBeneficiary.map((e) => e.clientReferenceId).toList(), + )); + + if (task.isNotEmpty) { + if (task.last.status == Status.closeHousehold.toValue()) { + await taskDataRepository.update(task.last + .copyWith(status: Status.notAdministered.toValue())); + } + } + } else { + await projectBeneficiaryRepository.create(ProjectBeneficiaryModel( + rowVersion: 1, + clientReferenceId: IdGen.i.identifier, + dateOfRegistration: DateTime.now().millisecondsSinceEpoch, + projectId: RegistrationDeliverySingleton().projectId, + tenantId: RegistrationDeliverySingleton().tenantId, + beneficiaryClientReferenceId: + beneficiaryType == BeneficiaryType.individual + ? value.individualModel.first.clientReferenceId + : value.householdModel.clientReferenceId, + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + ), + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + createdTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + ))); } for (var element in value.individualModel) { @@ -292,16 +503,16 @@ class BeneficiaryRegistrationBloc ), ); } - } catch (error) { - rethrow; - } finally { emit(value.copyWith(loading: false)); emit( BeneficiaryRegistrationPersistedState( householdModel: value.householdModel, + isEdit: true, ), ); - } + } catch (error) { + rethrow; + } finally {} }, ); } @@ -340,6 +551,17 @@ class BeneficiaryRegistrationBloc await projectBeneficiaryRepository .update(projectBeneficiary.first.copyWith(tag: event.tag)); } + var task = await taskDataRepository.search(TaskSearchModel( + projectBeneficiaryClientReferenceId: + projectBeneficiary.map((e) => e.clientReferenceId).toList(), + )); + + if (task.isNotEmpty) { + if (task.last.status == Status.closeHousehold.toValue()) { + await taskDataRepository.update(task.last + .copyWith(status: Status.notAdministered.toValue())); + } + } } } catch (error) { rethrow; @@ -447,6 +669,11 @@ class BeneficiaryRegistrationBloc }, ); } + + getIndividualBeneficiaryClientReferenceId( + List individualModel) { + return individualModel.map((e) => e.clientReferenceId).toList(); + } } @freezed @@ -455,6 +682,10 @@ class BeneficiaryRegistrationEvent with _$BeneficiaryRegistrationEvent { AddressModel model, ) = BeneficiaryRegistrationSaveAddressEvent; + const factory BeneficiaryRegistrationEvent.saveHouseDetails({ + required HouseholdModel model, + }) = BeneficiaryRegistrationSaveHouseDetailsEvent; + const factory BeneficiaryRegistrationEvent.saveHouseholdDetails({ required HouseholdModel household, required DateTime registrationDate, @@ -488,12 +719,21 @@ class BeneficiaryRegistrationEvent with _$BeneficiaryRegistrationEvent { required AddressModel addressModel, }) = BeneficiaryRegistrationUpdateIndividualDetailsEvent; - const factory BeneficiaryRegistrationEvent.create({ - required String userUuid, - required String projectId, - required BoundaryModel boundary, - String? tag, - }) = BeneficiaryRegistrationCreateEvent; + const factory BeneficiaryRegistrationEvent.create( + {required String userUuid, + required String projectId, + required BoundaryModel boundary, + String? tag, + @Default(true) bool navigateToSummary}) = + BeneficiaryRegistrationCreateEvent; + + const factory BeneficiaryRegistrationEvent.summary( + {required String userUuid, + required String projectId, + required BoundaryModel boundary, + String? tag, + @Default(true) bool navigateToSummary}) = + BeneficiaryRegistrationSummaryEvent; const factory BeneficiaryRegistrationEvent.validate({ required String tag, @@ -506,6 +746,7 @@ class BeneficiaryRegistrationState with _$BeneficiaryRegistrationState { AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, @Default(false) bool loading, @@ -519,6 +760,7 @@ class BeneficiaryRegistrationState with _$BeneficiaryRegistrationState { required DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, @Default(false) bool loading, + IndividualModel? headOfHousehold, }) = BeneficiaryRegistrationEditHouseholdState; const factory BeneficiaryRegistrationState.editIndividual({ @@ -538,7 +780,25 @@ class BeneficiaryRegistrationState with _$BeneficiaryRegistrationState { const factory BeneficiaryRegistrationState.persisted({ @Default(true) bool navigateToRoot, required HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + @Default(false) bool loading, + @Default(false) bool isEdit, + @Default(false) bool isHeadOfHousehold, }) = BeneficiaryRegistrationPersistedState; + + const factory BeneficiaryRegistrationState.summary({ + @Default(true) bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + @Default(false) bool loading, + @Default(false) bool isHeadOfHousehold, + }) = BeneficiaryRegistrationSummaryState; } class InvalidRegistrationStateException implements Exception { diff --git a/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.freezed.dart b/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.freezed.dart index f3e0597d6..20219bfe7 100644 --- a/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.freezed.dart +++ b/packages/registration_delivery/lib/blocs/beneficiary_registration/beneficiary_registration.freezed.dart @@ -19,6 +19,7 @@ mixin _$BeneficiaryRegistrationEvent { @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -40,14 +41,18 @@ mixin _$BeneficiaryRegistrationEvent { HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -68,14 +73,18 @@ mixin _$BeneficiaryRegistrationEvent { HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -96,8 +105,11 @@ mixin _$BeneficiaryRegistrationEvent { HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) => @@ -106,6 +118,9 @@ mixin _$BeneficiaryRegistrationEvent { TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -121,6 +136,8 @@ mixin _$BeneficiaryRegistrationEvent { BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) => throw _privateConstructorUsedError; @@ -128,6 +145,8 @@ mixin _$BeneficiaryRegistrationEvent { TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -139,6 +158,7 @@ mixin _$BeneficiaryRegistrationEvent { BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) => throw _privateConstructorUsedError; @@ -146,6 +166,8 @@ mixin _$BeneficiaryRegistrationEvent { TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -156,6 +178,7 @@ mixin _$BeneficiaryRegistrationEvent { TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) => @@ -255,6 +278,7 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -276,8 +300,11 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return saveAddress(model); @@ -287,6 +314,7 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -307,8 +335,11 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return saveAddress?.call(model); @@ -318,6 +349,7 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -338,8 +370,11 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -354,6 +389,9 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -369,6 +407,8 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return saveAddress(this); @@ -379,6 +419,8 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -390,6 +432,7 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return saveAddress?.call(this); @@ -400,6 +443,8 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -410,6 +455,7 @@ class _$BeneficiaryRegistrationSaveAddressEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -432,6 +478,284 @@ abstract class BeneficiaryRegistrationSaveAddressEvent get copyWith => throw _privateConstructorUsedError; } +/// @nodoc +abstract class _$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWith< + $Res> { + factory _$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWith( + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl value, + $Res Function(_$BeneficiaryRegistrationSaveHouseDetailsEventImpl) + then) = + __$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWithImpl<$Res>; + @useResult + $Res call({HouseholdModel model}); +} + +/// @nodoc +class __$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWithImpl<$Res> + extends _$BeneficiaryRegistrationEventCopyWithImpl<$Res, + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl> + implements + _$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWith<$Res> { + __$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWithImpl( + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl _value, + $Res Function(_$BeneficiaryRegistrationSaveHouseDetailsEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? model = null, + }) { + return _then(_$BeneficiaryRegistrationSaveHouseDetailsEventImpl( + model: null == model + ? _value.model + : model // ignore: cast_nullable_to_non_nullable + as HouseholdModel, + )); + } +} + +/// @nodoc + +class _$BeneficiaryRegistrationSaveHouseDetailsEventImpl + implements BeneficiaryRegistrationSaveHouseDetailsEvent { + const _$BeneficiaryRegistrationSaveHouseDetailsEventImpl( + {required this.model}); + + @override + final HouseholdModel model; + + @override + String toString() { + return 'BeneficiaryRegistrationEvent.saveHouseDetails(model: $model)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BeneficiaryRegistrationSaveHouseDetailsEventImpl && + (identical(other.model, model) || other.model == model)); + } + + @override + int get hashCode => Object.hash(runtimeType, model); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWith< + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl> + get copyWith => + __$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWithImpl< + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl>( + this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, + required TResult Function( + HouseholdModel household, DateTime registrationDate) + saveHouseholdDetails, + required TResult Function(IndividualModel model, bool isHeadOfHousehold) + saveIndividualDetails, + required TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType) + addMember, + required TResult Function( + HouseholdModel household, AddressModel? addressModel, String? tag) + updateHouseholdDetails, + required TResult Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel) + updateIndividualDetails, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, + required TResult Function(String tag) validate, + }) { + return saveHouseDetails(model); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, + TResult? Function(HouseholdModel household, DateTime registrationDate)? + saveHouseholdDetails, + TResult? Function(IndividualModel model, bool isHeadOfHousehold)? + saveIndividualDetails, + TResult? Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType)? + addMember, + TResult? Function( + HouseholdModel household, AddressModel? addressModel, String? tag)? + updateHouseholdDetails, + TResult? Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel)? + updateIndividualDetails, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, + TResult? Function(String tag)? validate, + }) { + return saveHouseDetails?.call(model); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, + TResult Function(HouseholdModel household, DateTime registrationDate)? + saveHouseholdDetails, + TResult Function(IndividualModel model, bool isHeadOfHousehold)? + saveIndividualDetails, + TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType)? + addMember, + TResult Function( + HouseholdModel household, AddressModel? addressModel, String? tag)? + updateHouseholdDetails, + TResult Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel)? + updateIndividualDetails, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, + TResult Function(String tag)? validate, + required TResult orElse(), + }) { + if (saveHouseDetails != null) { + return saveHouseDetails(model); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) + saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, + required TResult Function( + BeneficiaryRegistrationSaveHouseholdDetailsEvent value) + saveHouseholdDetails, + required TResult Function( + BeneficiaryRegistrationSaveIndividualDetailsEvent value) + saveIndividualDetails, + required TResult Function(BeneficiaryRegistrationAddMemberEvent value) + addMember, + required TResult Function( + BeneficiaryRegistrationUpdateHouseholdDetailsEvent value) + updateHouseholdDetails, + required TResult Function( + BeneficiaryRegistrationUpdateIndividualDetailsEvent value) + updateIndividualDetails, + required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, + required TResult Function(BeneficiaryRegistrationTagEvent value) validate, + }) { + return saveHouseDetails(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? + saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, + TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? + saveHouseholdDetails, + TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? + saveIndividualDetails, + TResult? Function(BeneficiaryRegistrationAddMemberEvent value)? addMember, + TResult? Function(BeneficiaryRegistrationUpdateHouseholdDetailsEvent value)? + updateHouseholdDetails, + TResult? Function( + BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? + updateIndividualDetails, + TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, + TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, + }) { + return saveHouseDetails?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? + saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, + TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? + saveHouseholdDetails, + TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? + saveIndividualDetails, + TResult Function(BeneficiaryRegistrationAddMemberEvent value)? addMember, + TResult Function(BeneficiaryRegistrationUpdateHouseholdDetailsEvent value)? + updateHouseholdDetails, + TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? + updateIndividualDetails, + TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, + TResult Function(BeneficiaryRegistrationTagEvent value)? validate, + required TResult orElse(), + }) { + if (saveHouseDetails != null) { + return saveHouseDetails(this); + } + return orElse(); + } +} + +abstract class BeneficiaryRegistrationSaveHouseDetailsEvent + implements BeneficiaryRegistrationEvent { + const factory BeneficiaryRegistrationSaveHouseDetailsEvent( + {required final HouseholdModel model}) = + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl; + + HouseholdModel get model; + @JsonKey(ignore: true) + _$$BeneficiaryRegistrationSaveHouseDetailsEventImplCopyWith< + _$BeneficiaryRegistrationSaveHouseDetailsEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + /// @nodoc abstract class _$$BeneficiaryRegistrationSaveHouseholdDetailsEventImplCopyWith< $Res> { @@ -521,6 +845,7 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -542,8 +867,11 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return saveHouseholdDetails(household, registrationDate); @@ -553,6 +881,7 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -573,8 +902,11 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return saveHouseholdDetails?.call(household, registrationDate); @@ -584,6 +916,7 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -604,8 +937,11 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -620,6 +956,9 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -635,6 +974,8 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return saveHouseholdDetails(this); @@ -645,6 +986,8 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -656,6 +999,7 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return saveHouseholdDetails?.call(this); @@ -666,6 +1010,8 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -676,6 +1022,7 @@ class _$BeneficiaryRegistrationSaveHouseholdDetailsEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -791,6 +1138,7 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -812,8 +1160,11 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return saveIndividualDetails(model, isHeadOfHousehold); @@ -823,6 +1174,7 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -843,8 +1195,11 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return saveIndividualDetails?.call(model, isHeadOfHousehold); @@ -854,6 +1209,7 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -874,8 +1230,11 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -890,6 +1249,9 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -905,6 +1267,8 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return saveIndividualDetails(this); @@ -915,6 +1279,8 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -926,6 +1292,7 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return saveIndividualDetails?.call(this); @@ -936,6 +1303,8 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -946,6 +1315,7 @@ class _$BeneficiaryRegistrationSaveIndividualDetailsEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -1111,6 +1481,7 @@ class _$BeneficiaryRegistrationAddMemberEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -1132,8 +1503,11 @@ class _$BeneficiaryRegistrationAddMemberEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return addMember(householdModel, individualModel, addressModel, userUuid, @@ -1144,6 +1518,7 @@ class _$BeneficiaryRegistrationAddMemberEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1164,8 +1539,11 @@ class _$BeneficiaryRegistrationAddMemberEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return addMember?.call(householdModel, individualModel, addressModel, @@ -1176,6 +1554,7 @@ class _$BeneficiaryRegistrationAddMemberEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1196,8 +1575,11 @@ class _$BeneficiaryRegistrationAddMemberEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -1213,6 +1595,9 @@ class _$BeneficiaryRegistrationAddMemberEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -1228,6 +1613,8 @@ class _$BeneficiaryRegistrationAddMemberEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return addMember(this); @@ -1238,6 +1625,8 @@ class _$BeneficiaryRegistrationAddMemberEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1249,6 +1638,7 @@ class _$BeneficiaryRegistrationAddMemberEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return addMember?.call(this); @@ -1259,6 +1649,8 @@ class _$BeneficiaryRegistrationAddMemberEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1269,6 +1661,7 @@ class _$BeneficiaryRegistrationAddMemberEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -1405,6 +1798,7 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -1426,8 +1820,11 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return updateHouseholdDetails(household, addressModel, tag); @@ -1437,6 +1834,7 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1457,8 +1855,11 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return updateHouseholdDetails?.call(household, addressModel, tag); @@ -1468,6 +1869,7 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1488,8 +1890,11 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -1504,6 +1909,9 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -1519,6 +1927,8 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return updateHouseholdDetails(this); @@ -1529,6 +1939,8 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1540,6 +1952,7 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return updateHouseholdDetails?.call(this); @@ -1550,6 +1963,8 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1560,6 +1975,7 @@ class _$BeneficiaryRegistrationUpdateHouseholdDetailsEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -1704,6 +2120,7 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -1725,8 +2142,11 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { return updateIndividualDetails(model, tag, householdModel, addressModel); @@ -1736,6 +2156,7 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1756,8 +2177,11 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { return updateIndividualDetails?.call( @@ -1768,6 +2192,7 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -1788,8 +2213,11 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { @@ -1804,6 +2232,9 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -1819,6 +2250,8 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return updateIndividualDetails(this); @@ -1829,6 +2262,8 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1840,6 +2275,7 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return updateIndividualDetails?.call(this); @@ -1850,6 +2286,8 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -1860,6 +2298,7 @@ class _$BeneficiaryRegistrationUpdateIndividualDetailsEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -1897,7 +2336,11 @@ abstract class _$$BeneficiaryRegistrationCreateEventImplCopyWith<$Res> { __$$BeneficiaryRegistrationCreateEventImplCopyWithImpl<$Res>; @useResult $Res call( - {String userUuid, String projectId, BoundaryModel boundary, String? tag}); + {String userUuid, + String projectId, + BoundaryModel boundary, + String? tag, + bool navigateToSummary}); } /// @nodoc @@ -1917,6 +2360,7 @@ class __$$BeneficiaryRegistrationCreateEventImplCopyWithImpl<$Res> Object? projectId = null, Object? boundary = null, Object? tag = freezed, + Object? navigateToSummary = null, }) { return _then(_$BeneficiaryRegistrationCreateEventImpl( userUuid: null == userUuid @@ -1935,6 +2379,10 @@ class __$$BeneficiaryRegistrationCreateEventImplCopyWithImpl<$Res> ? _value.tag : tag // ignore: cast_nullable_to_non_nullable as String?, + navigateToSummary: null == navigateToSummary + ? _value.navigateToSummary + : navigateToSummary // ignore: cast_nullable_to_non_nullable + as bool, )); } } @@ -1947,7 +2395,8 @@ class _$BeneficiaryRegistrationCreateEventImpl {required this.userUuid, required this.projectId, required this.boundary, - this.tag}); + this.tag, + this.navigateToSummary = true}); @override final String userUuid; @@ -1957,10 +2406,13 @@ class _$BeneficiaryRegistrationCreateEventImpl final BoundaryModel boundary; @override final String? tag; + @override + @JsonKey() + final bool navigateToSummary; @override String toString() { - return 'BeneficiaryRegistrationEvent.create(userUuid: $userUuid, projectId: $projectId, boundary: $boundary, tag: $tag)'; + return 'BeneficiaryRegistrationEvent.create(userUuid: $userUuid, projectId: $projectId, boundary: $boundary, tag: $tag, navigateToSummary: $navigateToSummary)'; } @override @@ -1974,12 +2426,14 @@ class _$BeneficiaryRegistrationCreateEventImpl other.projectId == projectId) && (identical(other.boundary, boundary) || other.boundary == boundary) && - (identical(other.tag, tag) || other.tag == tag)); + (identical(other.tag, tag) || other.tag == tag) && + (identical(other.navigateToSummary, navigateToSummary) || + other.navigateToSummary == navigateToSummary)); } @override - int get hashCode => - Object.hash(runtimeType, userUuid, projectId, boundary, tag); + int get hashCode => Object.hash( + runtimeType, userUuid, projectId, boundary, tag, navigateToSummary); @JsonKey(ignore: true) @override @@ -1993,6 +2447,7 @@ class _$BeneficiaryRegistrationCreateEventImpl @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -2014,17 +2469,21 @@ class _$BeneficiaryRegistrationCreateEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { - return create(userUuid, projectId, boundary, tag); + return create(userUuid, projectId, boundary, tag, navigateToSummary); } @override @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -2045,17 +2504,21 @@ class _$BeneficiaryRegistrationCreateEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { - return create?.call(userUuid, projectId, boundary, tag); + return create?.call(userUuid, projectId, boundary, tag, navigateToSummary); } @override @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -2076,13 +2539,16 @@ class _$BeneficiaryRegistrationCreateEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { if (create != null) { - return create(userUuid, projectId, boundary, tag); + return create(userUuid, projectId, boundary, tag, navigateToSummary); } return orElse(); } @@ -2092,6 +2558,9 @@ class _$BeneficiaryRegistrationCreateEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -2107,6 +2576,8 @@ class _$BeneficiaryRegistrationCreateEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { return create(this); @@ -2117,6 +2588,8 @@ class _$BeneficiaryRegistrationCreateEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -2128,6 +2601,7 @@ class _$BeneficiaryRegistrationCreateEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { return create?.call(this); @@ -2138,6 +2612,8 @@ class _$BeneficiaryRegistrationCreateEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -2148,6 +2624,7 @@ class _$BeneficiaryRegistrationCreateEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { @@ -2164,12 +2641,14 @@ abstract class BeneficiaryRegistrationCreateEvent {required final String userUuid, required final String projectId, required final BoundaryModel boundary, - final String? tag}) = _$BeneficiaryRegistrationCreateEventImpl; + final String? tag, + final bool navigateToSummary}) = _$BeneficiaryRegistrationCreateEventImpl; String get userUuid; String get projectId; BoundaryModel get boundary; String? get tag; + bool get navigateToSummary; @JsonKey(ignore: true) _$$BeneficiaryRegistrationCreateEventImplCopyWith< _$BeneficiaryRegistrationCreateEventImpl> @@ -2177,76 +2656,125 @@ abstract class BeneficiaryRegistrationCreateEvent } /// @nodoc -abstract class _$$BeneficiaryRegistrationTagEventImplCopyWith<$Res> { - factory _$$BeneficiaryRegistrationTagEventImplCopyWith( - _$BeneficiaryRegistrationTagEventImpl value, - $Res Function(_$BeneficiaryRegistrationTagEventImpl) then) = - __$$BeneficiaryRegistrationTagEventImplCopyWithImpl<$Res>; +abstract class _$$BeneficiaryRegistrationSummaryEventImplCopyWith<$Res> { + factory _$$BeneficiaryRegistrationSummaryEventImplCopyWith( + _$BeneficiaryRegistrationSummaryEventImpl value, + $Res Function(_$BeneficiaryRegistrationSummaryEventImpl) then) = + __$$BeneficiaryRegistrationSummaryEventImplCopyWithImpl<$Res>; @useResult - $Res call({String tag}); + $Res call( + {String userUuid, + String projectId, + BoundaryModel boundary, + String? tag, + bool navigateToSummary}); } /// @nodoc -class __$$BeneficiaryRegistrationTagEventImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationSummaryEventImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationEventCopyWithImpl<$Res, - _$BeneficiaryRegistrationTagEventImpl> - implements _$$BeneficiaryRegistrationTagEventImplCopyWith<$Res> { - __$$BeneficiaryRegistrationTagEventImplCopyWithImpl( - _$BeneficiaryRegistrationTagEventImpl _value, - $Res Function(_$BeneficiaryRegistrationTagEventImpl) _then) + _$BeneficiaryRegistrationSummaryEventImpl> + implements _$$BeneficiaryRegistrationSummaryEventImplCopyWith<$Res> { + __$$BeneficiaryRegistrationSummaryEventImplCopyWithImpl( + _$BeneficiaryRegistrationSummaryEventImpl _value, + $Res Function(_$BeneficiaryRegistrationSummaryEventImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ - Object? tag = null, + Object? userUuid = null, + Object? projectId = null, + Object? boundary = null, + Object? tag = freezed, + Object? navigateToSummary = null, }) { - return _then(_$BeneficiaryRegistrationTagEventImpl( - tag: null == tag + return _then(_$BeneficiaryRegistrationSummaryEventImpl( + userUuid: null == userUuid + ? _value.userUuid + : userUuid // ignore: cast_nullable_to_non_nullable + as String, + projectId: null == projectId + ? _value.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + boundary: null == boundary + ? _value.boundary + : boundary // ignore: cast_nullable_to_non_nullable + as BoundaryModel, + tag: freezed == tag ? _value.tag : tag // ignore: cast_nullable_to_non_nullable - as String, + as String?, + navigateToSummary: null == navigateToSummary + ? _value.navigateToSummary + : navigateToSummary // ignore: cast_nullable_to_non_nullable + as bool, )); } } /// @nodoc -class _$BeneficiaryRegistrationTagEventImpl - implements BeneficiaryRegistrationTagEvent { - const _$BeneficiaryRegistrationTagEventImpl({required this.tag}); +class _$BeneficiaryRegistrationSummaryEventImpl + implements BeneficiaryRegistrationSummaryEvent { + const _$BeneficiaryRegistrationSummaryEventImpl( + {required this.userUuid, + required this.projectId, + required this.boundary, + this.tag, + this.navigateToSummary = true}); @override - final String tag; + final String userUuid; + @override + final String projectId; + @override + final BoundaryModel boundary; + @override + final String? tag; + @override + @JsonKey() + final bool navigateToSummary; @override String toString() { - return 'BeneficiaryRegistrationEvent.validate(tag: $tag)'; + return 'BeneficiaryRegistrationEvent.summary(userUuid: $userUuid, projectId: $projectId, boundary: $boundary, tag: $tag, navigateToSummary: $navigateToSummary)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationTagEventImpl && - (identical(other.tag, tag) || other.tag == tag)); + other is _$BeneficiaryRegistrationSummaryEventImpl && + (identical(other.userUuid, userUuid) || + other.userUuid == userUuid) && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + (identical(other.boundary, boundary) || + other.boundary == boundary) && + (identical(other.tag, tag) || other.tag == tag) && + (identical(other.navigateToSummary, navigateToSummary) || + other.navigateToSummary == navigateToSummary)); } @override - int get hashCode => Object.hash(runtimeType, tag); + int get hashCode => Object.hash( + runtimeType, userUuid, projectId, boundary, tag, navigateToSummary); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationTagEventImplCopyWith< - _$BeneficiaryRegistrationTagEventImpl> - get copyWith => __$$BeneficiaryRegistrationTagEventImplCopyWithImpl< - _$BeneficiaryRegistrationTagEventImpl>(this, _$identity); + _$$BeneficiaryRegistrationSummaryEventImplCopyWith< + _$BeneficiaryRegistrationSummaryEventImpl> + get copyWith => __$$BeneficiaryRegistrationSummaryEventImplCopyWithImpl< + _$BeneficiaryRegistrationSummaryEventImpl>(this, _$identity); @override @optionalTypeArgs TResult when({ required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( HouseholdModel household, DateTime registrationDate) saveHouseholdDetails, @@ -2268,17 +2796,21 @@ class _$BeneficiaryRegistrationTagEventImpl HouseholdModel householdModel, AddressModel addressModel) updateIndividualDetails, required TResult Function(String userUuid, String projectId, - BoundaryModel boundary, String? tag) + BoundaryModel boundary, String? tag, bool navigateToSummary) create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, required TResult Function(String tag) validate, }) { - return validate(tag); + return summary(userUuid, projectId, boundary, tag, navigateToSummary); } @override @optionalTypeArgs TResult? whenOrNull({ TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, TResult? Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult? Function(IndividualModel model, bool isHeadOfHousehold)? @@ -2299,17 +2831,21 @@ class _$BeneficiaryRegistrationTagEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult? Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult? Function(String tag)? validate, }) { - return validate?.call(tag); + return summary?.call(userUuid, projectId, boundary, tag, navigateToSummary); } @override @optionalTypeArgs TResult maybeWhen({ TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, TResult Function(HouseholdModel household, DateTime registrationDate)? saveHouseholdDetails, TResult Function(IndividualModel model, bool isHeadOfHousehold)? @@ -2330,13 +2866,16 @@ class _$BeneficiaryRegistrationTagEventImpl HouseholdModel householdModel, AddressModel addressModel)? updateIndividualDetails, TResult Function(String userUuid, String projectId, BoundaryModel boundary, - String? tag)? + String? tag, bool navigateToSummary)? create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, TResult Function(String tag)? validate, required TResult orElse(), }) { - if (validate != null) { - return validate(tag); + if (summary != null) { + return summary(userUuid, projectId, boundary, tag, navigateToSummary); } return orElse(); } @@ -2346,6 +2885,9 @@ class _$BeneficiaryRegistrationTagEventImpl TResult map({ required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, required TResult Function( BeneficiaryRegistrationSaveHouseholdDetailsEvent value) saveHouseholdDetails, @@ -2361,9 +2903,11 @@ class _$BeneficiaryRegistrationTagEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value) updateIndividualDetails, required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, required TResult Function(BeneficiaryRegistrationTagEvent value) validate, }) { - return validate(this); + return summary(this); } @override @@ -2371,6 +2915,8 @@ class _$BeneficiaryRegistrationTagEventImpl TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -2382,9 +2928,10 @@ class _$BeneficiaryRegistrationTagEventImpl BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, }) { - return validate?.call(this); + return summary?.call(this); } @override @@ -2392,6 +2939,8 @@ class _$BeneficiaryRegistrationTagEventImpl TResult maybeMap({ TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? saveHouseholdDetails, TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? @@ -2402,116 +2951,881 @@ class _$BeneficiaryRegistrationTagEventImpl TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? updateIndividualDetails, TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, TResult Function(BeneficiaryRegistrationTagEvent value)? validate, required TResult orElse(), }) { - if (validate != null) { - return validate(this); + if (summary != null) { + return summary(this); } return orElse(); } } -abstract class BeneficiaryRegistrationTagEvent +abstract class BeneficiaryRegistrationSummaryEvent implements BeneficiaryRegistrationEvent { - const factory BeneficiaryRegistrationTagEvent({required final String tag}) = - _$BeneficiaryRegistrationTagEventImpl; + const factory BeneficiaryRegistrationSummaryEvent( + {required final String userUuid, + required final String projectId, + required final BoundaryModel boundary, + final String? tag, + final bool navigateToSummary}) = + _$BeneficiaryRegistrationSummaryEventImpl; - String get tag; + String get userUuid; + String get projectId; + BoundaryModel get boundary; + String? get tag; + bool get navigateToSummary; @JsonKey(ignore: true) - _$$BeneficiaryRegistrationTagEventImplCopyWith< - _$BeneficiaryRegistrationTagEventImpl> + _$$BeneficiaryRegistrationSummaryEventImplCopyWith< + _$BeneficiaryRegistrationSummaryEventImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc -mixin _$BeneficiaryRegistrationState { - HouseholdModel? get householdModel => throw _privateConstructorUsedError; +abstract class _$$BeneficiaryRegistrationTagEventImplCopyWith<$Res> { + factory _$$BeneficiaryRegistrationTagEventImplCopyWith( + _$BeneficiaryRegistrationTagEventImpl value, + $Res Function(_$BeneficiaryRegistrationTagEventImpl) then) = + __$$BeneficiaryRegistrationTagEventImplCopyWithImpl<$Res>; + @useResult + $Res call({String tag}); +} + +/// @nodoc +class __$$BeneficiaryRegistrationTagEventImplCopyWithImpl<$Res> + extends _$BeneficiaryRegistrationEventCopyWithImpl<$Res, + _$BeneficiaryRegistrationTagEventImpl> + implements _$$BeneficiaryRegistrationTagEventImplCopyWith<$Res> { + __$$BeneficiaryRegistrationTagEventImplCopyWithImpl( + _$BeneficiaryRegistrationTagEventImpl _value, + $Res Function(_$BeneficiaryRegistrationTagEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? tag = null, + }) { + return _then(_$BeneficiaryRegistrationTagEventImpl( + tag: null == tag + ? _value.tag + : tag // ignore: cast_nullable_to_non_nullable + as String, + )); + } +} + +/// @nodoc + +class _$BeneficiaryRegistrationTagEventImpl + implements BeneficiaryRegistrationTagEvent { + const _$BeneficiaryRegistrationTagEventImpl({required this.tag}); + + @override + final String tag; + + @override + String toString() { + return 'BeneficiaryRegistrationEvent.validate(tag: $tag)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BeneficiaryRegistrationTagEventImpl && + (identical(other.tag, tag) || other.tag == tag)); + } + + @override + int get hashCode => Object.hash(runtimeType, tag); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BeneficiaryRegistrationTagEventImplCopyWith< + _$BeneficiaryRegistrationTagEventImpl> + get copyWith => __$$BeneficiaryRegistrationTagEventImplCopyWithImpl< + _$BeneficiaryRegistrationTagEventImpl>(this, _$identity); + + @override @optionalTypeArgs TResult when({ + required TResult Function(AddressModel model) saveAddress, + required TResult Function(HouseholdModel model) saveHouseDetails, required TResult Function( - AddressModel? addressModel, - HouseholdModel? householdModel, - IndividualModel? individualModel, - DateTime? registrationDate, - String? searchQuery, - bool loading, - bool isHeadOfHousehold) - create, - required TResult Function( - AddressModel addressModel, - HouseholdModel householdModel, - List individualModel, - DateTime registrationDate, - ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) - editHousehold, + HouseholdModel household, DateTime registrationDate) + saveHouseholdDetails, + required TResult Function(IndividualModel model, bool isHeadOfHousehold) + saveIndividualDetails, required TResult Function( HouseholdModel householdModel, IndividualModel individualModel, AddressModel addressModel, - ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) - editIndividual, - required TResult Function(AddressModel addressModel, - HouseholdModel householdModel, bool loading) + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) - persisted, - }) => - throw _privateConstructorUsedError; + HouseholdModel household, AddressModel? addressModel, String? tag) + updateHouseholdDetails, + required TResult Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel) + updateIndividualDetails, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + create, + required TResult Function(String userUuid, String projectId, + BoundaryModel boundary, String? tag, bool navigateToSummary) + summary, + required TResult Function(String tag) validate, + }) { + return validate(tag); + } + + @override @optionalTypeArgs TResult? whenOrNull({ - TResult? Function( - AddressModel? addressModel, - HouseholdModel? householdModel, - IndividualModel? individualModel, - DateTime? registrationDate, - String? searchQuery, - bool loading, - bool isHeadOfHousehold)? - create, - TResult? Function( - AddressModel addressModel, - HouseholdModel householdModel, - List individualModel, - DateTime registrationDate, - ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? - editHousehold, + TResult? Function(AddressModel model)? saveAddress, + TResult? Function(HouseholdModel model)? saveHouseDetails, + TResult? Function(HouseholdModel household, DateTime registrationDate)? + saveHouseholdDetails, + TResult? Function(IndividualModel model, bool isHeadOfHousehold)? + saveIndividualDetails, TResult? Function( HouseholdModel householdModel, IndividualModel individualModel, AddressModel addressModel, - ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? - editIndividual, - TResult? Function(AddressModel addressModel, HouseholdModel householdModel, - bool loading)? + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType)? addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? - persisted, - }) => - throw _privateConstructorUsedError; - @optionalTypeArgs - TResult maybeWhen({ - TResult Function( - AddressModel? addressModel, - HouseholdModel? householdModel, - IndividualModel? individualModel, - DateTime? registrationDate, - String? searchQuery, + TResult? Function( + HouseholdModel household, AddressModel? addressModel, String? tag)? + updateHouseholdDetails, + TResult? Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel)? + updateIndividualDetails, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + create, + TResult? Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, + TResult? Function(String tag)? validate, + }) { + return validate?.call(tag); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(AddressModel model)? saveAddress, + TResult Function(HouseholdModel model)? saveHouseDetails, + TResult Function(HouseholdModel household, DateTime registrationDate)? + saveHouseholdDetails, + TResult Function(IndividualModel model, bool isHeadOfHousehold)? + saveIndividualDetails, + TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + String userUuid, + String projectId, + String? tag, + BeneficiaryType beneficiaryType)? + addMember, + TResult Function( + HouseholdModel household, AddressModel? addressModel, String? tag)? + updateHouseholdDetails, + TResult Function(IndividualModel model, String? tag, + HouseholdModel householdModel, AddressModel addressModel)? + updateIndividualDetails, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + create, + TResult Function(String userUuid, String projectId, BoundaryModel boundary, + String? tag, bool navigateToSummary)? + summary, + TResult Function(String tag)? validate, + required TResult orElse(), + }) { + if (validate != null) { + return validate(tag); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(BeneficiaryRegistrationSaveAddressEvent value) + saveAddress, + required TResult Function( + BeneficiaryRegistrationSaveHouseDetailsEvent value) + saveHouseDetails, + required TResult Function( + BeneficiaryRegistrationSaveHouseholdDetailsEvent value) + saveHouseholdDetails, + required TResult Function( + BeneficiaryRegistrationSaveIndividualDetailsEvent value) + saveIndividualDetails, + required TResult Function(BeneficiaryRegistrationAddMemberEvent value) + addMember, + required TResult Function( + BeneficiaryRegistrationUpdateHouseholdDetailsEvent value) + updateHouseholdDetails, + required TResult Function( + BeneficiaryRegistrationUpdateIndividualDetailsEvent value) + updateIndividualDetails, + required TResult Function(BeneficiaryRegistrationCreateEvent value) create, + required TResult Function(BeneficiaryRegistrationSummaryEvent value) + summary, + required TResult Function(BeneficiaryRegistrationTagEvent value) validate, + }) { + return validate(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(BeneficiaryRegistrationSaveAddressEvent value)? + saveAddress, + TResult? Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, + TResult? Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? + saveHouseholdDetails, + TResult? Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? + saveIndividualDetails, + TResult? Function(BeneficiaryRegistrationAddMemberEvent value)? addMember, + TResult? Function(BeneficiaryRegistrationUpdateHouseholdDetailsEvent value)? + updateHouseholdDetails, + TResult? Function( + BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? + updateIndividualDetails, + TResult? Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult? Function(BeneficiaryRegistrationSummaryEvent value)? summary, + TResult? Function(BeneficiaryRegistrationTagEvent value)? validate, + }) { + return validate?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(BeneficiaryRegistrationSaveAddressEvent value)? + saveAddress, + TResult Function(BeneficiaryRegistrationSaveHouseDetailsEvent value)? + saveHouseDetails, + TResult Function(BeneficiaryRegistrationSaveHouseholdDetailsEvent value)? + saveHouseholdDetails, + TResult Function(BeneficiaryRegistrationSaveIndividualDetailsEvent value)? + saveIndividualDetails, + TResult Function(BeneficiaryRegistrationAddMemberEvent value)? addMember, + TResult Function(BeneficiaryRegistrationUpdateHouseholdDetailsEvent value)? + updateHouseholdDetails, + TResult Function(BeneficiaryRegistrationUpdateIndividualDetailsEvent value)? + updateIndividualDetails, + TResult Function(BeneficiaryRegistrationCreateEvent value)? create, + TResult Function(BeneficiaryRegistrationSummaryEvent value)? summary, + TResult Function(BeneficiaryRegistrationTagEvent value)? validate, + required TResult orElse(), + }) { + if (validate != null) { + return validate(this); + } + return orElse(); + } +} + +abstract class BeneficiaryRegistrationTagEvent + implements BeneficiaryRegistrationEvent { + const factory BeneficiaryRegistrationTagEvent({required final String tag}) = + _$BeneficiaryRegistrationTagEventImpl; + + String get tag; + @JsonKey(ignore: true) + _$$BeneficiaryRegistrationTagEventImplCopyWith< + _$BeneficiaryRegistrationTagEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +mixin _$BeneficiaryRegistrationState { + AddressModel? get addressModel => throw _privateConstructorUsedError; + HouseholdModel? get householdModel => throw _privateConstructorUsedError; + bool get loading => throw _privateConstructorUsedError; + @optionalTypeArgs + TResult when({ + required TResult Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold) + create, + required TResult Function( + AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold) + editHousehold, + required TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading) + editIndividual, + required TResult Function(AddressModel addressModel, + HouseholdModel householdModel, bool loading) + addMember, + required TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) + persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold)? + create, + TResult? Function( + AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold)? + editHousehold, + TResult? Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading)? + editIndividual, + TResult? Function(AddressModel addressModel, HouseholdModel householdModel, + bool loading)? + addMember, + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? + persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeWhen({ + TResult Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold)? + create, + TResult Function( + AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold)? + editHousehold, + TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading)? + editIndividual, + TResult Function(AddressModel addressModel, HouseholdModel householdModel, + bool loading)? + addMember, + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? + persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult map({ + required TResult Function(BeneficiaryRegistrationCreateState value) create, + required TResult Function(BeneficiaryRegistrationEditHouseholdState value) + editHousehold, + required TResult Function(BeneficiaryRegistrationEditIndividualState value) + editIndividual, + required TResult Function(BeneficiaryRegistrationAddMemberState value) + addMember, + required TResult Function(BeneficiaryRegistrationPersistedState value) + persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(BeneficiaryRegistrationCreateState value)? create, + TResult? Function(BeneficiaryRegistrationEditHouseholdState value)? + editHousehold, + TResult? Function(BeneficiaryRegistrationEditIndividualState value)? + editIndividual, + TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, + TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, + }) => + throw _privateConstructorUsedError; + @optionalTypeArgs + TResult maybeMap({ + TResult Function(BeneficiaryRegistrationCreateState value)? create, + TResult Function(BeneficiaryRegistrationEditHouseholdState value)? + editHousehold, + TResult Function(BeneficiaryRegistrationEditIndividualState value)? + editIndividual, + TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, + TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, + required TResult orElse(), + }) => + throw _privateConstructorUsedError; + + @JsonKey(ignore: true) + $BeneficiaryRegistrationStateCopyWith + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $BeneficiaryRegistrationStateCopyWith<$Res> { + factory $BeneficiaryRegistrationStateCopyWith( + BeneficiaryRegistrationState value, + $Res Function(BeneficiaryRegistrationState) then) = + _$BeneficiaryRegistrationStateCopyWithImpl<$Res, + BeneficiaryRegistrationState>; + @useResult + $Res call( + {AddressModel addressModel, HouseholdModel householdModel, bool loading}); +} + +/// @nodoc +class _$BeneficiaryRegistrationStateCopyWithImpl<$Res, + $Val extends BeneficiaryRegistrationState> + implements $BeneficiaryRegistrationStateCopyWith<$Res> { + _$BeneficiaryRegistrationStateCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? addressModel = null, + Object? householdModel = null, + Object? loading = null, + }) { + return _then(_value.copyWith( + addressModel: null == addressModel + ? _value.addressModel! + : addressModel // ignore: cast_nullable_to_non_nullable + as AddressModel, + householdModel: null == householdModel + ? _value.householdModel! + : householdModel // ignore: cast_nullable_to_non_nullable + as HouseholdModel, + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + ) as $Val); + } +} + +/// @nodoc +abstract class _$$BeneficiaryRegistrationCreateStateImplCopyWith<$Res> + implements $BeneficiaryRegistrationStateCopyWith<$Res> { + factory _$$BeneficiaryRegistrationCreateStateImplCopyWith( + _$BeneficiaryRegistrationCreateStateImpl value, + $Res Function(_$BeneficiaryRegistrationCreateStateImpl) then) = + __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl<$Res>; + @override + @useResult + $Res call( + {AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold}); +} + +/// @nodoc +class __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl<$Res> + extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, + _$BeneficiaryRegistrationCreateStateImpl> + implements _$$BeneficiaryRegistrationCreateStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl( + _$BeneficiaryRegistrationCreateStateImpl _value, + $Res Function(_$BeneficiaryRegistrationCreateStateImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? addressModel = freezed, + Object? householdModel = freezed, + Object? individualModel = freezed, + Object? projectBeneficiaryModel = freezed, + Object? registrationDate = freezed, + Object? searchQuery = freezed, + Object? loading = null, + Object? isHeadOfHousehold = null, + }) { + return _then(_$BeneficiaryRegistrationCreateStateImpl( + addressModel: freezed == addressModel + ? _value.addressModel + : addressModel // ignore: cast_nullable_to_non_nullable + as AddressModel?, + householdModel: freezed == householdModel + ? _value.householdModel + : householdModel // ignore: cast_nullable_to_non_nullable + as HouseholdModel?, + individualModel: freezed == individualModel + ? _value.individualModel + : individualModel // ignore: cast_nullable_to_non_nullable + as IndividualModel?, + projectBeneficiaryModel: freezed == projectBeneficiaryModel + ? _value.projectBeneficiaryModel + : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable + as ProjectBeneficiaryModel?, + registrationDate: freezed == registrationDate + ? _value.registrationDate + : registrationDate // ignore: cast_nullable_to_non_nullable + as DateTime?, + searchQuery: freezed == searchQuery + ? _value.searchQuery + : searchQuery // ignore: cast_nullable_to_non_nullable + as String?, + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + isHeadOfHousehold: null == isHeadOfHousehold + ? _value.isHeadOfHousehold + : isHeadOfHousehold // ignore: cast_nullable_to_non_nullable + as bool, + )); + } +} + +/// @nodoc + +class _$BeneficiaryRegistrationCreateStateImpl + implements BeneficiaryRegistrationCreateState { + const _$BeneficiaryRegistrationCreateStateImpl( + {this.addressModel, + this.householdModel, + this.individualModel, + this.projectBeneficiaryModel, + this.registrationDate, + this.searchQuery, + this.loading = false, + this.isHeadOfHousehold = false}); + + @override + final AddressModel? addressModel; + @override + final HouseholdModel? householdModel; + @override + final IndividualModel? individualModel; + @override + final ProjectBeneficiaryModel? projectBeneficiaryModel; + @override + final DateTime? registrationDate; + @override + final String? searchQuery; + @override + @JsonKey() + final bool loading; + @override + @JsonKey() + final bool isHeadOfHousehold; + + @override + String toString() { + return 'BeneficiaryRegistrationState.create(addressModel: $addressModel, householdModel: $householdModel, individualModel: $individualModel, projectBeneficiaryModel: $projectBeneficiaryModel, registrationDate: $registrationDate, searchQuery: $searchQuery, loading: $loading, isHeadOfHousehold: $isHeadOfHousehold)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$BeneficiaryRegistrationCreateStateImpl && + (identical(other.addressModel, addressModel) || + other.addressModel == addressModel) && + (identical(other.householdModel, householdModel) || + other.householdModel == householdModel) && + (identical(other.individualModel, individualModel) || + other.individualModel == individualModel) && + (identical( + other.projectBeneficiaryModel, projectBeneficiaryModel) || + other.projectBeneficiaryModel == projectBeneficiaryModel) && + (identical(other.registrationDate, registrationDate) || + other.registrationDate == registrationDate) && + (identical(other.searchQuery, searchQuery) || + other.searchQuery == searchQuery) && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.isHeadOfHousehold, isHeadOfHousehold) || + other.isHeadOfHousehold == isHeadOfHousehold)); + } + + @override + int get hashCode => Object.hash( + runtimeType, + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$BeneficiaryRegistrationCreateStateImplCopyWith< + _$BeneficiaryRegistrationCreateStateImpl> + get copyWith => __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl< + _$BeneficiaryRegistrationCreateStateImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold) + create, + required TResult Function( + AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold) + editHousehold, + required TResult Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading) + editIndividual, + required TResult Function(AddressModel addressModel, + HouseholdModel householdModel, bool loading) + addMember, + required TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) + persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, + }) { + return create( + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, bool loading, bool isHeadOfHousehold)? create, - TResult Function( + TResult? Function( AddressModel addressModel, HouseholdModel householdModel, List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold)? + editHousehold, + TResult? Function( + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading)? + editIndividual, + TResult? Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? + addMember, + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? + persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, + }) { + return create?.call( + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function( + AddressModel? addressModel, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + String? searchQuery, + bool loading, + bool isHeadOfHousehold)? + create, + TResult Function( + AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -2523,11 +3837,44 @@ mixin _$BeneficiaryRegistrationState { TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), - }) => - throw _privateConstructorUsedError; + }) { + if (create != null) { + return create( + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold); + } + return orElse(); + } + + @override @optionalTypeArgs TResult map({ required TResult Function(BeneficiaryRegistrationCreateState value) create, @@ -2539,8 +3886,13 @@ mixin _$BeneficiaryRegistrationState { addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, - }) => - throw _privateConstructorUsedError; + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, + }) { + return create(this); + } + + @override @optionalTypeArgs TResult? mapOrNull({ TResult? Function(BeneficiaryRegistrationCreateState value)? create, @@ -2550,8 +3902,12 @@ mixin _$BeneficiaryRegistrationState { editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, - }) => - throw _privateConstructorUsedError; + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, + }) { + return create?.call(this); + } + + @override @optionalTypeArgs TResult maybeMap({ TResult Function(BeneficiaryRegistrationCreateState value)? create, @@ -2561,177 +3917,179 @@ mixin _$BeneficiaryRegistrationState { editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), - }) => - throw _privateConstructorUsedError; - - @JsonKey(ignore: true) - $BeneficiaryRegistrationStateCopyWith - get copyWith => throw _privateConstructorUsedError; -} - -/// @nodoc -abstract class $BeneficiaryRegistrationStateCopyWith<$Res> { - factory $BeneficiaryRegistrationStateCopyWith( - BeneficiaryRegistrationState value, - $Res Function(BeneficiaryRegistrationState) then) = - _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - BeneficiaryRegistrationState>; - @useResult - $Res call({HouseholdModel householdModel}); + }) { + if (create != null) { + return create(this); + } + return orElse(); + } } -/// @nodoc -class _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - $Val extends BeneficiaryRegistrationState> - implements $BeneficiaryRegistrationStateCopyWith<$Res> { - _$BeneficiaryRegistrationStateCopyWithImpl(this._value, this._then); - - // ignore: unused_field - final $Val _value; - // ignore: unused_field - final $Res Function($Val) _then; +abstract class BeneficiaryRegistrationCreateState + implements BeneficiaryRegistrationState { + const factory BeneficiaryRegistrationCreateState( + {final AddressModel? addressModel, + final HouseholdModel? householdModel, + final IndividualModel? individualModel, + final ProjectBeneficiaryModel? projectBeneficiaryModel, + final DateTime? registrationDate, + final String? searchQuery, + final bool loading, + final bool isHeadOfHousehold}) = _$BeneficiaryRegistrationCreateStateImpl; - @pragma('vm:prefer-inline') @override - $Res call({ - Object? householdModel = null, - }) { - return _then(_value.copyWith( - householdModel: null == householdModel - ? _value.householdModel! - : householdModel // ignore: cast_nullable_to_non_nullable - as HouseholdModel, - ) as $Val); - } + AddressModel? get addressModel; + @override + HouseholdModel? get householdModel; + IndividualModel? get individualModel; + ProjectBeneficiaryModel? get projectBeneficiaryModel; + DateTime? get registrationDate; + String? get searchQuery; + @override + bool get loading; + bool get isHeadOfHousehold; + @override + @JsonKey(ignore: true) + _$$BeneficiaryRegistrationCreateStateImplCopyWith< + _$BeneficiaryRegistrationCreateStateImpl> + get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class _$$BeneficiaryRegistrationCreateStateImplCopyWith<$Res> +abstract class _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith<$Res> implements $BeneficiaryRegistrationStateCopyWith<$Res> { - factory _$$BeneficiaryRegistrationCreateStateImplCopyWith( - _$BeneficiaryRegistrationCreateStateImpl value, - $Res Function(_$BeneficiaryRegistrationCreateStateImpl) then) = - __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl<$Res>; + factory _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith( + _$BeneficiaryRegistrationEditHouseholdStateImpl value, + $Res Function(_$BeneficiaryRegistrationEditHouseholdStateImpl) then) = + __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl<$Res>; @override @useResult $Res call( - {AddressModel? addressModel, - HouseholdModel? householdModel, - IndividualModel? individualModel, - DateTime? registrationDate, - String? searchQuery, + {AddressModel addressModel, + HouseholdModel householdModel, + List individualModel, + DateTime registrationDate, + ProjectBeneficiaryModel? projectBeneficiaryModel, bool loading, - bool isHeadOfHousehold}); + IndividualModel? headOfHousehold}); } /// @nodoc -class __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - _$BeneficiaryRegistrationCreateStateImpl> - implements _$$BeneficiaryRegistrationCreateStateImplCopyWith<$Res> { - __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl( - _$BeneficiaryRegistrationCreateStateImpl _value, - $Res Function(_$BeneficiaryRegistrationCreateStateImpl) _then) + _$BeneficiaryRegistrationEditHouseholdStateImpl> + implements _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl( + _$BeneficiaryRegistrationEditHouseholdStateImpl _value, + $Res Function(_$BeneficiaryRegistrationEditHouseholdStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ - Object? addressModel = freezed, - Object? householdModel = freezed, - Object? individualModel = freezed, - Object? registrationDate = freezed, - Object? searchQuery = freezed, + Object? addressModel = null, + Object? householdModel = null, + Object? individualModel = null, + Object? registrationDate = null, + Object? projectBeneficiaryModel = freezed, Object? loading = null, - Object? isHeadOfHousehold = null, - }) { - return _then(_$BeneficiaryRegistrationCreateStateImpl( - addressModel: freezed == addressModel + Object? headOfHousehold = freezed, + }) { + return _then(_$BeneficiaryRegistrationEditHouseholdStateImpl( + addressModel: null == addressModel ? _value.addressModel : addressModel // ignore: cast_nullable_to_non_nullable - as AddressModel?, - householdModel: freezed == householdModel + as AddressModel, + householdModel: null == householdModel ? _value.householdModel : householdModel // ignore: cast_nullable_to_non_nullable - as HouseholdModel?, - individualModel: freezed == individualModel - ? _value.individualModel + as HouseholdModel, + individualModel: null == individualModel + ? _value._individualModel : individualModel // ignore: cast_nullable_to_non_nullable - as IndividualModel?, - registrationDate: freezed == registrationDate + as List, + registrationDate: null == registrationDate ? _value.registrationDate : registrationDate // ignore: cast_nullable_to_non_nullable - as DateTime?, - searchQuery: freezed == searchQuery - ? _value.searchQuery - : searchQuery // ignore: cast_nullable_to_non_nullable - as String?, + as DateTime, + projectBeneficiaryModel: freezed == projectBeneficiaryModel + ? _value.projectBeneficiaryModel + : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable + as ProjectBeneficiaryModel?, loading: null == loading ? _value.loading : loading // ignore: cast_nullable_to_non_nullable as bool, - isHeadOfHousehold: null == isHeadOfHousehold - ? _value.isHeadOfHousehold - : isHeadOfHousehold // ignore: cast_nullable_to_non_nullable - as bool, + headOfHousehold: freezed == headOfHousehold + ? _value.headOfHousehold + : headOfHousehold // ignore: cast_nullable_to_non_nullable + as IndividualModel?, )); } } /// @nodoc -class _$BeneficiaryRegistrationCreateStateImpl - implements BeneficiaryRegistrationCreateState { - const _$BeneficiaryRegistrationCreateStateImpl( - {this.addressModel, - this.householdModel, - this.individualModel, - this.registrationDate, - this.searchQuery, +class _$BeneficiaryRegistrationEditHouseholdStateImpl + implements BeneficiaryRegistrationEditHouseholdState { + const _$BeneficiaryRegistrationEditHouseholdStateImpl( + {required this.addressModel, + required this.householdModel, + required final List individualModel, + required this.registrationDate, + this.projectBeneficiaryModel, this.loading = false, - this.isHeadOfHousehold = false}); + this.headOfHousehold}) + : _individualModel = individualModel; @override - final AddressModel? addressModel; + final AddressModel addressModel; @override - final HouseholdModel? householdModel; + final HouseholdModel householdModel; + final List _individualModel; @override - final IndividualModel? individualModel; + List get individualModel { + if (_individualModel is EqualUnmodifiableListView) return _individualModel; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_individualModel); + } + @override - final DateTime? registrationDate; + final DateTime registrationDate; @override - final String? searchQuery; + final ProjectBeneficiaryModel? projectBeneficiaryModel; @override @JsonKey() final bool loading; @override - @JsonKey() - final bool isHeadOfHousehold; + final IndividualModel? headOfHousehold; @override String toString() { - return 'BeneficiaryRegistrationState.create(addressModel: $addressModel, householdModel: $householdModel, individualModel: $individualModel, registrationDate: $registrationDate, searchQuery: $searchQuery, loading: $loading, isHeadOfHousehold: $isHeadOfHousehold)'; + return 'BeneficiaryRegistrationState.editHousehold(addressModel: $addressModel, householdModel: $householdModel, individualModel: $individualModel, registrationDate: $registrationDate, projectBeneficiaryModel: $projectBeneficiaryModel, loading: $loading, headOfHousehold: $headOfHousehold)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationCreateStateImpl && + other is _$BeneficiaryRegistrationEditHouseholdStateImpl && (identical(other.addressModel, addressModel) || other.addressModel == addressModel) && (identical(other.householdModel, householdModel) || other.householdModel == householdModel) && - (identical(other.individualModel, individualModel) || - other.individualModel == individualModel) && + const DeepCollectionEquality() + .equals(other._individualModel, _individualModel) && (identical(other.registrationDate, registrationDate) || other.registrationDate == registrationDate) && - (identical(other.searchQuery, searchQuery) || - other.searchQuery == searchQuery) && + (identical( + other.projectBeneficiaryModel, projectBeneficiaryModel) || + other.projectBeneficiaryModel == projectBeneficiaryModel) && (identical(other.loading, loading) || other.loading == loading) && - (identical(other.isHeadOfHousehold, isHeadOfHousehold) || - other.isHeadOfHousehold == isHeadOfHousehold)); + (identical(other.headOfHousehold, headOfHousehold) || + other.headOfHousehold == headOfHousehold)); } @override @@ -2739,19 +4097,21 @@ class _$BeneficiaryRegistrationCreateStateImpl runtimeType, addressModel, householdModel, - individualModel, + const DeepCollectionEquality().hash(_individualModel), registrationDate, - searchQuery, + projectBeneficiaryModel, loading, - isHeadOfHousehold); + headOfHousehold); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationCreateStateImplCopyWith< - _$BeneficiaryRegistrationCreateStateImpl> - get copyWith => __$$BeneficiaryRegistrationCreateStateImplCopyWithImpl< - _$BeneficiaryRegistrationCreateStateImpl>(this, _$identity); + _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith< + _$BeneficiaryRegistrationEditHouseholdStateImpl> + get copyWith => + __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl< + _$BeneficiaryRegistrationEditHouseholdStateImpl>( + this, _$identity); @override @optionalTypeArgs @@ -2760,6 +4120,7 @@ class _$BeneficiaryRegistrationCreateStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -2771,7 +4132,8 @@ class _$BeneficiaryRegistrationCreateStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) + bool loading, + IndividualModel? headOfHousehold) editHousehold, required TResult Function( HouseholdModel householdModel, @@ -2784,11 +4146,29 @@ class _$BeneficiaryRegistrationCreateStateImpl HouseholdModel householdModel, bool loading) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, }) { - return create(addressModel, householdModel, individualModel, - registrationDate, searchQuery, loading, isHeadOfHousehold); + return editHousehold(addressModel, householdModel, individualModel, + registrationDate, projectBeneficiaryModel, loading, headOfHousehold); } @override @@ -2798,6 +4178,7 @@ class _$BeneficiaryRegistrationCreateStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -2809,7 +4190,8 @@ class _$BeneficiaryRegistrationCreateStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult? Function( HouseholdModel householdModel, @@ -2821,11 +4203,30 @@ class _$BeneficiaryRegistrationCreateStateImpl TResult? Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, }) { - return create?.call(addressModel, householdModel, individualModel, - registrationDate, searchQuery, loading, isHeadOfHousehold); + return editHousehold?.call(addressModel, householdModel, individualModel, + registrationDate, projectBeneficiaryModel, loading, headOfHousehold); } @override @@ -2835,6 +4236,7 @@ class _$BeneficiaryRegistrationCreateStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -2846,7 +4248,8 @@ class _$BeneficiaryRegistrationCreateStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -2858,13 +4261,32 @@ class _$BeneficiaryRegistrationCreateStateImpl TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), }) { - if (create != null) { - return create(addressModel, householdModel, individualModel, - registrationDate, searchQuery, loading, isHeadOfHousehold); + if (editHousehold != null) { + return editHousehold(addressModel, householdModel, individualModel, + registrationDate, projectBeneficiaryModel, loading, headOfHousehold); } return orElse(); } @@ -2881,8 +4303,10 @@ class _$BeneficiaryRegistrationCreateStateImpl addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, }) { - return create(this); + return editHousehold(this); } @override @@ -2895,8 +4319,9 @@ class _$BeneficiaryRegistrationCreateStateImpl editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, }) { - return create?.call(this); + return editHousehold?.call(this); } @override @@ -2909,96 +4334,95 @@ class _$BeneficiaryRegistrationCreateStateImpl editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), }) { - if (create != null) { - return create(this); + if (editHousehold != null) { + return editHousehold(this); } return orElse(); } } -abstract class BeneficiaryRegistrationCreateState +abstract class BeneficiaryRegistrationEditHouseholdState implements BeneficiaryRegistrationState { - const factory BeneficiaryRegistrationCreateState( - {final AddressModel? addressModel, - final HouseholdModel? householdModel, - final IndividualModel? individualModel, - final DateTime? registrationDate, - final String? searchQuery, - final bool loading, - final bool isHeadOfHousehold}) = _$BeneficiaryRegistrationCreateStateImpl; + const factory BeneficiaryRegistrationEditHouseholdState( + {required final AddressModel addressModel, + required final HouseholdModel householdModel, + required final List individualModel, + required final DateTime registrationDate, + final ProjectBeneficiaryModel? projectBeneficiaryModel, + final bool loading, + final IndividualModel? headOfHousehold}) = + _$BeneficiaryRegistrationEditHouseholdStateImpl; - AddressModel? get addressModel; @override - HouseholdModel? get householdModel; - IndividualModel? get individualModel; - DateTime? get registrationDate; - String? get searchQuery; + AddressModel get addressModel; + @override + HouseholdModel get householdModel; + List get individualModel; + DateTime get registrationDate; + ProjectBeneficiaryModel? get projectBeneficiaryModel; + @override bool get loading; - bool get isHeadOfHousehold; + IndividualModel? get headOfHousehold; @override @JsonKey(ignore: true) - _$$BeneficiaryRegistrationCreateStateImplCopyWith< - _$BeneficiaryRegistrationCreateStateImpl> + _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith< + _$BeneficiaryRegistrationEditHouseholdStateImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith<$Res> +abstract class _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith<$Res> implements $BeneficiaryRegistrationStateCopyWith<$Res> { - factory _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith( - _$BeneficiaryRegistrationEditHouseholdStateImpl value, - $Res Function(_$BeneficiaryRegistrationEditHouseholdStateImpl) then) = - __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl<$Res>; + factory _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith( + _$BeneficiaryRegistrationEditIndividualStateImpl value, + $Res Function(_$BeneficiaryRegistrationEditIndividualStateImpl) + then) = + __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl<$Res>; @override @useResult $Res call( - {AddressModel addressModel, - HouseholdModel householdModel, - List individualModel, - DateTime registrationDate, + {HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, ProjectBeneficiaryModel? projectBeneficiaryModel, bool loading}); } /// @nodoc -class __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - _$BeneficiaryRegistrationEditHouseholdStateImpl> - implements _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith<$Res> { - __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl( - _$BeneficiaryRegistrationEditHouseholdStateImpl _value, - $Res Function(_$BeneficiaryRegistrationEditHouseholdStateImpl) _then) + _$BeneficiaryRegistrationEditIndividualStateImpl> + implements _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl( + _$BeneficiaryRegistrationEditIndividualStateImpl _value, + $Res Function(_$BeneficiaryRegistrationEditIndividualStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ - Object? addressModel = null, Object? householdModel = null, Object? individualModel = null, - Object? registrationDate = null, + Object? addressModel = null, Object? projectBeneficiaryModel = freezed, Object? loading = null, }) { - return _then(_$BeneficiaryRegistrationEditHouseholdStateImpl( - addressModel: null == addressModel - ? _value.addressModel - : addressModel // ignore: cast_nullable_to_non_nullable - as AddressModel, + return _then(_$BeneficiaryRegistrationEditIndividualStateImpl( householdModel: null == householdModel ? _value.householdModel : householdModel // ignore: cast_nullable_to_non_nullable as HouseholdModel, individualModel: null == individualModel - ? _value._individualModel + ? _value.individualModel : individualModel // ignore: cast_nullable_to_non_nullable - as List, - registrationDate: null == registrationDate - ? _value.registrationDate - : registrationDate // ignore: cast_nullable_to_non_nullable - as DateTime, + as IndividualModel, + addressModel: null == addressModel + ? _value.addressModel + : addressModel // ignore: cast_nullable_to_non_nullable + as AddressModel, projectBeneficiaryModel: freezed == projectBeneficiaryModel ? _value.projectBeneficiaryModel : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable @@ -3013,31 +4437,21 @@ class __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl<$Res> /// @nodoc -class _$BeneficiaryRegistrationEditHouseholdStateImpl - implements BeneficiaryRegistrationEditHouseholdState { - const _$BeneficiaryRegistrationEditHouseholdStateImpl( - {required this.addressModel, - required this.householdModel, - required final List individualModel, - required this.registrationDate, +class _$BeneficiaryRegistrationEditIndividualStateImpl + implements BeneficiaryRegistrationEditIndividualState { + const _$BeneficiaryRegistrationEditIndividualStateImpl( + {required this.householdModel, + required this.individualModel, + required this.addressModel, this.projectBeneficiaryModel, - this.loading = false}) - : _individualModel = individualModel; + this.loading = false}); - @override - final AddressModel addressModel; @override final HouseholdModel householdModel; - final List _individualModel; @override - List get individualModel { - if (_individualModel is EqualUnmodifiableListView) return _individualModel; - // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_individualModel); - } - + final IndividualModel individualModel; @override - final DateTime registrationDate; + final AddressModel addressModel; @override final ProjectBeneficiaryModel? projectBeneficiaryModel; @override @@ -3046,22 +4460,20 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl @override String toString() { - return 'BeneficiaryRegistrationState.editHousehold(addressModel: $addressModel, householdModel: $householdModel, individualModel: $individualModel, registrationDate: $registrationDate, projectBeneficiaryModel: $projectBeneficiaryModel, loading: $loading)'; + return 'BeneficiaryRegistrationState.editIndividual(householdModel: $householdModel, individualModel: $individualModel, addressModel: $addressModel, projectBeneficiaryModel: $projectBeneficiaryModel, loading: $loading)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationEditHouseholdStateImpl && - (identical(other.addressModel, addressModel) || - other.addressModel == addressModel) && + other is _$BeneficiaryRegistrationEditIndividualStateImpl && (identical(other.householdModel, householdModel) || other.householdModel == householdModel) && - const DeepCollectionEquality() - .equals(other._individualModel, _individualModel) && - (identical(other.registrationDate, registrationDate) || - other.registrationDate == registrationDate) && + (identical(other.individualModel, individualModel) || + other.individualModel == individualModel) && + (identical(other.addressModel, addressModel) || + other.addressModel == addressModel) && (identical( other.projectBeneficiaryModel, projectBeneficiaryModel) || other.projectBeneficiaryModel == projectBeneficiaryModel) && @@ -3069,23 +4481,17 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl } @override - int get hashCode => Object.hash( - runtimeType, - addressModel, - householdModel, - const DeepCollectionEquality().hash(_individualModel), - registrationDate, - projectBeneficiaryModel, - loading); + int get hashCode => Object.hash(runtimeType, householdModel, individualModel, + addressModel, projectBeneficiaryModel, loading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith< - _$BeneficiaryRegistrationEditHouseholdStateImpl> + _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith< + _$BeneficiaryRegistrationEditIndividualStateImpl> get copyWith => - __$$BeneficiaryRegistrationEditHouseholdStateImplCopyWithImpl< - _$BeneficiaryRegistrationEditHouseholdStateImpl>( + __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl< + _$BeneficiaryRegistrationEditIndividualStateImpl>( this, _$identity); @override @@ -3095,6 +4501,7 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3106,7 +4513,8 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) + bool loading, + IndividualModel? headOfHousehold) editHousehold, required TResult Function( HouseholdModel householdModel, @@ -3119,11 +4527,29 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl HouseholdModel householdModel, bool loading) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, }) { - return editHousehold(addressModel, householdModel, individualModel, - registrationDate, projectBeneficiaryModel, loading); + return editIndividual(householdModel, individualModel, addressModel, + projectBeneficiaryModel, loading); } @override @@ -3133,6 +4559,7 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3144,7 +4571,8 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult? Function( HouseholdModel householdModel, @@ -3156,11 +4584,30 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl TResult? Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, }) { - return editHousehold?.call(addressModel, householdModel, individualModel, - registrationDate, projectBeneficiaryModel, loading); + return editIndividual?.call(householdModel, individualModel, addressModel, + projectBeneficiaryModel, loading); } @override @@ -3170,6 +4617,7 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3181,7 +4629,8 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -3193,13 +4642,32 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), }) { - if (editHousehold != null) { - return editHousehold(addressModel, householdModel, individualModel, - registrationDate, projectBeneficiaryModel, loading); + if (editIndividual != null) { + return editIndividual(householdModel, individualModel, addressModel, + projectBeneficiaryModel, loading); } return orElse(); } @@ -3216,8 +4684,10 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, }) { - return editHousehold(this); + return editIndividual(this); } @override @@ -3230,8 +4700,9 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, }) { - return editHousehold?.call(this); + return editIndividual?.call(this); } @override @@ -3244,93 +4715,79 @@ class _$BeneficiaryRegistrationEditHouseholdStateImpl editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), }) { - if (editHousehold != null) { - return editHousehold(this); + if (editIndividual != null) { + return editIndividual(this); } return orElse(); } } -abstract class BeneficiaryRegistrationEditHouseholdState +abstract class BeneficiaryRegistrationEditIndividualState implements BeneficiaryRegistrationState { - const factory BeneficiaryRegistrationEditHouseholdState( - {required final AddressModel addressModel, - required final HouseholdModel householdModel, - required final List individualModel, - required final DateTime registrationDate, + const factory BeneficiaryRegistrationEditIndividualState( + {required final HouseholdModel householdModel, + required final IndividualModel individualModel, + required final AddressModel addressModel, final ProjectBeneficiaryModel? projectBeneficiaryModel, - final bool loading}) = _$BeneficiaryRegistrationEditHouseholdStateImpl; + final bool loading}) = _$BeneficiaryRegistrationEditIndividualStateImpl; - AddressModel get addressModel; @override HouseholdModel get householdModel; - List get individualModel; - DateTime get registrationDate; + IndividualModel get individualModel; + @override + AddressModel get addressModel; ProjectBeneficiaryModel? get projectBeneficiaryModel; + @override bool get loading; @override @JsonKey(ignore: true) - _$$BeneficiaryRegistrationEditHouseholdStateImplCopyWith< - _$BeneficiaryRegistrationEditHouseholdStateImpl> + _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith< + _$BeneficiaryRegistrationEditIndividualStateImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith<$Res> +abstract class _$$BeneficiaryRegistrationAddMemberStateImplCopyWith<$Res> implements $BeneficiaryRegistrationStateCopyWith<$Res> { - factory _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith( - _$BeneficiaryRegistrationEditIndividualStateImpl value, - $Res Function(_$BeneficiaryRegistrationEditIndividualStateImpl) - then) = - __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl<$Res>; + factory _$$BeneficiaryRegistrationAddMemberStateImplCopyWith( + _$BeneficiaryRegistrationAddMemberStateImpl value, + $Res Function(_$BeneficiaryRegistrationAddMemberStateImpl) then) = + __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl<$Res>; @override @useResult $Res call( - {HouseholdModel householdModel, - IndividualModel individualModel, - AddressModel addressModel, - ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading}); + {AddressModel addressModel, HouseholdModel householdModel, bool loading}); } /// @nodoc -class __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - _$BeneficiaryRegistrationEditIndividualStateImpl> - implements _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith<$Res> { - __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl( - _$BeneficiaryRegistrationEditIndividualStateImpl _value, - $Res Function(_$BeneficiaryRegistrationEditIndividualStateImpl) _then) + _$BeneficiaryRegistrationAddMemberStateImpl> + implements _$$BeneficiaryRegistrationAddMemberStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl( + _$BeneficiaryRegistrationAddMemberStateImpl _value, + $Res Function(_$BeneficiaryRegistrationAddMemberStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ - Object? householdModel = null, - Object? individualModel = null, Object? addressModel = null, - Object? projectBeneficiaryModel = freezed, + Object? householdModel = null, Object? loading = null, }) { - return _then(_$BeneficiaryRegistrationEditIndividualStateImpl( - householdModel: null == householdModel - ? _value.householdModel - : householdModel // ignore: cast_nullable_to_non_nullable - as HouseholdModel, - individualModel: null == individualModel - ? _value.individualModel - : individualModel // ignore: cast_nullable_to_non_nullable - as IndividualModel, + return _then(_$BeneficiaryRegistrationAddMemberStateImpl( addressModel: null == addressModel ? _value.addressModel : addressModel // ignore: cast_nullable_to_non_nullable as AddressModel, - projectBeneficiaryModel: freezed == projectBeneficiaryModel - ? _value.projectBeneficiaryModel - : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable - as ProjectBeneficiaryModel?, + householdModel: null == householdModel + ? _value.householdModel + : householdModel // ignore: cast_nullable_to_non_nullable + as HouseholdModel, loading: null == loading ? _value.loading : loading // ignore: cast_nullable_to_non_nullable @@ -3341,62 +4798,49 @@ class __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl<$Res> /// @nodoc -class _$BeneficiaryRegistrationEditIndividualStateImpl - implements BeneficiaryRegistrationEditIndividualState { - const _$BeneficiaryRegistrationEditIndividualStateImpl( - {required this.householdModel, - required this.individualModel, - required this.addressModel, - this.projectBeneficiaryModel, +class _$BeneficiaryRegistrationAddMemberStateImpl + implements BeneficiaryRegistrationAddMemberState { + const _$BeneficiaryRegistrationAddMemberStateImpl( + {required this.addressModel, + required this.householdModel, this.loading = false}); - @override - final HouseholdModel householdModel; - @override - final IndividualModel individualModel; @override final AddressModel addressModel; @override - final ProjectBeneficiaryModel? projectBeneficiaryModel; + final HouseholdModel householdModel; @override @JsonKey() final bool loading; @override String toString() { - return 'BeneficiaryRegistrationState.editIndividual(householdModel: $householdModel, individualModel: $individualModel, addressModel: $addressModel, projectBeneficiaryModel: $projectBeneficiaryModel, loading: $loading)'; + return 'BeneficiaryRegistrationState.addMember(addressModel: $addressModel, householdModel: $householdModel, loading: $loading)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationEditIndividualStateImpl && - (identical(other.householdModel, householdModel) || - other.householdModel == householdModel) && - (identical(other.individualModel, individualModel) || - other.individualModel == individualModel) && + other is _$BeneficiaryRegistrationAddMemberStateImpl && (identical(other.addressModel, addressModel) || other.addressModel == addressModel) && - (identical( - other.projectBeneficiaryModel, projectBeneficiaryModel) || - other.projectBeneficiaryModel == projectBeneficiaryModel) && + (identical(other.householdModel, householdModel) || + other.householdModel == householdModel) && (identical(other.loading, loading) || other.loading == loading)); } @override - int get hashCode => Object.hash(runtimeType, householdModel, individualModel, - addressModel, projectBeneficiaryModel, loading); + int get hashCode => + Object.hash(runtimeType, addressModel, householdModel, loading); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith< - _$BeneficiaryRegistrationEditIndividualStateImpl> - get copyWith => - __$$BeneficiaryRegistrationEditIndividualStateImplCopyWithImpl< - _$BeneficiaryRegistrationEditIndividualStateImpl>( - this, _$identity); + _$$BeneficiaryRegistrationAddMemberStateImplCopyWith< + _$BeneficiaryRegistrationAddMemberStateImpl> + get copyWith => __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl< + _$BeneficiaryRegistrationAddMemberStateImpl>(this, _$identity); @override @optionalTypeArgs @@ -3405,6 +4849,7 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3416,7 +4861,8 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) + bool loading, + IndividualModel? headOfHousehold) editHousehold, required TResult Function( HouseholdModel householdModel, @@ -3429,11 +4875,28 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl HouseholdModel householdModel, bool loading) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, }) { - return editIndividual(householdModel, individualModel, addressModel, - projectBeneficiaryModel, loading); + return addMember(addressModel, householdModel, loading); } @override @@ -3443,6 +4906,7 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3454,7 +4918,8 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult? Function( HouseholdModel householdModel, @@ -3466,11 +4931,29 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl TResult? Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, }) { - return editIndividual?.call(householdModel, individualModel, addressModel, - projectBeneficiaryModel, loading); + return addMember?.call(addressModel, householdModel, loading); } @override @@ -3480,6 +4963,7 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3491,7 +4975,8 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -3503,13 +4988,31 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), }) { - if (editIndividual != null) { - return editIndividual(householdModel, individualModel, addressModel, - projectBeneficiaryModel, loading); + if (addMember != null) { + return addMember(addressModel, householdModel, loading); } return orElse(); } @@ -3526,8 +5029,10 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, }) { - return editIndividual(this); + return addMember(this); } @override @@ -3540,8 +5045,9 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, }) { - return editIndividual?.call(this); + return addMember?.call(this); } @override @@ -3554,129 +5060,208 @@ class _$BeneficiaryRegistrationEditIndividualStateImpl editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), }) { - if (editIndividual != null) { - return editIndividual(this); + if (addMember != null) { + return addMember(this); } return orElse(); } } -abstract class BeneficiaryRegistrationEditIndividualState +abstract class BeneficiaryRegistrationAddMemberState implements BeneficiaryRegistrationState { - const factory BeneficiaryRegistrationEditIndividualState( - {required final HouseholdModel householdModel, - required final IndividualModel individualModel, - required final AddressModel addressModel, - final ProjectBeneficiaryModel? projectBeneficiaryModel, - final bool loading}) = _$BeneficiaryRegistrationEditIndividualStateImpl; + const factory BeneficiaryRegistrationAddMemberState( + {required final AddressModel addressModel, + required final HouseholdModel householdModel, + final bool loading}) = _$BeneficiaryRegistrationAddMemberStateImpl; @override - HouseholdModel get householdModel; - IndividualModel get individualModel; AddressModel get addressModel; - ProjectBeneficiaryModel? get projectBeneficiaryModel; + @override + HouseholdModel get householdModel; + @override bool get loading; @override @JsonKey(ignore: true) - _$$BeneficiaryRegistrationEditIndividualStateImplCopyWith< - _$BeneficiaryRegistrationEditIndividualStateImpl> + _$$BeneficiaryRegistrationAddMemberStateImplCopyWith< + _$BeneficiaryRegistrationAddMemberStateImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class _$$BeneficiaryRegistrationAddMemberStateImplCopyWith<$Res> +abstract class _$$BeneficiaryRegistrationPersistedStateImplCopyWith<$Res> implements $BeneficiaryRegistrationStateCopyWith<$Res> { - factory _$$BeneficiaryRegistrationAddMemberStateImplCopyWith( - _$BeneficiaryRegistrationAddMemberStateImpl value, - $Res Function(_$BeneficiaryRegistrationAddMemberStateImpl) then) = - __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl<$Res>; + factory _$$BeneficiaryRegistrationPersistedStateImplCopyWith( + _$BeneficiaryRegistrationPersistedStateImpl value, + $Res Function(_$BeneficiaryRegistrationPersistedStateImpl) then) = + __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl<$Res>; @override @useResult $Res call( - {AddressModel addressModel, HouseholdModel householdModel, bool loading}); + {bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold}); } /// @nodoc -class __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - _$BeneficiaryRegistrationAddMemberStateImpl> - implements _$$BeneficiaryRegistrationAddMemberStateImplCopyWith<$Res> { - __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl( - _$BeneficiaryRegistrationAddMemberStateImpl _value, - $Res Function(_$BeneficiaryRegistrationAddMemberStateImpl) _then) + _$BeneficiaryRegistrationPersistedStateImpl> + implements _$$BeneficiaryRegistrationPersistedStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl( + _$BeneficiaryRegistrationPersistedStateImpl _value, + $Res Function(_$BeneficiaryRegistrationPersistedStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ - Object? addressModel = null, + Object? navigateToRoot = null, Object? householdModel = null, + Object? individualModel = freezed, + Object? projectBeneficiaryModel = freezed, + Object? registrationDate = freezed, + Object? addressModel = freezed, Object? loading = null, + Object? isEdit = null, + Object? isHeadOfHousehold = null, }) { - return _then(_$BeneficiaryRegistrationAddMemberStateImpl( - addressModel: null == addressModel - ? _value.addressModel - : addressModel // ignore: cast_nullable_to_non_nullable - as AddressModel, + return _then(_$BeneficiaryRegistrationPersistedStateImpl( + navigateToRoot: null == navigateToRoot + ? _value.navigateToRoot + : navigateToRoot // ignore: cast_nullable_to_non_nullable + as bool, householdModel: null == householdModel ? _value.householdModel : householdModel // ignore: cast_nullable_to_non_nullable as HouseholdModel, + individualModel: freezed == individualModel + ? _value.individualModel + : individualModel // ignore: cast_nullable_to_non_nullable + as IndividualModel?, + projectBeneficiaryModel: freezed == projectBeneficiaryModel + ? _value.projectBeneficiaryModel + : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable + as ProjectBeneficiaryModel?, + registrationDate: freezed == registrationDate + ? _value.registrationDate + : registrationDate // ignore: cast_nullable_to_non_nullable + as DateTime?, + addressModel: freezed == addressModel + ? _value.addressModel + : addressModel // ignore: cast_nullable_to_non_nullable + as AddressModel?, loading: null == loading ? _value.loading : loading // ignore: cast_nullable_to_non_nullable as bool, + isEdit: null == isEdit + ? _value.isEdit + : isEdit // ignore: cast_nullable_to_non_nullable + as bool, + isHeadOfHousehold: null == isHeadOfHousehold + ? _value.isHeadOfHousehold + : isHeadOfHousehold // ignore: cast_nullable_to_non_nullable + as bool, )); } } /// @nodoc -class _$BeneficiaryRegistrationAddMemberStateImpl - implements BeneficiaryRegistrationAddMemberState { - const _$BeneficiaryRegistrationAddMemberStateImpl( - {required this.addressModel, +class _$BeneficiaryRegistrationPersistedStateImpl + implements BeneficiaryRegistrationPersistedState { + const _$BeneficiaryRegistrationPersistedStateImpl( + {this.navigateToRoot = true, required this.householdModel, - this.loading = false}); + this.individualModel, + this.projectBeneficiaryModel, + this.registrationDate, + this.addressModel, + this.loading = false, + this.isEdit = false, + this.isHeadOfHousehold = false}); @override - final AddressModel addressModel; + @JsonKey() + final bool navigateToRoot; @override final HouseholdModel householdModel; @override + final IndividualModel? individualModel; + @override + final ProjectBeneficiaryModel? projectBeneficiaryModel; + @override + final DateTime? registrationDate; + @override + final AddressModel? addressModel; + @override @JsonKey() final bool loading; + @override + @JsonKey() + final bool isEdit; + @override + @JsonKey() + final bool isHeadOfHousehold; @override String toString() { - return 'BeneficiaryRegistrationState.addMember(addressModel: $addressModel, householdModel: $householdModel, loading: $loading)'; + return 'BeneficiaryRegistrationState.persisted(navigateToRoot: $navigateToRoot, householdModel: $householdModel, individualModel: $individualModel, projectBeneficiaryModel: $projectBeneficiaryModel, registrationDate: $registrationDate, addressModel: $addressModel, loading: $loading, isEdit: $isEdit, isHeadOfHousehold: $isHeadOfHousehold)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationAddMemberStateImpl && - (identical(other.addressModel, addressModel) || - other.addressModel == addressModel) && + other is _$BeneficiaryRegistrationPersistedStateImpl && + (identical(other.navigateToRoot, navigateToRoot) || + other.navigateToRoot == navigateToRoot) && (identical(other.householdModel, householdModel) || other.householdModel == householdModel) && - (identical(other.loading, loading) || other.loading == loading)); + (identical(other.individualModel, individualModel) || + other.individualModel == individualModel) && + (identical( + other.projectBeneficiaryModel, projectBeneficiaryModel) || + other.projectBeneficiaryModel == projectBeneficiaryModel) && + (identical(other.registrationDate, registrationDate) || + other.registrationDate == registrationDate) && + (identical(other.addressModel, addressModel) || + other.addressModel == addressModel) && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.isEdit, isEdit) || other.isEdit == isEdit) && + (identical(other.isHeadOfHousehold, isHeadOfHousehold) || + other.isHeadOfHousehold == isHeadOfHousehold)); } @override - int get hashCode => - Object.hash(runtimeType, addressModel, householdModel, loading); + int get hashCode => Object.hash( + runtimeType, + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isEdit, + isHeadOfHousehold); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationAddMemberStateImplCopyWith< - _$BeneficiaryRegistrationAddMemberStateImpl> - get copyWith => __$$BeneficiaryRegistrationAddMemberStateImplCopyWithImpl< - _$BeneficiaryRegistrationAddMemberStateImpl>(this, _$identity); + _$$BeneficiaryRegistrationPersistedStateImplCopyWith< + _$BeneficiaryRegistrationPersistedStateImpl> + get copyWith => __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl< + _$BeneficiaryRegistrationPersistedStateImpl>(this, _$identity); @override @optionalTypeArgs @@ -3685,6 +5270,7 @@ class _$BeneficiaryRegistrationAddMemberStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3696,7 +5282,8 @@ class _$BeneficiaryRegistrationAddMemberStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) + bool loading, + IndividualModel? headOfHousehold) editHousehold, required TResult Function( HouseholdModel householdModel, @@ -3709,10 +5296,37 @@ class _$BeneficiaryRegistrationAddMemberStateImpl HouseholdModel householdModel, bool loading) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, }) { - return addMember(addressModel, householdModel, loading); + return persisted( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isEdit, + isHeadOfHousehold); } @override @@ -3722,6 +5336,7 @@ class _$BeneficiaryRegistrationAddMemberStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3733,22 +5348,51 @@ class _$BeneficiaryRegistrationAddMemberStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult? Function( - HouseholdModel householdModel, - IndividualModel individualModel, - AddressModel addressModel, + HouseholdModel householdModel, + IndividualModel individualModel, + AddressModel addressModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + bool loading)? + editIndividual, + TResult? Function(AddressModel addressModel, HouseholdModel householdModel, + bool loading)? + addMember, + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? + persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? - editIndividual, - TResult? Function(AddressModel addressModel, HouseholdModel householdModel, - bool loading)? - addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? - persisted, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, }) { - return addMember?.call(addressModel, householdModel, loading); + return persisted?.call( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isEdit, + isHeadOfHousehold); } @override @@ -3758,6 +5402,7 @@ class _$BeneficiaryRegistrationAddMemberStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3769,7 +5414,8 @@ class _$BeneficiaryRegistrationAddMemberStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -3781,12 +5427,40 @@ class _$BeneficiaryRegistrationAddMemberStateImpl TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), }) { - if (addMember != null) { - return addMember(addressModel, householdModel, loading); + if (persisted != null) { + return persisted( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isEdit, + isHeadOfHousehold); } return orElse(); } @@ -3803,8 +5477,10 @@ class _$BeneficiaryRegistrationAddMemberStateImpl addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, }) { - return addMember(this); + return persisted(this); } @override @@ -3817,8 +5493,9 @@ class _$BeneficiaryRegistrationAddMemberStateImpl editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, }) { - return addMember?.call(this); + return persisted?.call(this); } @override @@ -3831,113 +5508,209 @@ class _$BeneficiaryRegistrationAddMemberStateImpl editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), }) { - if (addMember != null) { - return addMember(this); + if (persisted != null) { + return persisted(this); } return orElse(); } } -abstract class BeneficiaryRegistrationAddMemberState +abstract class BeneficiaryRegistrationPersistedState implements BeneficiaryRegistrationState { - const factory BeneficiaryRegistrationAddMemberState( - {required final AddressModel addressModel, - required final HouseholdModel householdModel, - final bool loading}) = _$BeneficiaryRegistrationAddMemberStateImpl; + const factory BeneficiaryRegistrationPersistedState( + {final bool navigateToRoot, + required final HouseholdModel householdModel, + final IndividualModel? individualModel, + final ProjectBeneficiaryModel? projectBeneficiaryModel, + final DateTime? registrationDate, + final AddressModel? addressModel, + final bool loading, + final bool isEdit, + final bool isHeadOfHousehold}) = + _$BeneficiaryRegistrationPersistedStateImpl; - AddressModel get addressModel; + bool get navigateToRoot; @override HouseholdModel get householdModel; + IndividualModel? get individualModel; + ProjectBeneficiaryModel? get projectBeneficiaryModel; + DateTime? get registrationDate; + @override + AddressModel? get addressModel; + @override bool get loading; + bool get isEdit; + bool get isHeadOfHousehold; @override @JsonKey(ignore: true) - _$$BeneficiaryRegistrationAddMemberStateImplCopyWith< - _$BeneficiaryRegistrationAddMemberStateImpl> + _$$BeneficiaryRegistrationPersistedStateImplCopyWith< + _$BeneficiaryRegistrationPersistedStateImpl> get copyWith => throw _privateConstructorUsedError; } /// @nodoc -abstract class _$$BeneficiaryRegistrationPersistedStateImplCopyWith<$Res> +abstract class _$$BeneficiaryRegistrationSummaryStateImplCopyWith<$Res> implements $BeneficiaryRegistrationStateCopyWith<$Res> { - factory _$$BeneficiaryRegistrationPersistedStateImplCopyWith( - _$BeneficiaryRegistrationPersistedStateImpl value, - $Res Function(_$BeneficiaryRegistrationPersistedStateImpl) then) = - __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl<$Res>; + factory _$$BeneficiaryRegistrationSummaryStateImplCopyWith( + _$BeneficiaryRegistrationSummaryStateImpl value, + $Res Function(_$BeneficiaryRegistrationSummaryStateImpl) then) = + __$$BeneficiaryRegistrationSummaryStateImplCopyWithImpl<$Res>; @override @useResult - $Res call({bool navigateToRoot, HouseholdModel householdModel}); + $Res call( + {bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold}); } /// @nodoc -class __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl<$Res> +class __$$BeneficiaryRegistrationSummaryStateImplCopyWithImpl<$Res> extends _$BeneficiaryRegistrationStateCopyWithImpl<$Res, - _$BeneficiaryRegistrationPersistedStateImpl> - implements _$$BeneficiaryRegistrationPersistedStateImplCopyWith<$Res> { - __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl( - _$BeneficiaryRegistrationPersistedStateImpl _value, - $Res Function(_$BeneficiaryRegistrationPersistedStateImpl) _then) + _$BeneficiaryRegistrationSummaryStateImpl> + implements _$$BeneficiaryRegistrationSummaryStateImplCopyWith<$Res> { + __$$BeneficiaryRegistrationSummaryStateImplCopyWithImpl( + _$BeneficiaryRegistrationSummaryStateImpl _value, + $Res Function(_$BeneficiaryRegistrationSummaryStateImpl) _then) : super(_value, _then); @pragma('vm:prefer-inline') @override $Res call({ Object? navigateToRoot = null, - Object? householdModel = null, + Object? householdModel = freezed, + Object? individualModel = freezed, + Object? projectBeneficiaryModel = freezed, + Object? registrationDate = freezed, + Object? addressModel = freezed, + Object? loading = null, + Object? isHeadOfHousehold = null, }) { - return _then(_$BeneficiaryRegistrationPersistedStateImpl( + return _then(_$BeneficiaryRegistrationSummaryStateImpl( navigateToRoot: null == navigateToRoot ? _value.navigateToRoot : navigateToRoot // ignore: cast_nullable_to_non_nullable as bool, - householdModel: null == householdModel + householdModel: freezed == householdModel ? _value.householdModel : householdModel // ignore: cast_nullable_to_non_nullable - as HouseholdModel, + as HouseholdModel?, + individualModel: freezed == individualModel + ? _value.individualModel + : individualModel // ignore: cast_nullable_to_non_nullable + as IndividualModel?, + projectBeneficiaryModel: freezed == projectBeneficiaryModel + ? _value.projectBeneficiaryModel + : projectBeneficiaryModel // ignore: cast_nullable_to_non_nullable + as ProjectBeneficiaryModel?, + registrationDate: freezed == registrationDate + ? _value.registrationDate + : registrationDate // ignore: cast_nullable_to_non_nullable + as DateTime?, + addressModel: freezed == addressModel + ? _value.addressModel + : addressModel // ignore: cast_nullable_to_non_nullable + as AddressModel?, + loading: null == loading + ? _value.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + isHeadOfHousehold: null == isHeadOfHousehold + ? _value.isHeadOfHousehold + : isHeadOfHousehold // ignore: cast_nullable_to_non_nullable + as bool, )); } } /// @nodoc -class _$BeneficiaryRegistrationPersistedStateImpl - implements BeneficiaryRegistrationPersistedState { - const _$BeneficiaryRegistrationPersistedStateImpl( - {this.navigateToRoot = true, required this.householdModel}); +class _$BeneficiaryRegistrationSummaryStateImpl + implements BeneficiaryRegistrationSummaryState { + const _$BeneficiaryRegistrationSummaryStateImpl( + {this.navigateToRoot = true, + this.householdModel, + this.individualModel, + this.projectBeneficiaryModel, + this.registrationDate, + this.addressModel, + this.loading = false, + this.isHeadOfHousehold = false}); @override @JsonKey() final bool navigateToRoot; @override - final HouseholdModel householdModel; + final HouseholdModel? householdModel; + @override + final IndividualModel? individualModel; + @override + final ProjectBeneficiaryModel? projectBeneficiaryModel; + @override + final DateTime? registrationDate; + @override + final AddressModel? addressModel; + @override + @JsonKey() + final bool loading; + @override + @JsonKey() + final bool isHeadOfHousehold; @override String toString() { - return 'BeneficiaryRegistrationState.persisted(navigateToRoot: $navigateToRoot, householdModel: $householdModel)'; + return 'BeneficiaryRegistrationState.summary(navigateToRoot: $navigateToRoot, householdModel: $householdModel, individualModel: $individualModel, projectBeneficiaryModel: $projectBeneficiaryModel, registrationDate: $registrationDate, addressModel: $addressModel, loading: $loading, isHeadOfHousehold: $isHeadOfHousehold)'; } @override bool operator ==(Object other) { return identical(this, other) || (other.runtimeType == runtimeType && - other is _$BeneficiaryRegistrationPersistedStateImpl && + other is _$BeneficiaryRegistrationSummaryStateImpl && (identical(other.navigateToRoot, navigateToRoot) || other.navigateToRoot == navigateToRoot) && (identical(other.householdModel, householdModel) || - other.householdModel == householdModel)); + other.householdModel == householdModel) && + (identical(other.individualModel, individualModel) || + other.individualModel == individualModel) && + (identical( + other.projectBeneficiaryModel, projectBeneficiaryModel) || + other.projectBeneficiaryModel == projectBeneficiaryModel) && + (identical(other.registrationDate, registrationDate) || + other.registrationDate == registrationDate) && + (identical(other.addressModel, addressModel) || + other.addressModel == addressModel) && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.isHeadOfHousehold, isHeadOfHousehold) || + other.isHeadOfHousehold == isHeadOfHousehold)); } @override - int get hashCode => Object.hash(runtimeType, navigateToRoot, householdModel); + int get hashCode => Object.hash( + runtimeType, + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold); @JsonKey(ignore: true) @override @pragma('vm:prefer-inline') - _$$BeneficiaryRegistrationPersistedStateImplCopyWith< - _$BeneficiaryRegistrationPersistedStateImpl> - get copyWith => __$$BeneficiaryRegistrationPersistedStateImplCopyWithImpl< - _$BeneficiaryRegistrationPersistedStateImpl>(this, _$identity); + _$$BeneficiaryRegistrationSummaryStateImplCopyWith< + _$BeneficiaryRegistrationSummaryStateImpl> + get copyWith => __$$BeneficiaryRegistrationSummaryStateImplCopyWithImpl< + _$BeneficiaryRegistrationSummaryStateImpl>(this, _$identity); @override @optionalTypeArgs @@ -3946,6 +5719,7 @@ class _$BeneficiaryRegistrationPersistedStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3957,7 +5731,8 @@ class _$BeneficiaryRegistrationPersistedStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading) + bool loading, + IndividualModel? headOfHousehold) editHousehold, required TResult Function( HouseholdModel householdModel, @@ -3970,10 +5745,36 @@ class _$BeneficiaryRegistrationPersistedStateImpl HouseholdModel householdModel, bool loading) addMember, required TResult Function( - bool navigateToRoot, HouseholdModel householdModel) + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold) persisted, + required TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold) + summary, }) { - return persisted(navigateToRoot, householdModel); + return summary( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold); } @override @@ -3983,6 +5784,7 @@ class _$BeneficiaryRegistrationPersistedStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -3994,7 +5796,8 @@ class _$BeneficiaryRegistrationPersistedStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult? Function( HouseholdModel householdModel, @@ -4006,10 +5809,37 @@ class _$BeneficiaryRegistrationPersistedStateImpl TResult? Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult? Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult? Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult? Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, }) { - return persisted?.call(navigateToRoot, householdModel); + return summary?.call( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold); } @override @@ -4019,6 +5849,7 @@ class _$BeneficiaryRegistrationPersistedStateImpl AddressModel? addressModel, HouseholdModel? householdModel, IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, DateTime? registrationDate, String? searchQuery, bool loading, @@ -4030,7 +5861,8 @@ class _$BeneficiaryRegistrationPersistedStateImpl List individualModel, DateTime registrationDate, ProjectBeneficiaryModel? projectBeneficiaryModel, - bool loading)? + bool loading, + IndividualModel? headOfHousehold)? editHousehold, TResult Function( HouseholdModel householdModel, @@ -4042,12 +5874,39 @@ class _$BeneficiaryRegistrationPersistedStateImpl TResult Function(AddressModel addressModel, HouseholdModel householdModel, bool loading)? addMember, - TResult Function(bool navigateToRoot, HouseholdModel householdModel)? + TResult Function( + bool navigateToRoot, + HouseholdModel householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isEdit, + bool isHeadOfHousehold)? persisted, + TResult Function( + bool navigateToRoot, + HouseholdModel? householdModel, + IndividualModel? individualModel, + ProjectBeneficiaryModel? projectBeneficiaryModel, + DateTime? registrationDate, + AddressModel? addressModel, + bool loading, + bool isHeadOfHousehold)? + summary, required TResult orElse(), }) { - if (persisted != null) { - return persisted(navigateToRoot, householdModel); + if (summary != null) { + return summary( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold); } return orElse(); } @@ -4064,8 +5923,10 @@ class _$BeneficiaryRegistrationPersistedStateImpl addMember, required TResult Function(BeneficiaryRegistrationPersistedState value) persisted, + required TResult Function(BeneficiaryRegistrationSummaryState value) + summary, }) { - return persisted(this); + return summary(this); } @override @@ -4078,8 +5939,9 @@ class _$BeneficiaryRegistrationPersistedStateImpl editIndividual, TResult? Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult? Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult? Function(BeneficiaryRegistrationSummaryState value)? summary, }) { - return persisted?.call(this); + return summary?.call(this); } @override @@ -4092,28 +5954,43 @@ class _$BeneficiaryRegistrationPersistedStateImpl editIndividual, TResult Function(BeneficiaryRegistrationAddMemberState value)? addMember, TResult Function(BeneficiaryRegistrationPersistedState value)? persisted, + TResult Function(BeneficiaryRegistrationSummaryState value)? summary, required TResult orElse(), }) { - if (persisted != null) { - return persisted(this); + if (summary != null) { + return summary(this); } return orElse(); } } -abstract class BeneficiaryRegistrationPersistedState +abstract class BeneficiaryRegistrationSummaryState implements BeneficiaryRegistrationState { - const factory BeneficiaryRegistrationPersistedState( + const factory BeneficiaryRegistrationSummaryState( {final bool navigateToRoot, - required final HouseholdModel householdModel}) = - _$BeneficiaryRegistrationPersistedStateImpl; + final HouseholdModel? householdModel, + final IndividualModel? individualModel, + final ProjectBeneficiaryModel? projectBeneficiaryModel, + final DateTime? registrationDate, + final AddressModel? addressModel, + final bool loading, + final bool isHeadOfHousehold}) = + _$BeneficiaryRegistrationSummaryStateImpl; bool get navigateToRoot; @override - HouseholdModel get householdModel; + HouseholdModel? get householdModel; + IndividualModel? get individualModel; + ProjectBeneficiaryModel? get projectBeneficiaryModel; + DateTime? get registrationDate; + @override + AddressModel? get addressModel; + @override + bool get loading; + bool get isHeadOfHousehold; @override @JsonKey(ignore: true) - _$$BeneficiaryRegistrationPersistedStateImplCopyWith< - _$BeneficiaryRegistrationPersistedStateImpl> + _$$BeneficiaryRegistrationSummaryStateImplCopyWith< + _$BeneficiaryRegistrationSummaryStateImpl> get copyWith => throw _privateConstructorUsedError; } diff --git a/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.dart b/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.dart index 1c3b173db..8ccbd43a2 100644 --- a/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.dart +++ b/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.dart @@ -1,8 +1,10 @@ import 'dart:async'; +import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:registration_delivery/blocs/search_households/search_households.dart'; import '../../models/entities/additional_fields_type.dart'; import '../../models/entities/deliver_strategy_type.dart'; @@ -36,20 +38,26 @@ class DeliverInterventionBloc emit(state.copyWith(loading: true)); try { if (event.isEditing) { + if (!event.navigateToSummary) { + await taskRepository.update(event.task.copyWith( + clientAuditDetails: (event.task.clientAuditDetails?.createdBy != + null && + event.task.clientAuditDetails?.createdTime != null) + ? ClientAuditDetails( + createdBy: event.task.clientAuditDetails!.createdBy, + createdTime: event.task.clientAuditDetails!.createdTime, + lastModifiedBy: event.task.auditDetails?.lastModifiedBy ?? + event.task.clientAuditDetails!.createdBy, + lastModifiedTime: DateTime.now().millisecondsSinceEpoch, + ) + : null, + )); + } + + emit(state.copyWith( + oldTask: event.task, + householdMemberWrapper: event.householdMemberWrapper)); // Update an existing task - await taskRepository.update(event.task.copyWith( - clientAuditDetails: - (event.task.clientAuditDetails?.createdBy != null && - event.task.clientAuditDetails?.createdTime != null) - ? ClientAuditDetails( - createdBy: event.task.clientAuditDetails!.createdBy, - createdTime: event.task.clientAuditDetails!.createdTime, - lastModifiedBy: event.task.auditDetails?.lastModifiedBy ?? - event.task.clientAuditDetails!.createdBy, - lastModifiedTime: DateTime.now().millisecondsSinceEpoch, - ) - : null, - )); } else { // Create a new task final code = event.boundaryModel.code; @@ -59,14 +67,17 @@ class DeliverInterventionBloc ? null : LocalityModel(code: code, name: name); - await taskRepository.create(event.task.copyWith( - address: event.task.address?.copyWith( - locality: localityModel, - ), - )); + if (!event.navigateToSummary) { + await taskRepository.create(event.task.copyWith( + address: event.task.address?.copyWith( + locality: localityModel, + ), + )); + } + emit(state.copyWith( - oldTask: event.task, - )); + oldTask: event.task, + householdMemberWrapper: event.householdMemberWrapper)); } } catch (error) { rethrow; @@ -87,16 +98,17 @@ class DeliverInterventionBloc ); final List futureTask = tasks - .where((element) => - element.additionalFields?.fields - .firstWhere( - (a) => - a.key == - AdditionalFieldsType.deliveryStrategy.toValue(), - ) - .value == - DeliverStrategyType.indirect.toValue() && - element.status == Status.delivered.toValue()) + .where((element) => element.additionalFields != null + ? element.additionalFields!.fields + .firstWhereOrNull( + (a) => + a.key == + AdditionalFieldsType.deliveryStrategy.toValue(), + ) + ?.value == + DeliverStrategyType.indirect.toValue() && + element.status == Status.delivered.toValue() + : false) .toList(); if (tasks.isNotEmpty) { @@ -242,6 +254,8 @@ class DeliverInterventionEvent with _$DeliverInterventionEvent { required TaskModel task, required bool isEditing, required BoundaryModel boundaryModel, + @Default(false) bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper, }) = DeliverInterventionSubmitEvent; const factory DeliverInterventionEvent.handleSearch({ @@ -272,6 +286,7 @@ class DeliverInterventionState with _$DeliverInterventionState { List? pastCycles, @Default(true) bool hasCycleArrived, @Default(false) bool isLastDoseOfCycle, + HouseholdMemberWrapper? householdMemberWrapper, List? tasks, List? futureDeliveries, List? futureTask, diff --git a/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.freezed.dart b/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.freezed.dart index 496a94259..fd519292a 100644 --- a/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.freezed.dart +++ b/packages/registration_delivery/lib/blocs/delivery_intervention/deliver_intervention.freezed.dart @@ -19,7 +19,11 @@ mixin _$DeliverInterventionEvent { @optionalTypeArgs TResult when({ required TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel) + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper) handleSubmit, required TResult Function(TaskSearchModel taskSearch) handleSearch, required TResult Function( @@ -33,7 +37,11 @@ mixin _$DeliverInterventionEvent { @optionalTypeArgs TResult? whenOrNull({ TResult? Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult? Function(TaskSearchModel taskSearch)? handleSearch, TResult? Function( @@ -47,7 +55,11 @@ mixin _$DeliverInterventionEvent { @optionalTypeArgs TResult maybeWhen({ TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult Function(TaskSearchModel taskSearch)? handleSearch, TResult Function( @@ -122,7 +134,14 @@ abstract class _$$DeliverInterventionSubmitEventImplCopyWith<$Res> { $Res Function(_$DeliverInterventionSubmitEventImpl) then) = __$$DeliverInterventionSubmitEventImplCopyWithImpl<$Res>; @useResult - $Res call({TaskModel task, bool isEditing, BoundaryModel boundaryModel}); + $Res call( + {TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper}); + + $HouseholdMemberWrapperCopyWith<$Res>? get householdMemberWrapper; } /// @nodoc @@ -141,6 +160,8 @@ class __$$DeliverInterventionSubmitEventImplCopyWithImpl<$Res> Object? task = null, Object? isEditing = null, Object? boundaryModel = null, + Object? navigateToSummary = null, + Object? householdMemberWrapper = freezed, }) { return _then(_$DeliverInterventionSubmitEventImpl( task: null == task @@ -155,8 +176,29 @@ class __$$DeliverInterventionSubmitEventImplCopyWithImpl<$Res> ? _value.boundaryModel : boundaryModel // ignore: cast_nullable_to_non_nullable as BoundaryModel, + navigateToSummary: null == navigateToSummary + ? _value.navigateToSummary + : navigateToSummary // ignore: cast_nullable_to_non_nullable + as bool, + householdMemberWrapper: freezed == householdMemberWrapper + ? _value.householdMemberWrapper + : householdMemberWrapper // ignore: cast_nullable_to_non_nullable + as HouseholdMemberWrapper?, )); } + + @override + @pragma('vm:prefer-inline') + $HouseholdMemberWrapperCopyWith<$Res>? get householdMemberWrapper { + if (_value.householdMemberWrapper == null) { + return null; + } + + return $HouseholdMemberWrapperCopyWith<$Res>(_value.householdMemberWrapper!, + (value) { + return _then(_value.copyWith(householdMemberWrapper: value)); + }); + } } /// @nodoc @@ -166,7 +208,9 @@ class _$DeliverInterventionSubmitEventImpl const _$DeliverInterventionSubmitEventImpl( {required this.task, required this.isEditing, - required this.boundaryModel}); + required this.boundaryModel, + this.navigateToSummary = false, + this.householdMemberWrapper}); @override final TaskModel task; @@ -174,10 +218,15 @@ class _$DeliverInterventionSubmitEventImpl final bool isEditing; @override final BoundaryModel boundaryModel; + @override + @JsonKey() + final bool navigateToSummary; + @override + final HouseholdMemberWrapper? householdMemberWrapper; @override String toString() { - return 'DeliverInterventionEvent.handleSubmit(task: $task, isEditing: $isEditing, boundaryModel: $boundaryModel)'; + return 'DeliverInterventionEvent.handleSubmit(task: $task, isEditing: $isEditing, boundaryModel: $boundaryModel, navigateToSummary: $navigateToSummary, householdMemberWrapper: $householdMemberWrapper)'; } @override @@ -189,11 +238,16 @@ class _$DeliverInterventionSubmitEventImpl (identical(other.isEditing, isEditing) || other.isEditing == isEditing) && (identical(other.boundaryModel, boundaryModel) || - other.boundaryModel == boundaryModel)); + other.boundaryModel == boundaryModel) && + (identical(other.navigateToSummary, navigateToSummary) || + other.navigateToSummary == navigateToSummary) && + (identical(other.householdMemberWrapper, householdMemberWrapper) || + other.householdMemberWrapper == householdMemberWrapper)); } @override - int get hashCode => Object.hash(runtimeType, task, isEditing, boundaryModel); + int get hashCode => Object.hash(runtimeType, task, isEditing, boundaryModel, + navigateToSummary, householdMemberWrapper); @JsonKey(ignore: true) @override @@ -207,7 +261,11 @@ class _$DeliverInterventionSubmitEventImpl @optionalTypeArgs TResult when({ required TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel) + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper) handleSubmit, required TResult Function(TaskSearchModel taskSearch) handleSearch, required TResult Function( @@ -217,14 +275,19 @@ class _$DeliverInterventionSubmitEventImpl IndividualModel? individualModel, ProjectTypeModel projectType) setActiveCycleDose, }) { - return handleSubmit(task, isEditing, boundaryModel); + return handleSubmit(task, isEditing, boundaryModel, navigateToSummary, + householdMemberWrapper); } @override @optionalTypeArgs TResult? whenOrNull({ TResult? Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult? Function(TaskSearchModel taskSearch)? handleSearch, TResult? Function( @@ -234,14 +297,19 @@ class _$DeliverInterventionSubmitEventImpl IndividualModel? individualModel, ProjectTypeModel projectType)? setActiveCycleDose, }) { - return handleSubmit?.call(task, isEditing, boundaryModel); + return handleSubmit?.call(task, isEditing, boundaryModel, navigateToSummary, + householdMemberWrapper); } @override @optionalTypeArgs TResult maybeWhen({ TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult Function(TaskSearchModel taskSearch)? handleSearch, TResult Function( @@ -253,7 +321,8 @@ class _$DeliverInterventionSubmitEventImpl required TResult orElse(), }) { if (handleSubmit != null) { - return handleSubmit(task, isEditing, boundaryModel); + return handleSubmit(task, isEditing, boundaryModel, navigateToSummary, + householdMemberWrapper); } return orElse(); } @@ -311,12 +380,16 @@ abstract class DeliverInterventionSubmitEvent const factory DeliverInterventionSubmitEvent( {required final TaskModel task, required final bool isEditing, - required final BoundaryModel boundaryModel}) = + required final BoundaryModel boundaryModel, + final bool navigateToSummary, + final HouseholdMemberWrapper? householdMemberWrapper}) = _$DeliverInterventionSubmitEventImpl; TaskModel get task; bool get isEditing; BoundaryModel get boundaryModel; + bool get navigateToSummary; + HouseholdMemberWrapper? get householdMemberWrapper; @JsonKey(ignore: true) _$$DeliverInterventionSubmitEventImplCopyWith< _$DeliverInterventionSubmitEventImpl> @@ -395,7 +468,11 @@ class _$DeliverInterventionSearchEventImpl @optionalTypeArgs TResult when({ required TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel) + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper) handleSubmit, required TResult Function(TaskSearchModel taskSearch) handleSearch, required TResult Function( @@ -412,7 +489,11 @@ class _$DeliverInterventionSearchEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult? Function(TaskSearchModel taskSearch)? handleSearch, TResult? Function( @@ -429,7 +510,11 @@ class _$DeliverInterventionSearchEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult Function(TaskSearchModel taskSearch)? handleSearch, TResult Function( @@ -603,7 +688,11 @@ class _$DeliverInterventionCycleFutureDoseSelectionEventImpl @optionalTypeArgs TResult when({ required TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel) + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper) handleSubmit, required TResult Function(TaskSearchModel taskSearch) handleSearch, required TResult Function( @@ -620,7 +709,11 @@ class _$DeliverInterventionCycleFutureDoseSelectionEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult? Function(TaskSearchModel taskSearch)? handleSearch, TResult? Function( @@ -637,7 +730,11 @@ class _$DeliverInterventionCycleFutureDoseSelectionEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult Function(TaskSearchModel taskSearch)? handleSearch, TResult Function( @@ -834,7 +931,11 @@ class _$DeliverInterventionActiveCycleDoseSelectionEventImpl @optionalTypeArgs TResult when({ required TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel) + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper) handleSubmit, required TResult Function(TaskSearchModel taskSearch) handleSearch, required TResult Function( @@ -852,7 +953,11 @@ class _$DeliverInterventionActiveCycleDoseSelectionEventImpl @optionalTypeArgs TResult? whenOrNull({ TResult? Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult? Function(TaskSearchModel taskSearch)? handleSearch, TResult? Function( @@ -870,7 +975,11 @@ class _$DeliverInterventionActiveCycleDoseSelectionEventImpl @optionalTypeArgs TResult maybeWhen({ TResult Function( - TaskModel task, bool isEditing, BoundaryModel boundaryModel)? + TaskModel task, + bool isEditing, + BoundaryModel boundaryModel, + bool navigateToSummary, + HouseholdMemberWrapper? householdMemberWrapper)? handleSubmit, TResult Function(TaskSearchModel taskSearch)? handleSearch, TResult Function( @@ -964,6 +1073,8 @@ mixin _$DeliverInterventionState { List? get pastCycles => throw _privateConstructorUsedError; bool get hasCycleArrived => throw _privateConstructorUsedError; bool get isLastDoseOfCycle => throw _privateConstructorUsedError; + HouseholdMemberWrapper? get householdMemberWrapper => + throw _privateConstructorUsedError; List? get tasks => throw _privateConstructorUsedError; List? get futureDeliveries => throw _privateConstructorUsedError; @@ -989,10 +1100,13 @@ abstract class $DeliverInterventionStateCopyWith<$Res> { List? pastCycles, bool hasCycleArrived, bool isLastDoseOfCycle, + HouseholdMemberWrapper? householdMemberWrapper, List? tasks, List? futureDeliveries, List? futureTask, TaskModel? oldTask}); + + $HouseholdMemberWrapperCopyWith<$Res>? get householdMemberWrapper; } /// @nodoc @@ -1016,6 +1130,7 @@ class _$DeliverInterventionStateCopyWithImpl<$Res, Object? pastCycles = freezed, Object? hasCycleArrived = null, Object? isLastDoseOfCycle = null, + Object? householdMemberWrapper = freezed, Object? tasks = freezed, Object? futureDeliveries = freezed, Object? futureTask = freezed, @@ -1050,6 +1165,10 @@ class _$DeliverInterventionStateCopyWithImpl<$Res, ? _value.isLastDoseOfCycle : isLastDoseOfCycle // ignore: cast_nullable_to_non_nullable as bool, + householdMemberWrapper: freezed == householdMemberWrapper + ? _value.householdMemberWrapper + : householdMemberWrapper // ignore: cast_nullable_to_non_nullable + as HouseholdMemberWrapper?, tasks: freezed == tasks ? _value.tasks : tasks // ignore: cast_nullable_to_non_nullable @@ -1068,6 +1187,19 @@ class _$DeliverInterventionStateCopyWithImpl<$Res, as TaskModel?, ) as $Val); } + + @override + @pragma('vm:prefer-inline') + $HouseholdMemberWrapperCopyWith<$Res>? get householdMemberWrapper { + if (_value.householdMemberWrapper == null) { + return null; + } + + return $HouseholdMemberWrapperCopyWith<$Res>(_value.householdMemberWrapper!, + (value) { + return _then(_value.copyWith(householdMemberWrapper: value) as $Val); + }); + } } /// @nodoc @@ -1087,10 +1219,14 @@ abstract class _$$DeliverInterventionStateImplCopyWith<$Res> List? pastCycles, bool hasCycleArrived, bool isLastDoseOfCycle, + HouseholdMemberWrapper? householdMemberWrapper, List? tasks, List? futureDeliveries, List? futureTask, TaskModel? oldTask}); + + @override + $HouseholdMemberWrapperCopyWith<$Res>? get householdMemberWrapper; } /// @nodoc @@ -1113,6 +1249,7 @@ class __$$DeliverInterventionStateImplCopyWithImpl<$Res> Object? pastCycles = freezed, Object? hasCycleArrived = null, Object? isLastDoseOfCycle = null, + Object? householdMemberWrapper = freezed, Object? tasks = freezed, Object? futureDeliveries = freezed, Object? futureTask = freezed, @@ -1147,6 +1284,10 @@ class __$$DeliverInterventionStateImplCopyWithImpl<$Res> ? _value.isLastDoseOfCycle : isLastDoseOfCycle // ignore: cast_nullable_to_non_nullable as bool, + householdMemberWrapper: freezed == householdMemberWrapper + ? _value.householdMemberWrapper + : householdMemberWrapper // ignore: cast_nullable_to_non_nullable + as HouseholdMemberWrapper?, tasks: freezed == tasks ? _value._tasks : tasks // ignore: cast_nullable_to_non_nullable @@ -1178,6 +1319,7 @@ class _$DeliverInterventionStateImpl implements _DeliverInterventionState { final List? pastCycles, this.hasCycleArrived = true, this.isLastDoseOfCycle = false, + this.householdMemberWrapper, final List? tasks, final List? futureDeliveries, final List? futureTask, @@ -1215,6 +1357,8 @@ class _$DeliverInterventionStateImpl implements _DeliverInterventionState { @override @JsonKey() final bool isLastDoseOfCycle; + @override + final HouseholdMemberWrapper? householdMemberWrapper; final List? _tasks; @override List? get tasks { @@ -1251,7 +1395,7 @@ class _$DeliverInterventionStateImpl implements _DeliverInterventionState { @override String toString() { - return 'DeliverInterventionState(loading: $loading, isEditing: $isEditing, cycle: $cycle, dose: $dose, pastCycles: $pastCycles, hasCycleArrived: $hasCycleArrived, isLastDoseOfCycle: $isLastDoseOfCycle, tasks: $tasks, futureDeliveries: $futureDeliveries, futureTask: $futureTask, oldTask: $oldTask)'; + return 'DeliverInterventionState(loading: $loading, isEditing: $isEditing, cycle: $cycle, dose: $dose, pastCycles: $pastCycles, hasCycleArrived: $hasCycleArrived, isLastDoseOfCycle: $isLastDoseOfCycle, householdMemberWrapper: $householdMemberWrapper, tasks: $tasks, futureDeliveries: $futureDeliveries, futureTask: $futureTask, oldTask: $oldTask)'; } @override @@ -1270,6 +1414,8 @@ class _$DeliverInterventionStateImpl implements _DeliverInterventionState { other.hasCycleArrived == hasCycleArrived) && (identical(other.isLastDoseOfCycle, isLastDoseOfCycle) || other.isLastDoseOfCycle == isLastDoseOfCycle) && + (identical(other.householdMemberWrapper, householdMemberWrapper) || + other.householdMemberWrapper == householdMemberWrapper) && const DeepCollectionEquality().equals(other._tasks, _tasks) && const DeepCollectionEquality() .equals(other._futureDeliveries, _futureDeliveries) && @@ -1288,6 +1434,7 @@ class _$DeliverInterventionStateImpl implements _DeliverInterventionState { const DeepCollectionEquality().hash(_pastCycles), hasCycleArrived, isLastDoseOfCycle, + householdMemberWrapper, const DeepCollectionEquality().hash(_tasks), const DeepCollectionEquality().hash(_futureDeliveries), const DeepCollectionEquality().hash(_futureTask), @@ -1310,6 +1457,7 @@ abstract class _DeliverInterventionState implements DeliverInterventionState { final List? pastCycles, final bool hasCycleArrived, final bool isLastDoseOfCycle, + final HouseholdMemberWrapper? householdMemberWrapper, final List? tasks, final List? futureDeliveries, final List? futureTask, @@ -1330,6 +1478,8 @@ abstract class _DeliverInterventionState implements DeliverInterventionState { @override bool get isLastDoseOfCycle; @override + HouseholdMemberWrapper? get householdMemberWrapper; + @override List? get tasks; @override List? get futureDeliveries; diff --git a/packages/registration_delivery/lib/blocs/household_overview/household_overview.dart b/packages/registration_delivery/lib/blocs/household_overview/household_overview.dart index 4130fcc74..4a6c6354f 100644 --- a/packages/registration_delivery/lib/blocs/household_overview/household_overview.dart +++ b/packages/registration_delivery/lib/blocs/household_overview/household_overview.dart @@ -69,9 +69,10 @@ class HouseholdOverviewBloc // Retrieve household members based on certain criteria. final members = await householdMemberRepository.search( HouseholdMemberSearchModel( - householdClientReferenceId: [ - state.householdMemberWrapper.household.clientReferenceId - ], + householdClientReferenceId: + state.householdMemberWrapper.household != null + ? [state.householdMemberWrapper.household!.clientReferenceId] + : [], ), ); @@ -81,7 +82,7 @@ class HouseholdOverviewBloc ); final householdId = - state.householdMemberWrapper.household.clientReferenceId; + state.householdMemberWrapper.household?.clientReferenceId; // Check if the current household has any members. if (!groupedHouseholds.containsKey(householdId)) { @@ -102,7 +103,8 @@ class HouseholdOverviewBloc // Search for households with the specified client reference ID. final households = await householdRepository.search( - HouseholdSearchModel(clientReferenceId: [householdId]), + HouseholdSearchModel( + clientReferenceId: householdId != null ? [householdId] : []), ); // Check if any households were found. diff --git a/packages/registration_delivery/lib/blocs/search_households/household_global_seach.dart b/packages/registration_delivery/lib/blocs/search_households/household_global_seach.dart new file mode 100644 index 000000000..332d43054 --- /dev/null +++ b/packages/registration_delivery/lib/blocs/search_households/household_global_seach.dart @@ -0,0 +1,350 @@ +import 'dart:async'; +import 'package:collection/collection.dart'; +import 'package:digit_data_model/models/entities/individual.dart'; +import 'package:registration_delivery/blocs/search_households/search_households.dart'; +import 'package:registration_delivery/utils/utils.dart'; + +import '../../models/entities/household.dart'; +import '../../models/entities/household_member.dart'; +import '../../models/entities/project_beneficiary.dart'; +import '../../models/entities/referral.dart'; +import '../../models/entities/side_effect.dart'; +import '../../models/entities/status.dart'; +import '../../models/entities/task.dart'; +import '../../utils/global_search_parameters.dart'; + +class HouseHoldGlobalSearchBloc extends SearchHouseholdsBloc { + HouseHoldGlobalSearchBloc({ + required super.userUid, + required super.projectId, + required super.individual, + required super.householdMember, + required super.household, + required super.projectBeneficiary, + required super.taskDataRepository, + required super.beneficiaryType, + required super.sideEffectDataRepository, + required super.addressRepository, + required super.referralDataRepository, + required super.individualGlobalSearchRepository, + required super.houseHoldGlobalSearchRepository, + }) { + on(_houseHoldGlobalSearch); + } + + Future _houseHoldGlobalSearch( + HouseHoldGlobalSearchEvent event, + SearchHouseholdsEmitter emit, + ) async { + final containers = [...state.householdMembers]; + + List householdList = []; + List individualsList = []; + List householdMembersList = []; + List projectBeneficiariesList = []; + List taskList = []; + List sideEffectsList = []; + List referralsList = []; + + emit(state.copyWith(loading: true)); + + final results = await houseHoldGlobalSearchRepository.houseHoldGlobalSearch( + GlobalSearchParameters( + projectId: event.globalSearchParams.projectId, + isProximityEnabled: event.globalSearchParams.isProximityEnabled, + latitude: event.globalSearchParams.latitude, + longitude: event.globalSearchParams.longitude, + maxRadius: event.globalSearchParams.maxRadius, + nameSearch: event.globalSearchParams.nameSearch, + filter: event.globalSearchParams.filter, + offset: event.globalSearchParams.offset, + limit: event.globalSearchParams.limit, + totalCount: state.totalResults), + ); + + var totalCount = results['total_count']; + var finalResults = results['data'].map((e) => e).toList(); + + if (event.globalSearchParams.filter!.contains(Status.registered.name) || + event.globalSearchParams.filter!.contains(Status.notRegistered.name)) { + late List houseHoldClientReferenceIds = []; + + finalResults.forEach((e) { + houseHoldClientReferenceIds.add(e.clientReferenceId); + }); + + householdList = await household.search(HouseholdSearchModel( + clientReferenceId: + houseHoldClientReferenceIds.map((e) => e.toString()).toList())); + + // Search for individual results using the extracted IDs and search text. + householdMembersList = await fetchHouseholdMembersBulk( + null, + houseHoldClientReferenceIds, + ); + + final List individualClientReferenceIds = householdMembersList + .map((e) => e.individualClientReferenceId.toString()) + .toList(); + + individualsList = await individual.search( + IndividualSearchModel(clientReferenceId: individualClientReferenceIds), + ); + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + beneficiaryClientReferenceId: + houseHoldClientReferenceIds.map((e) => e).toList())); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + // Process household entries and add to containers + await _processHouseholdEntries( + householdMembersList, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers, + ); + } else if (event.globalSearchParams.filter!.isNotEmpty && + event.globalSearchParams.filter != null) { + late List listOfBeneficiaries = []; + for (var e in finalResults) { + !listOfBeneficiaries.contains(e.projectBeneficiaryClientReferenceId) + ? listOfBeneficiaries.add(e.projectBeneficiaryClientReferenceId!) + : null; + } + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + clientReferenceId: listOfBeneficiaries)); + + late List listOfMembers = []; + + listOfMembers = projectBeneficiariesList + .map((e) => e.beneficiaryClientReferenceId.toString()) + .toList(); + + householdMembersList = await fetchHouseholdMembersBulk( + null, + listOfMembers, + ); + + final List individualClientReferenceIds = householdMembersList + .map((e) => e.individualClientReferenceId.toString()) + .toList(); + + individualsList = await individual.search( + IndividualSearchModel(clientReferenceId: individualClientReferenceIds), + ); + + late List houseHoldClientReferenceIds = []; + + houseHoldClientReferenceIds = householdMembersList + .map((e) => e.householdClientReferenceId.toString()) + .toList(); + + householdList = await household.search(HouseholdSearchModel( + clientReferenceId: houseHoldClientReferenceIds, + )); + + finalResults.forEach((element) { + taskList.add(element); + }); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + // Process household entries and add to containers + await _processHouseholdEntries( + householdMembersList, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers, + ); + } else { + late List houseHoldClientReferenceIds = []; + + finalResults.forEach((e) { + houseHoldClientReferenceIds.add(e.clientReferenceId); + }); + + householdList = await household.search(HouseholdSearchModel( + clientReferenceId: + houseHoldClientReferenceIds.map((e) => e.toString()).toList())); + + // Search for individual results using the extracted IDs and search text. + householdMembersList = await fetchHouseholdMembersBulk( + null, + houseHoldClientReferenceIds, + ); + + final List individualClientReferenceIds = householdMembersList + .map((e) => e.individualClientReferenceId.toString()) + .toList(); + + individualsList = await individual.search( + IndividualSearchModel(clientReferenceId: individualClientReferenceIds), + ); + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + beneficiaryClientReferenceId: + houseHoldClientReferenceIds.map((e) => e).toList())); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + // Process household entries and add to containers + await _processHouseholdEntries( + householdMembersList, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers, + ); + } + emit(state.copyWith( + householdMembers: containers, + loading: false, + searchQuery: event.globalSearchParams.nameSearch, + offset: + event.globalSearchParams.offset! + event.globalSearchParams.limit!, + limit: event.globalSearchParams.limit!, + totalResults: containers.isEmpty ? 0 : totalCount, + )); + } + + Future _processHouseholdEntries( + List householdMembersList, + List householdList, + List individualsList, + List projectBeneficiariesList, + List taskList, + List sideEffectsList, + List referralsList, + List containers, + ) async { + final groupedHouseholdsMembers = householdMembersList + .groupListsBy((element) => element.householdClientReferenceId); + + for (final entry in groupedHouseholdsMembers.entries) { + HouseholdModel filteredHousehold; + List filteredIndividuals; + List filteredTasks = []; + List filteredBeneficiaries = []; + final householdId = entry.key; + if (householdId == null) continue; + + // Filter household based on household ID + filteredHousehold = + householdList.firstWhere((e) => e.clientReferenceId == householdId); + + // Extract individual client reference IDs from household members + final List membersIds = + entry.value.map((e) => e.individualClientReferenceId).toList(); + + // Filter individuals based on individual client reference IDs + filteredIndividuals = individualsList + .where((element) => membersIds.contains(element.clientReferenceId)) + .toList(); + + // Filter beneficiaries based on filtered household client reference IDs + filteredBeneficiaries = projectBeneficiariesList + .where((element) => + element.beneficiaryClientReferenceId == + filteredHousehold.clientReferenceId) + .toList(); + + // Filter tasks based on project beneficiary client reference IDs + for (var beneficiary in filteredBeneficiaries) { + var tasksForBeneficiary = taskList.where((element) => + beneficiary.clientReferenceId == + element.projectBeneficiaryClientReferenceId); + + filteredTasks.addAll(tasksForBeneficiary); + } + + // Find the head of the household + final head = filteredIndividuals.firstWhereOrNull( + (element) => + element.clientReferenceId == + entry.value + .firstWhereOrNull( + (element) => element.isHeadOfHousehold, + ) + ?.individualClientReferenceId, + ); + + // Skip if no head of household or no filtered beneficiaries + if (head == null) continue; + + // Add household member wrapper to containers + containers.add( + HouseholdMemberWrapper( + household: filteredHousehold, + headOfHousehold: head, + members: filteredIndividuals, + projectBeneficiaries: filteredBeneficiaries, + tasks: filteredTasks.isEmpty ? null : filteredTasks, + sideEffects: sideEffectsList.isEmpty ? null : sideEffectsList, + referrals: referralsList.isEmpty ? null : referralsList, + ), + ); + } + } + + Future> _processTasksAndRelatedData( + List projectBeneficiariesList, + List taskList, + List sideEffectsList, + List referralsList, + ) async { + if (projectBeneficiariesList.isNotEmpty) { + if (taskList.isEmpty) { + taskList = + await fetchTaskbyProjectBeneficiary(projectBeneficiariesList); + } + sideEffectsList = + await sideEffectDataRepository.search(SideEffectSearchModel( + taskClientReferenceId: + taskList.map((e) => e.clientReferenceId).toList(), + )); + referralsList = await referralDataRepository.search(ReferralSearchModel( + projectBeneficiaryClientReferenceId: + projectBeneficiariesList.map((e) => e.clientReferenceId).toList(), + )); + } + return [ + taskList, + sideEffectsList, + referralsList, + ]; + } +} diff --git a/packages/registration_delivery/lib/blocs/search_households/individual_global_search.dart b/packages/registration_delivery/lib/blocs/search_households/individual_global_search.dart new file mode 100644 index 000000000..696df872e --- /dev/null +++ b/packages/registration_delivery/lib/blocs/search_households/individual_global_search.dart @@ -0,0 +1,344 @@ +import 'dart:async'; + +import 'package:collection/collection.dart'; +import 'package:digit_data_model/models/entities/individual.dart'; +import 'package:registration_delivery/blocs/search_households/search_households.dart'; + +import '../../models/entities/household.dart'; +import '../../models/entities/household_member.dart'; +import '../../models/entities/project_beneficiary.dart'; +import '../../models/entities/referral.dart'; +import '../../models/entities/side_effect.dart'; +import '../../models/entities/status.dart'; +import '../../models/entities/task.dart'; +import '../../utils/global_search_parameters.dart'; +import '../../utils/utils.dart'; + +class IndividualGlobalSearchBloc extends SearchHouseholdsBloc { + IndividualGlobalSearchBloc( + {required super.userUid, + required super.projectId, + required super.individual, + required super.householdMember, + required super.household, + required super.projectBeneficiary, + required super.taskDataRepository, + required super.beneficiaryType, + required super.sideEffectDataRepository, + required super.addressRepository, + required super.referralDataRepository, + required super.individualGlobalSearchRepository, + required super.houseHoldGlobalSearchRepository}) { + on(_individualGlobalSearch); + } + + Future _individualGlobalSearch( + IndividualGlobalSearchEvent event, + SearchHouseholdsEmitter emit, + ) async { + final containers = [...state.householdMembers]; + + List householdList = []; + List individualsList = []; + List householdMembersList = []; + List projectBeneficiariesList = []; + List taskList = []; + List sideEffectsList = []; + List referralsList = []; + + emit(state.copyWith(loading: true)); + + final results = + await individualGlobalSearchRepository.individualGlobalSearch( + GlobalSearchParameters( + projectId: event.globalSearchParams.projectId, + isProximityEnabled: event.globalSearchParams.isProximityEnabled, + latitude: event.globalSearchParams.latitude, + longitude: event.globalSearchParams.longitude, + maxRadius: event.globalSearchParams.maxRadius, + nameSearch: event.globalSearchParams.nameSearch, + filter: event.globalSearchParams.filter, + offset: event.globalSearchParams.offset, + limit: event.globalSearchParams.limit, + totalCount: state.totalResults, + ), + ); + + var totalCount = results['total_count']; + var finalResults = results['data'].map((e) => e).toList(); + + if (event.globalSearchParams.filter!.contains(Status.registered.name) || + event.globalSearchParams.filter!.contains(Status.notRegistered.name)) { + late List individualClientReferenceIds = []; + + finalResults.forEach((e) { + individualClientReferenceIds.add(e.clientReferenceId); + }); + + individualsList = await individual.search(IndividualSearchModel( + clientReferenceId: + individualClientReferenceIds.map((e) => e.toString()).toList())); + + final List householdMembers = + await fetchHouseholdMembersBulk( + individualClientReferenceIds, + null, + ); + + final houseHoldIds = + householdMembers.map((e) => e.householdClientReferenceId!).toList(); + + householdList = await household.search( + HouseholdSearchModel( + clientReferenceId: houseHoldIds, + ), + ); + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + beneficiaryClientReferenceId: + individualClientReferenceIds.map((e) => e).toList())); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + await _processHouseholdEntries( + householdMembers, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers); + } else if (event.globalSearchParams.filter!.isNotEmpty && + event.globalSearchParams.filter != null) { + late List listOfBeneficiaries = []; + for (var e in finalResults) { + !listOfBeneficiaries.contains(e.projectBeneficiaryClientReferenceId) + ? listOfBeneficiaries.add(e.projectBeneficiaryClientReferenceId!) + : null; + } + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + clientReferenceId: listOfBeneficiaries)); + + late List listOfMembers = []; + + listOfMembers = projectBeneficiariesList + .map((e) => e.beneficiaryClientReferenceId.toString()) + .toList(); + + householdMembersList = await fetchHouseholdMembersBulk( + listOfMembers, + null, + ); + + final List individualClientReferenceIds = householdMembersList + .map((e) => e.individualClientReferenceId.toString()) + .toList(); + + individualsList = await individual.search( + IndividualSearchModel(clientReferenceId: individualClientReferenceIds), + ); + + late List houseHoldClientReferenceIds = []; + + houseHoldClientReferenceIds = householdMembersList + .map((e) => e.householdClientReferenceId.toString()) + .toList(); + + householdList = await household.search(HouseholdSearchModel( + clientReferenceId: houseHoldClientReferenceIds, + )); + + finalResults.forEach((element) { + taskList.add(element); + }); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + // Process household entries and add to containers + await _processHouseholdEntries( + householdMembersList, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers, + ); + } else { + late List individualClientReferenceIds = []; + + finalResults.forEach((e) { + individualClientReferenceIds.add(e.clientReferenceId); + }); + + individualsList = await individual.search(IndividualSearchModel( + clientReferenceId: + individualClientReferenceIds.map((e) => e.toString()).toList())); + + // Search for individual results using the extracted IDs and search text. + final List householdMembers = + await fetchHouseholdMembersBulk( + individualClientReferenceIds, + null, + ); + + householdList = await household.search(HouseholdSearchModel( + clientReferenceId: householdMembers + .map((e) => e.householdClientReferenceId.toString()) + .toList(), + )); + + projectBeneficiariesList = await projectBeneficiary.search( + ProjectBeneficiarySearchModel( + projectId: [RegistrationDeliverySingleton().projectId.toString()], + beneficiaryClientReferenceId: + individualClientReferenceIds.map((e) => e).toList())); + + List tasksRelated = await _processTasksAndRelatedData( + projectBeneficiariesList, taskList, sideEffectsList, referralsList); + + taskList = tasksRelated[0]; + sideEffectsList = tasksRelated[1]; + referralsList = tasksRelated[2]; + + await _processHouseholdEntries( + householdMembers, + householdList, + individualsList, + projectBeneficiariesList, + taskList, + sideEffectsList, + referralsList, + containers); + } + + emit(state.copyWith( + householdMembers: containers, + loading: false, + searchQuery: event.globalSearchParams.nameSearch, + offset: + event.globalSearchParams.offset! + event.globalSearchParams.limit!, + limit: event.globalSearchParams.limit!, + totalResults: totalCount, + )); + } + + _processHouseholdEntries( + List householdMembers, + List householdList, + List individualsList, + List projectBeneficiariesList, + List taskList, + List sideEffectsList, + List referralsList, + List containers) async { + // Group household members by household client reference ID + final groupedHouseholdsMembers = householdMembers + .groupListsBy((element) => element.householdClientReferenceId); + + for (final entry in groupedHouseholdsMembers.entries) { + HouseholdModel filteredHousehold; + List filteredIndividuals; + List filteredTasks = []; + List filteredBeneficiaries = []; + final householdId = entry.key; + if (householdId == null) continue; + + // Filter household based on household ID + filteredHousehold = + householdList.firstWhere((e) => e.clientReferenceId == householdId); + + // Extract individual client reference IDs from household members + final List membersIds = + entry.value.map((e) => e.individualClientReferenceId).toList(); + + // Filter individuals based on individual client reference IDs + filteredIndividuals = individualsList + .where((element) => membersIds.contains(element.clientReferenceId)) + .toList(); + + // Filter beneficiaries based on individual client reference IDs + filteredBeneficiaries = projectBeneficiariesList + .where((element) => + membersIds.contains(element.beneficiaryClientReferenceId)) + .toList(); + + // Filter tasks based on project beneficiary client reference IDs + for (var beneficiary in filteredBeneficiaries) { + var tasksForBeneficiary = taskList.where((element) => + beneficiary.clientReferenceId == + element.projectBeneficiaryClientReferenceId); + + filteredTasks.addAll(tasksForBeneficiary); + } + + // Find the head of the household + final head = filteredIndividuals.firstWhereOrNull( + (element) => + element.clientReferenceId == + entry.value + .firstWhereOrNull( + (element) => element.isHeadOfHousehold, + ) + ?.individualClientReferenceId, + ); + + // Skip if no head of household or no filtered beneficiaries + if (head == null) continue; + + // Add household member wrapper to containers + containers.add( + HouseholdMemberWrapper( + household: filteredHousehold, + headOfHousehold: head, + members: filteredIndividuals, + projectBeneficiaries: filteredBeneficiaries, + tasks: filteredTasks.isEmpty ? null : filteredTasks, + sideEffects: sideEffectsList.isEmpty ? null : sideEffectsList, + referrals: referralsList.isEmpty ? null : referralsList, + ), + ); + } + } + + _processTasksAndRelatedData( + List projectBeneficiariesList, + List taskList, + List sideEffectsList, + List referralsList) async { + if (projectBeneficiariesList.isNotEmpty) { + if (taskList.isEmpty) { + taskList = + await fetchTaskbyProjectBeneficiary(projectBeneficiariesList); + } + sideEffectsList = + await sideEffectDataRepository.search(SideEffectSearchModel( + taskClientReferenceId: + taskList.map((e) => e.clientReferenceId).toList(), + )); + referralsList = await referralDataRepository.search(ReferralSearchModel( + projectBeneficiaryClientReferenceId: + projectBeneficiariesList.map((e) => e.clientReferenceId).toList(), + )); + } + + return [taskList, sideEffectsList, referralsList]; + } +} diff --git a/packages/registration_delivery/lib/blocs/search_households/proximity_search.dart b/packages/registration_delivery/lib/blocs/search_households/proximity_search.dart deleted file mode 100644 index 771582ea8..000000000 --- a/packages/registration_delivery/lib/blocs/search_households/proximity_search.dart +++ /dev/null @@ -1,171 +0,0 @@ -import 'dart:async'; - -import 'package:collection/collection.dart'; -import 'package:digit_data_model/data_model.dart'; - -import '../../models/entities/household.dart'; -import '../../models/entities/household_member.dart'; -import '../../models/entities/project_beneficiary.dart'; -import '../../models/entities/referral.dart'; -import '../../models/entities/side_effect.dart'; -import '../../models/entities/task.dart'; -import 'search_households.dart'; - -class ProximitySearchBloc extends SearchHouseholdsBloc { - ProximitySearchBloc({ - required super.userUid, - required super.projectId, - required super.individual, - required super.householdMember, - required super.household, - required super.projectBeneficiary, - required super.taskDataRepository, - required super.beneficiaryType, - required super.sideEffectDataRepository, - required super.addressRepository, - required super.referralDataRepository, - }) { - on(_handleSearchByProximity); - } - - FutureOr _handleSearchByProximity( - SearchHouseholdsByProximityEvent event, - SearchHouseholdsEmitter emit, - ) async { - List householdList = []; - List individualsList = []; - List householdMembersList = []; - List projectBeneficiariesList = []; - List taskList = []; - List sideEffectsList = []; - List referralsList = []; - emit(state.copyWith(loading: true)); - // Fetch individual results based on proximity and other criteria. - householdList = - await addressRepository.searchHouseHoldbyAddress(AddressSearchModel( - latitude: event.latitude, - longitude: event.longititude, - maxRadius: event.maxRadius, - offset: event.offset, - limit: event.limit, - )); - // Extract individual IDs from proximity-based individual results. - final householdClientReferenceIds = - householdList.map((e) => e.clientReferenceId).toList(); - householdMembersList = await fetchHouseholdMembersBulk( - null, - householdClientReferenceIds, - ); - final List individualClientReferenceIds = householdMembersList - .map((e) => e.individualClientReferenceId.toString()) - .toList(); - individualsList = await individual.search( - IndividualSearchModel(clientReferenceId: individualClientReferenceIds), - ); - projectBeneficiariesList = await fetchProjectBeneficiary( - beneficiaryType != BeneficiaryType.individual - ? householdClientReferenceIds - : individualClientReferenceIds, - ); - if (projectBeneficiariesList.isNotEmpty) { - // Search for tasks and side effects based on project beneficiaries. - taskList = await fetchTaskbyProjectBeneficiary(projectBeneficiariesList); - sideEffectsList = - await sideEffectDataRepository.search(SideEffectSearchModel( - taskClientReferenceId: - taskList.map((e) => e.clientReferenceId).toList(), - )); - referralsList = await referralDataRepository.search(ReferralSearchModel( - projectBeneficiaryClientReferenceId: - projectBeneficiariesList.map((e) => e.clientReferenceId).toList(), - )); - } - // Initialize a list to store household member wrappers. - final containers = [...state.householdMembers]; - // Group household members by household client reference ID. - final groupedHouseholdsMembers = householdMembersList - .where((hm) => projectBeneficiariesList - .map((p) => p.beneficiaryClientReferenceId) - .toList() - .contains(beneficiaryType == BeneficiaryType.individual - ? hm.individualClientReferenceId - : hm.householdClientReferenceId)) - .groupListsBy((element) => element.householdClientReferenceId); - // Iterate through grouped households and retrieve additional data. - for (final entry in groupedHouseholdsMembers.entries) { - HouseholdModel filteredHousehold; - List filteredIndividuals; - List filteredBeneficiaries; - List filteredTasks; - final householdId = entry.key; - if (householdId == null) continue; - filteredHousehold = - householdList.firstWhere((e) => e.clientReferenceId == householdId); - final List membersIds = - entry.value.map((e) => e.individualClientReferenceId).toList(); - filteredIndividuals = individualsList - .where((element) => membersIds.contains(element.clientReferenceId)) - .toList(); - filteredBeneficiaries = projectBeneficiariesList - .where((element) => beneficiaryType == BeneficiaryType.individual - ? membersIds.contains(element.beneficiaryClientReferenceId) - : householdId == element.beneficiaryClientReferenceId) - .toList(); - filteredTasks = taskList - .where((element) => filteredBeneficiaries - .where((e) => - e.clientReferenceId == - element.projectBeneficiaryClientReferenceId) - .isNotEmpty) - .toList(); - - final beneficiaryClientReferenceIds = filteredBeneficiaries - .map((e) => e.beneficiaryClientReferenceId) - .toList(); - - final List beneficiaryIndividuals = filteredIndividuals - .where((element) => - beneficiaryClientReferenceIds.contains(element.clientReferenceId)) - .toList(); - // Find the head of household from the individuals. - final head = (beneficiaryType == BeneficiaryType.individual - ? beneficiaryIndividuals - : filteredIndividuals) - .firstWhereOrNull( - (element) => - element.clientReferenceId == - entry.value - .firstWhereOrNull( - (element) => element.isHeadOfHousehold, - ) - ?.individualClientReferenceId, - ); - if (head == null || filteredBeneficiaries.isEmpty) continue; - // Create a container for household members and associated data. - if (filteredBeneficiaries.isNotEmpty) { - containers.add( - HouseholdMemberWrapper( - household: filteredHousehold, - headOfHousehold: head, - members: beneficiaryType == BeneficiaryType.individual - ? beneficiaryIndividuals - : filteredIndividuals, - projectBeneficiaries: filteredBeneficiaries, - tasks: filteredTasks.isEmpty ? null : filteredTasks, - sideEffects: sideEffectsList.isEmpty ? null : sideEffectsList, - //TODO Need to added the side effects - referrals: referralsList.isEmpty ? null : referralsList, - //TODO Need to addevid the referrals - ), - ); - } - } - // Update the state with the results and mark the search as completed. - emit(state.copyWith( - householdMembers: containers, - loading: false, - offset: event.offset + event.limit, - limit: event.limit, - )); - } -} diff --git a/packages/registration_delivery/lib/blocs/search_households/search_bloc_common_wrapper.dart b/packages/registration_delivery/lib/blocs/search_households/search_bloc_common_wrapper.dart index 2c814d6e1..b612a83f4 100644 --- a/packages/registration_delivery/lib/blocs/search_households/search_bloc_common_wrapper.dart +++ b/packages/registration_delivery/lib/blocs/search_households/search_bloc_common_wrapper.dart @@ -2,37 +2,36 @@ import 'dart:async'; import 'package:async/async.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/blocs/search_households/individual_global_search.dart'; +import 'household_global_seach.dart'; import 'tag_by_search.dart'; -import 'proximity_search.dart'; import 'search_households.dart'; -import 'search_by_head.dart'; class SearchBlocWrapper implements StateStreamableSource { final SearchHouseholdsBloc searchHouseholdsBloc; - final SearchByHeadBloc searchByHeadBloc; - final ProximitySearchBloc proximitySearchBloc; final TagSearchBloc tagSearchBloc; + final IndividualGlobalSearchBloc individualGlobalSearchBloc; + final HouseHoldGlobalSearchBloc houseHoldGlobalSearchBloc; - SearchBlocWrapper({ - required this.searchHouseholdsBloc, - required this.searchByHeadBloc, - required this.proximitySearchBloc, - required this.tagSearchBloc, - }); + SearchBlocWrapper( + {required this.searchHouseholdsBloc, + required this.tagSearchBloc, + required this.individualGlobalSearchBloc, + required this.houseHoldGlobalSearchBloc}); Stream get stateChanges => StreamGroup.merge([ searchHouseholdsBloc.stream, - searchByHeadBloc.stream, - proximitySearchBloc.stream, + individualGlobalSearchBloc.stream, tagSearchBloc.stream, + houseHoldGlobalSearchBloc.stream, ]); void dispatch(SearchHouseholdsEvent event) { - if (event is SearchHouseholdsByProximityEvent) { - proximitySearchBloc.add(event); - } else if (event is SearchHouseholdsByHouseholdsEvent) { - searchByHeadBloc.add(event); + if (event is IndividualGlobalSearchEvent) { + individualGlobalSearchBloc.add(event); + } else if (event is HouseHoldGlobalSearchEvent) { + houseHoldGlobalSearchBloc.add(event); } else if (event is SearchHouseholdsByTagEvent) { tagSearchBloc.add(event); } else { @@ -41,10 +40,10 @@ class SearchBlocWrapper implements StateStreamableSource { } void clearEvent() { - proximitySearchBloc.add(const SearchHouseholdsEvent.clear()); - searchByHeadBloc.add(const SearchHouseholdsEvent.clear()); + individualGlobalSearchBloc.add(const SearchHouseholdsEvent.clear()); tagSearchBloc.add(const SearchHouseholdsEvent.clear()); searchHouseholdsBloc.add(const SearchHouseholdsEvent.clear()); + houseHoldGlobalSearchBloc.add(const SearchHouseholdsEvent.clear()); } @override @@ -56,15 +55,15 @@ class SearchBlocWrapper implements StateStreamableSource { @override FutureOr close() { searchHouseholdsBloc.close(); - searchByHeadBloc.close(); - proximitySearchBloc.close(); + individualGlobalSearchBloc.close(); + houseHoldGlobalSearchBloc.close(); tagSearchBloc.close(); } @override bool get isClosed => searchHouseholdsBloc.isClosed && - searchByHeadBloc.isClosed && - proximitySearchBloc.isClosed && + individualGlobalSearchBloc.isClosed && + houseHoldGlobalSearchBloc.isClosed && tagSearchBloc.isClosed; } diff --git a/packages/registration_delivery/lib/blocs/search_households/search_by_head.dart b/packages/registration_delivery/lib/blocs/search_households/search_by_head.dart deleted file mode 100644 index e055edfdb..000000000 --- a/packages/registration_delivery/lib/blocs/search_households/search_by_head.dart +++ /dev/null @@ -1,247 +0,0 @@ -import 'dart:async'; - -import 'package:collection/collection.dart'; -import 'package:digit_data_model/data_model.dart'; - -import '../../models/entities/household.dart'; -import '../../models/entities/household_member.dart'; -import '../../models/entities/project_beneficiary.dart'; -import '../../models/entities/referral.dart'; -import '../../models/entities/side_effect.dart'; -import '../../models/entities/task.dart'; -import 'search_households.dart'; - -class SearchByHeadBloc extends SearchHouseholdsBloc { - SearchByHeadBloc({ - required super.userUid, - required super.projectId, - required super.individual, - required super.householdMember, - required super.household, - required super.projectBeneficiary, - required super.taskDataRepository, - required super.beneficiaryType, - required super.sideEffectDataRepository, - required super.addressRepository, - required super.referralDataRepository, - }) { - on( - _handleSearchByHouseholdHead, - transformer: debounce( - const Duration(milliseconds: 100), - ), - ); - } - - FutureOr _handleSearchByHouseholdHead( - SearchHouseholdsSearchByHouseholdHeadEvent event, - SearchHouseholdsEmitter emit, - ) async { - // Check if the search text is empty; if so, clear the results and return. - if (event.searchText.trim().isEmpty) { - super.emit(state.copyWith( - householdMembers: [], - searchQuery: null, - loading: false, - )); - - return; - } - - // Update the state to indicate that the search is in progress. - super.emit(state.copyWith( - loading: true, - searchQuery: event.searchText, - )); - - // Perform a series of asynchronous data retrieval operations based on the search criteria. - - // Fetch household results based on proximity and other criteria. - - List individuals = []; - List proximityBasedIndividualResults = []; - List sideEffects = []; - final containers = []; - List referrals = []; - List tasks = []; - - if (event.isProximityEnabled) { - // Fetch individual results based on proximity and other criteria. - proximityBasedIndividualResults = await addressRepository - .searchHouseHoldByIndividual(AddressSearchModel( - latitude: event.latitude, - longitude: event.longitude, - maxRadius: event.maxRadius, - offset: event.offset, - limit: event.limit, - )); - } - // Extract individual IDs from proximity-based individual results. - final List individualIds = proximityBasedIndividualResults - .map((e) => e.clientReferenceId) - .toList(); - - individuals = await individual.search( - event.isProximityEnabled - ? IndividualSearchModel( - clientReferenceId: individualIds, - name: NameSearchModel( - givenName: event.searchText.trim(), - offset: event.offset, - limit: event.limit, - ), - ) - : IndividualSearchModel( - name: NameSearchModel( - givenName: event.searchText.trim(), - offset: event.offset, - limit: event.limit, - ), - ), - ); - - final individualClientReferenceIds = - individuals.map((e) => e.clientReferenceId).toList(); - // Search for individual results using the extracted IDs and search text. - final List householdMembers = - await fetchHouseholdMembersBulk( - individualClientReferenceIds, - null, - ); - - final househHoldIds = - householdMembers.map((e) => e.householdClientReferenceId!).toList(); - final List allhouseholdMembers = - await fetchHouseholdMembersBulk( - null, - househHoldIds, - ); - - final List individualMembers = - await individual.search(IndividualSearchModel( - clientReferenceId: allhouseholdMembers - .map((e) => e.individualClientReferenceId.toString()) - .toList(), - )); - final List houseHolds = await household.search( - HouseholdSearchModel( - clientReferenceId: househHoldIds, - ), - ); - - final projectBeneficiaries = await fetchProjectBeneficiary( - beneficiaryType != BeneficiaryType.individual - ? househHoldIds - : allhouseholdMembers - .map((e) => e.individualClientReferenceId.toString()) - .toList(), - ); - - // Search for individual results based on the search text only. - - if (projectBeneficiaries.isNotEmpty) { - // Search for tasks and side effects based on project beneficiaries. - tasks = await fetchTaskbyProjectBeneficiary(projectBeneficiaries); - - sideEffects = await sideEffectDataRepository.search(SideEffectSearchModel( - taskClientReferenceId: tasks.map((e) => e.clientReferenceId).toList(), - )); - - referrals = await referralDataRepository.search(ReferralSearchModel( - projectBeneficiaryClientReferenceId: - projectBeneficiaries.map((e) => e.clientReferenceId).toList(), - )); - } - - // Initialize a list to store household members. - final groupedHouseholds = allhouseholdMembers - .where((hm) => projectBeneficiaries - .map((p) => p.beneficiaryClientReferenceId) - .toList() - .contains(beneficiaryType == BeneficiaryType.individual - ? hm.individualClientReferenceId - : hm.householdClientReferenceId)) - .groupListsBy((element) => element.householdClientReferenceId); - - // Iterate through grouped households and retrieve additional data. - for (final entry in groupedHouseholds.entries) { - final householdId = entry.key; - - if (householdId == null) continue; - // Retrieve the first household result. - final householdresult = - houseHolds.firstWhere((e) => e.clientReferenceId == householdId); - // Search for individuals based on proximity, beneficiary type, and search text. - final List membersIds = - entry.value.map((e) => e.individualClientReferenceId).toList(); - final List individualMembersList = individualMembers - .where((element) => membersIds.contains(element.clientReferenceId)) - .toList(); - final List beneficiaries = projectBeneficiaries - .where((element) => beneficiaryType == BeneficiaryType.individual - ? individualClientReferenceIds - .contains(element.beneficiaryClientReferenceId) - : (househHoldIds).contains(element.beneficiaryClientReferenceId)) - .toList(); - final beneficiaryClientReferenceIds = projectBeneficiaries - .map((e) => e.beneficiaryClientReferenceId) - .toList(); - final List beneficiaryIndividuals = individualMembersList - .where((element) => - beneficiaryClientReferenceIds.contains(element.clientReferenceId)) - .toList(); - // Find the head of household from the individuals. - final head = ((beneficiaryType == BeneficiaryType.individual - ? beneficiaryIndividuals - : individualMembersList)) - .firstWhereOrNull( - (element) => - element.clientReferenceId == - entry.value - .firstWhereOrNull( - (element) => element.isHeadOfHousehold, - ) - ?.individualClientReferenceId, - ); - individualMembersList.firstWhereOrNull( - (element) => - element.clientReferenceId == - entry.value - .firstWhereOrNull( - (element) => element.isHeadOfHousehold, - ) - ?.individualClientReferenceId, - ); - - if (head == null || beneficiaries.isEmpty) continue; - - // Search for project beneficiaries based on client reference ID and project. - - if (beneficiaries.isNotEmpty) { - // Create a container for household members and associated data. - containers.add( - HouseholdMemberWrapper( - household: householdresult, - headOfHousehold: head, - members: beneficiaryType == BeneficiaryType.individual - ? beneficiaryIndividuals - : individualMembersList, - projectBeneficiaries: beneficiaries, - tasks: tasks.isEmpty ? null : tasks, - sideEffects: sideEffects.isEmpty ? null : sideEffects, - referrals: referrals.isEmpty ? null : referrals, - ), - ); - } - - // Update the state with the results and mark the search as completed. - } - super.emit(state.copyWith( - searchQuery: event.searchText, - householdMembers: [...containers], - loading: false, - offset: event.offset + event.limit, - limit: event.limit, - )); - } -} diff --git a/packages/registration_delivery/lib/blocs/search_households/search_households.dart b/packages/registration_delivery/lib/blocs/search_households/search_households.dart index 983e552b4..ed259aa84 100644 --- a/packages/registration_delivery/lib/blocs/search_households/search_households.dart +++ b/packages/registration_delivery/lib/blocs/search_households/search_households.dart @@ -8,6 +8,8 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:stream_transform/stream_transform.dart'; +import '../../data/repositories/local/household_global_search.dart'; +import '../../data/repositories/local/individual_global_search.dart'; import '../../data/repositories/local/registration_delivery_address.dart'; import '../../models/entities/household.dart'; import '../../models/entities/household_member.dart'; @@ -15,6 +17,7 @@ import '../../models/entities/project_beneficiary.dart'; import '../../models/entities/referral.dart'; import '../../models/entities/side_effect.dart'; import '../../models/entities/task.dart'; +import '../../utils/global_search_parameters.dart'; import '../../utils/typedefs.dart'; part 'search_households.freezed.dart'; @@ -38,20 +41,24 @@ class SearchHouseholdsBloc final TaskDataRepository taskDataRepository; final SideEffectDataRepository sideEffectDataRepository; final ReferralDataRepository referralDataRepository; - - SearchHouseholdsBloc({ - required this.userUid, - required this.projectId, - required this.individual, - required this.householdMember, - required this.household, - required this.projectBeneficiary, - required this.taskDataRepository, - required this.beneficiaryType, - required this.sideEffectDataRepository, - required this.addressRepository, - required this.referralDataRepository, - }) : super(const SearchHouseholdsState()) { + final IndividualGlobalSearchRepository individualGlobalSearchRepository; + final HouseHoldGlobalSearchRepository houseHoldGlobalSearchRepository; + + SearchHouseholdsBloc( + {required this.userUid, + required this.projectId, + required this.individual, + required this.householdMember, + required this.household, + required this.projectBeneficiary, + required this.taskDataRepository, + required this.beneficiaryType, + required this.sideEffectDataRepository, + required this.addressRepository, + required this.referralDataRepository, + required this.individualGlobalSearchRepository, + required this.houseHoldGlobalSearchRepository}) + : super(const SearchHouseholdsState()) { on(_handleClear); on(_handleSearchByHousehold); } @@ -257,6 +264,14 @@ class SearchHouseholdsEvent with _$SearchHouseholdsEvent { }) = SearchHouseholdsByTagEvent; const factory SearchHouseholdsEvent.clear() = SearchHouseholdsClearEvent; + + const factory SearchHouseholdsEvent.individualGlobalSearch({ + required GlobalSearchParameters globalSearchParams, + }) = IndividualGlobalSearchEvent; + + const factory SearchHouseholdsEvent.houseHoldGlobalSearch({ + required GlobalSearchParameters globalSearchParams, + }) = HouseHoldGlobalSearchEvent; } @freezed @@ -270,6 +285,7 @@ class SearchHouseholdsState with _$SearchHouseholdsState { String? searchQuery, String? tag, @Default([]) List householdMembers, + @Default(0) int totalResults, }) = _SearchHouseholdsState; bool get resultsNotFound { @@ -284,10 +300,10 @@ class SearchHouseholdsState with _$SearchHouseholdsState { @freezed class HouseholdMemberWrapper with _$HouseholdMemberWrapper { const factory HouseholdMemberWrapper({ - required HouseholdModel household, - required IndividualModel headOfHousehold, - required List members, - required List projectBeneficiaries, + HouseholdModel? household, + IndividualModel? headOfHousehold, + List? members, + List? projectBeneficiaries, double? distance, List? tasks, List? sideEffects, diff --git a/packages/registration_delivery/lib/blocs/search_households/search_households.freezed.dart b/packages/registration_delivery/lib/blocs/search_households/search_households.freezed.dart index 141b41c95..a6503ca8b 100644 --- a/packages/registration_delivery/lib/blocs/search_households/search_households.freezed.dart +++ b/packages/registration_delivery/lib/blocs/search_households/search_households.freezed.dart @@ -43,6 +43,10 @@ mixin _$SearchHouseholdsEvent { searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -72,6 +76,10 @@ mixin _$SearchHouseholdsEvent { searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -101,6 +109,10 @@ mixin _$SearchHouseholdsEvent { searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -116,6 +128,10 @@ mixin _$SearchHouseholdsEvent { searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -129,6 +145,9 @@ mixin _$SearchHouseholdsEvent { searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) => throw _privateConstructorUsedError; @optionalTypeArgs @@ -141,6 +160,8 @@ mixin _$SearchHouseholdsEvent { TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) => throw _privateConstructorUsedError; @@ -233,6 +254,10 @@ class _$SearchHouseholdsInitializedEventImpl searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return initialize(); } @@ -265,6 +290,10 @@ class _$SearchHouseholdsInitializedEventImpl searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return initialize?.call(); } @@ -297,6 +326,10 @@ class _$SearchHouseholdsInitializedEventImpl searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (initialize != null) { @@ -318,6 +351,10 @@ class _$SearchHouseholdsInitializedEventImpl searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return initialize(this); } @@ -334,6 +371,9 @@ class _$SearchHouseholdsInitializedEventImpl searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return initialize?.call(this); } @@ -349,6 +389,8 @@ class _$SearchHouseholdsInitializedEventImpl TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (initialize != null) { @@ -518,6 +560,10 @@ class _$SearchHouseholdsByHouseholdsEventImpl searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return searchByHousehold(projectId, latitude, longitude, maxRadius, isProximityEnabled, householdModel); @@ -551,6 +597,10 @@ class _$SearchHouseholdsByHouseholdsEventImpl searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return searchByHousehold?.call(projectId, latitude, longitude, maxRadius, isProximityEnabled, householdModel); @@ -584,6 +634,10 @@ class _$SearchHouseholdsByHouseholdsEventImpl searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByHousehold != null) { @@ -606,6 +660,10 @@ class _$SearchHouseholdsByHouseholdsEventImpl searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return searchByHousehold(this); } @@ -622,6 +680,9 @@ class _$SearchHouseholdsByHouseholdsEventImpl searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return searchByHousehold?.call(this); } @@ -637,6 +698,8 @@ class _$SearchHouseholdsByHouseholdsEventImpl TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByHousehold != null) { @@ -856,6 +919,10 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return searchByHouseholdHead(searchText, projectId, isProximityEnabled, latitude, longitude, maxRadius, tag, offset, limit); @@ -889,6 +956,10 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return searchByHouseholdHead?.call(searchText, projectId, isProximityEnabled, latitude, longitude, maxRadius, tag, offset, limit); @@ -922,6 +993,10 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByHouseholdHead != null) { @@ -944,6 +1019,10 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return searchByHouseholdHead(this); } @@ -960,6 +1039,9 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return searchByHouseholdHead?.call(this); } @@ -975,6 +1057,8 @@ class _$SearchHouseholdsSearchByHouseholdHeadEventImpl TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByHouseholdHead != null) { @@ -1165,6 +1249,10 @@ class _$SearchHouseholdsByProximityEventImpl searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return searchByProximity( latitude, longititude, projectId, maxRadius, offset, limit); @@ -1198,6 +1286,10 @@ class _$SearchHouseholdsByProximityEventImpl searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return searchByProximity?.call( latitude, longititude, projectId, maxRadius, offset, limit); @@ -1231,6 +1323,10 @@ class _$SearchHouseholdsByProximityEventImpl searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByProximity != null) { @@ -1253,6 +1349,10 @@ class _$SearchHouseholdsByProximityEventImpl searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return searchByProximity(this); } @@ -1269,6 +1369,9 @@ class _$SearchHouseholdsByProximityEventImpl searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return searchByProximity?.call(this); } @@ -1284,6 +1387,8 @@ class _$SearchHouseholdsByProximityEventImpl TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByProximity != null) { @@ -1418,6 +1523,10 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return searchByTag(tag, projectId); } @@ -1450,6 +1559,10 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return searchByTag?.call(tag, projectId); } @@ -1482,6 +1595,10 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByTag != null) { @@ -1503,6 +1620,10 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return searchByTag(this); } @@ -1519,6 +1640,9 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return searchByTag?.call(this); } @@ -1534,6 +1658,8 @@ class _$SearchHouseholdsByTagEventImpl implements SearchHouseholdsByTagEvent { TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (searchByTag != null) { @@ -1622,6 +1748,10 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { searchByProximity, required TResult Function(String tag, String projectId) searchByTag, required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, }) { return clear(); } @@ -1654,6 +1784,10 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { searchByProximity, TResult? Function(String tag, String projectId)? searchByTag, TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, }) { return clear?.call(); } @@ -1686,6 +1820,10 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { searchByProximity, TResult Function(String tag, String projectId)? searchByTag, TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, required TResult orElse(), }) { if (clear != null) { @@ -1707,6 +1845,10 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { searchByProximity, required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, }) { return clear(this); } @@ -1723,6 +1865,9 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { searchByProximity, TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, }) { return clear?.call(this); } @@ -1738,6 +1883,8 @@ class _$SearchHouseholdsClearEventImpl implements SearchHouseholdsClearEvent { TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, required TResult orElse(), }) { if (clear != null) { @@ -1751,6 +1898,508 @@ abstract class SearchHouseholdsClearEvent implements SearchHouseholdsEvent { const factory SearchHouseholdsClearEvent() = _$SearchHouseholdsClearEventImpl; } +/// @nodoc +abstract class _$$IndividualGlobalSearchEventImplCopyWith<$Res> { + factory _$$IndividualGlobalSearchEventImplCopyWith( + _$IndividualGlobalSearchEventImpl value, + $Res Function(_$IndividualGlobalSearchEventImpl) then) = + __$$IndividualGlobalSearchEventImplCopyWithImpl<$Res>; + @useResult + $Res call({GlobalSearchParameters globalSearchParams}); +} + +/// @nodoc +class __$$IndividualGlobalSearchEventImplCopyWithImpl<$Res> + extends _$SearchHouseholdsEventCopyWithImpl<$Res, + _$IndividualGlobalSearchEventImpl> + implements _$$IndividualGlobalSearchEventImplCopyWith<$Res> { + __$$IndividualGlobalSearchEventImplCopyWithImpl( + _$IndividualGlobalSearchEventImpl _value, + $Res Function(_$IndividualGlobalSearchEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? globalSearchParams = null, + }) { + return _then(_$IndividualGlobalSearchEventImpl( + globalSearchParams: null == globalSearchParams + ? _value.globalSearchParams + : globalSearchParams // ignore: cast_nullable_to_non_nullable + as GlobalSearchParameters, + )); + } +} + +/// @nodoc + +class _$IndividualGlobalSearchEventImpl implements IndividualGlobalSearchEvent { + const _$IndividualGlobalSearchEventImpl({required this.globalSearchParams}); + + @override + final GlobalSearchParameters globalSearchParams; + + @override + String toString() { + return 'SearchHouseholdsEvent.individualGlobalSearch(globalSearchParams: $globalSearchParams)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$IndividualGlobalSearchEventImpl && + (identical(other.globalSearchParams, globalSearchParams) || + other.globalSearchParams == globalSearchParams)); + } + + @override + int get hashCode => Object.hash(runtimeType, globalSearchParams); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$IndividualGlobalSearchEventImplCopyWith<_$IndividualGlobalSearchEventImpl> + get copyWith => __$$IndividualGlobalSearchEventImplCopyWithImpl< + _$IndividualGlobalSearchEventImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initialize, + required TResult Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel) + searchByHousehold, + required TResult Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit) + searchByHouseholdHead, + required TResult Function(double latitude, double longititude, + String projectId, double maxRadius, int offset, int limit) + searchByProximity, + required TResult Function(String tag, String projectId) searchByTag, + required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, + }) { + return individualGlobalSearch(globalSearchParams); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initialize, + TResult? Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel)? + searchByHousehold, + TResult? Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit)? + searchByHouseholdHead, + TResult? Function(double latitude, double longititude, String projectId, + double maxRadius, int offset, int limit)? + searchByProximity, + TResult? Function(String tag, String projectId)? searchByTag, + TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, + }) { + return individualGlobalSearch?.call(globalSearchParams); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initialize, + TResult Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel)? + searchByHousehold, + TResult Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit)? + searchByHouseholdHead, + TResult Function(double latitude, double longititude, String projectId, + double maxRadius, int offset, int limit)? + searchByProximity, + TResult Function(String tag, String projectId)? searchByTag, + TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, + required TResult orElse(), + }) { + if (individualGlobalSearch != null) { + return individualGlobalSearch(globalSearchParams); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(SearchHouseholdsInitializedEvent value) + initialize, + required TResult Function(SearchHouseholdsByHouseholdsEvent value) + searchByHousehold, + required TResult Function(SearchHouseholdsSearchByHouseholdHeadEvent value) + searchByHouseholdHead, + required TResult Function(SearchHouseholdsByProximityEvent value) + searchByProximity, + required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, + required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, + }) { + return individualGlobalSearch(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(SearchHouseholdsInitializedEvent value)? initialize, + TResult? Function(SearchHouseholdsByHouseholdsEvent value)? + searchByHousehold, + TResult? Function(SearchHouseholdsSearchByHouseholdHeadEvent value)? + searchByHouseholdHead, + TResult? Function(SearchHouseholdsByProximityEvent value)? + searchByProximity, + TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, + TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, + }) { + return individualGlobalSearch?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(SearchHouseholdsInitializedEvent value)? initialize, + TResult Function(SearchHouseholdsByHouseholdsEvent value)? + searchByHousehold, + TResult Function(SearchHouseholdsSearchByHouseholdHeadEvent value)? + searchByHouseholdHead, + TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, + TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, + TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, + required TResult orElse(), + }) { + if (individualGlobalSearch != null) { + return individualGlobalSearch(this); + } + return orElse(); + } +} + +abstract class IndividualGlobalSearchEvent implements SearchHouseholdsEvent { + const factory IndividualGlobalSearchEvent( + {required final GlobalSearchParameters globalSearchParams}) = + _$IndividualGlobalSearchEventImpl; + + GlobalSearchParameters get globalSearchParams; + @JsonKey(ignore: true) + _$$IndividualGlobalSearchEventImplCopyWith<_$IndividualGlobalSearchEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class _$$HouseHoldGlobalSearchEventImplCopyWith<$Res> { + factory _$$HouseHoldGlobalSearchEventImplCopyWith( + _$HouseHoldGlobalSearchEventImpl value, + $Res Function(_$HouseHoldGlobalSearchEventImpl) then) = + __$$HouseHoldGlobalSearchEventImplCopyWithImpl<$Res>; + @useResult + $Res call({GlobalSearchParameters globalSearchParams}); +} + +/// @nodoc +class __$$HouseHoldGlobalSearchEventImplCopyWithImpl<$Res> + extends _$SearchHouseholdsEventCopyWithImpl<$Res, + _$HouseHoldGlobalSearchEventImpl> + implements _$$HouseHoldGlobalSearchEventImplCopyWith<$Res> { + __$$HouseHoldGlobalSearchEventImplCopyWithImpl( + _$HouseHoldGlobalSearchEventImpl _value, + $Res Function(_$HouseHoldGlobalSearchEventImpl) _then) + : super(_value, _then); + + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? globalSearchParams = null, + }) { + return _then(_$HouseHoldGlobalSearchEventImpl( + globalSearchParams: null == globalSearchParams + ? _value.globalSearchParams + : globalSearchParams // ignore: cast_nullable_to_non_nullable + as GlobalSearchParameters, + )); + } +} + +/// @nodoc + +class _$HouseHoldGlobalSearchEventImpl implements HouseHoldGlobalSearchEvent { + const _$HouseHoldGlobalSearchEventImpl({required this.globalSearchParams}); + + @override + final GlobalSearchParameters globalSearchParams; + + @override + String toString() { + return 'SearchHouseholdsEvent.houseHoldGlobalSearch(globalSearchParams: $globalSearchParams)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$HouseHoldGlobalSearchEventImpl && + (identical(other.globalSearchParams, globalSearchParams) || + other.globalSearchParams == globalSearchParams)); + } + + @override + int get hashCode => Object.hash(runtimeType, globalSearchParams); + + @JsonKey(ignore: true) + @override + @pragma('vm:prefer-inline') + _$$HouseHoldGlobalSearchEventImplCopyWith<_$HouseHoldGlobalSearchEventImpl> + get copyWith => __$$HouseHoldGlobalSearchEventImplCopyWithImpl< + _$HouseHoldGlobalSearchEventImpl>(this, _$identity); + + @override + @optionalTypeArgs + TResult when({ + required TResult Function() initialize, + required TResult Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel) + searchByHousehold, + required TResult Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit) + searchByHouseholdHead, + required TResult Function(double latitude, double longititude, + String projectId, double maxRadius, int offset, int limit) + searchByProximity, + required TResult Function(String tag, String projectId) searchByTag, + required TResult Function() clear, + required TResult Function(GlobalSearchParameters globalSearchParams) + individualGlobalSearch, + required TResult Function(GlobalSearchParameters globalSearchParams) + houseHoldGlobalSearch, + }) { + return houseHoldGlobalSearch(globalSearchParams); + } + + @override + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? initialize, + TResult? Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel)? + searchByHousehold, + TResult? Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit)? + searchByHouseholdHead, + TResult? Function(double latitude, double longititude, String projectId, + double maxRadius, int offset, int limit)? + searchByProximity, + TResult? Function(String tag, String projectId)? searchByTag, + TResult? Function()? clear, + TResult? Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult? Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, + }) { + return houseHoldGlobalSearch?.call(globalSearchParams); + } + + @override + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? initialize, + TResult Function( + String projectId, + double? latitude, + double? longitude, + double? maxRadius, + bool isProximityEnabled, + HouseholdModel householdModel)? + searchByHousehold, + TResult Function( + String searchText, + String projectId, + bool isProximityEnabled, + double? latitude, + double? longitude, + double? maxRadius, + String? tag, + int offset, + int limit)? + searchByHouseholdHead, + TResult Function(double latitude, double longititude, String projectId, + double maxRadius, int offset, int limit)? + searchByProximity, + TResult Function(String tag, String projectId)? searchByTag, + TResult Function()? clear, + TResult Function(GlobalSearchParameters globalSearchParams)? + individualGlobalSearch, + TResult Function(GlobalSearchParameters globalSearchParams)? + houseHoldGlobalSearch, + required TResult orElse(), + }) { + if (houseHoldGlobalSearch != null) { + return houseHoldGlobalSearch(globalSearchParams); + } + return orElse(); + } + + @override + @optionalTypeArgs + TResult map({ + required TResult Function(SearchHouseholdsInitializedEvent value) + initialize, + required TResult Function(SearchHouseholdsByHouseholdsEvent value) + searchByHousehold, + required TResult Function(SearchHouseholdsSearchByHouseholdHeadEvent value) + searchByHouseholdHead, + required TResult Function(SearchHouseholdsByProximityEvent value) + searchByProximity, + required TResult Function(SearchHouseholdsByTagEvent value) searchByTag, + required TResult Function(SearchHouseholdsClearEvent value) clear, + required TResult Function(IndividualGlobalSearchEvent value) + individualGlobalSearch, + required TResult Function(HouseHoldGlobalSearchEvent value) + houseHoldGlobalSearch, + }) { + return houseHoldGlobalSearch(this); + } + + @override + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(SearchHouseholdsInitializedEvent value)? initialize, + TResult? Function(SearchHouseholdsByHouseholdsEvent value)? + searchByHousehold, + TResult? Function(SearchHouseholdsSearchByHouseholdHeadEvent value)? + searchByHouseholdHead, + TResult? Function(SearchHouseholdsByProximityEvent value)? + searchByProximity, + TResult? Function(SearchHouseholdsByTagEvent value)? searchByTag, + TResult? Function(SearchHouseholdsClearEvent value)? clear, + TResult? Function(IndividualGlobalSearchEvent value)? + individualGlobalSearch, + TResult? Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, + }) { + return houseHoldGlobalSearch?.call(this); + } + + @override + @optionalTypeArgs + TResult maybeMap({ + TResult Function(SearchHouseholdsInitializedEvent value)? initialize, + TResult Function(SearchHouseholdsByHouseholdsEvent value)? + searchByHousehold, + TResult Function(SearchHouseholdsSearchByHouseholdHeadEvent value)? + searchByHouseholdHead, + TResult Function(SearchHouseholdsByProximityEvent value)? searchByProximity, + TResult Function(SearchHouseholdsByTagEvent value)? searchByTag, + TResult Function(SearchHouseholdsClearEvent value)? clear, + TResult Function(IndividualGlobalSearchEvent value)? individualGlobalSearch, + TResult Function(HouseHoldGlobalSearchEvent value)? houseHoldGlobalSearch, + required TResult orElse(), + }) { + if (houseHoldGlobalSearch != null) { + return houseHoldGlobalSearch(this); + } + return orElse(); + } +} + +abstract class HouseHoldGlobalSearchEvent implements SearchHouseholdsEvent { + const factory HouseHoldGlobalSearchEvent( + {required final GlobalSearchParameters globalSearchParams}) = + _$HouseHoldGlobalSearchEventImpl; + + GlobalSearchParameters get globalSearchParams; + @JsonKey(ignore: true) + _$$HouseHoldGlobalSearchEventImplCopyWith<_$HouseHoldGlobalSearchEventImpl> + get copyWith => throw _privateConstructorUsedError; +} + /// @nodoc mixin _$SearchHouseholdsState { int get offset => throw _privateConstructorUsedError; @@ -1760,6 +2409,7 @@ mixin _$SearchHouseholdsState { String? get tag => throw _privateConstructorUsedError; List get householdMembers => throw _privateConstructorUsedError; + int get totalResults => throw _privateConstructorUsedError; @JsonKey(ignore: true) $SearchHouseholdsStateCopyWith get copyWith => @@ -1778,7 +2428,8 @@ abstract class $SearchHouseholdsStateCopyWith<$Res> { bool loading, String? searchQuery, String? tag, - List householdMembers}); + List householdMembers, + int totalResults}); } /// @nodoc @@ -1801,6 +2452,7 @@ class _$SearchHouseholdsStateCopyWithImpl<$Res, Object? searchQuery = freezed, Object? tag = freezed, Object? householdMembers = null, + Object? totalResults = null, }) { return _then(_value.copyWith( offset: null == offset @@ -1827,6 +2479,10 @@ class _$SearchHouseholdsStateCopyWithImpl<$Res, ? _value.householdMembers : householdMembers // ignore: cast_nullable_to_non_nullable as List, + totalResults: null == totalResults + ? _value.totalResults + : totalResults // ignore: cast_nullable_to_non_nullable + as int, ) as $Val); } } @@ -1846,7 +2502,8 @@ abstract class _$$SearchHouseholdsStateImplCopyWith<$Res> bool loading, String? searchQuery, String? tag, - List householdMembers}); + List householdMembers, + int totalResults}); } /// @nodoc @@ -1867,6 +2524,7 @@ class __$$SearchHouseholdsStateImplCopyWithImpl<$Res> Object? searchQuery = freezed, Object? tag = freezed, Object? householdMembers = null, + Object? totalResults = null, }) { return _then(_$SearchHouseholdsStateImpl( offset: null == offset @@ -1893,6 +2551,10 @@ class __$$SearchHouseholdsStateImplCopyWithImpl<$Res> ? _value._householdMembers : householdMembers // ignore: cast_nullable_to_non_nullable as List, + totalResults: null == totalResults + ? _value.totalResults + : totalResults // ignore: cast_nullable_to_non_nullable + as int, )); } } @@ -1906,7 +2568,8 @@ class _$SearchHouseholdsStateImpl extends _SearchHouseholdsState { this.loading = false, this.searchQuery, this.tag, - final List householdMembers = const []}) + final List householdMembers = const [], + this.totalResults = 0}) : _householdMembers = householdMembers, super._(); @@ -1933,9 +2596,13 @@ class _$SearchHouseholdsStateImpl extends _SearchHouseholdsState { return EqualUnmodifiableListView(_householdMembers); } + @override + @JsonKey() + final int totalResults; + @override String toString() { - return 'SearchHouseholdsState(offset: $offset, limit: $limit, loading: $loading, searchQuery: $searchQuery, tag: $tag, householdMembers: $householdMembers)'; + return 'SearchHouseholdsState(offset: $offset, limit: $limit, loading: $loading, searchQuery: $searchQuery, tag: $tag, householdMembers: $householdMembers, totalResults: $totalResults)'; } @override @@ -1950,12 +2617,21 @@ class _$SearchHouseholdsStateImpl extends _SearchHouseholdsState { other.searchQuery == searchQuery) && (identical(other.tag, tag) || other.tag == tag) && const DeepCollectionEquality() - .equals(other._householdMembers, _householdMembers)); + .equals(other._householdMembers, _householdMembers) && + (identical(other.totalResults, totalResults) || + other.totalResults == totalResults)); } @override - int get hashCode => Object.hash(runtimeType, offset, limit, loading, - searchQuery, tag, const DeepCollectionEquality().hash(_householdMembers)); + int get hashCode => Object.hash( + runtimeType, + offset, + limit, + loading, + searchQuery, + tag, + const DeepCollectionEquality().hash(_householdMembers), + totalResults); @JsonKey(ignore: true) @override @@ -1967,13 +2643,13 @@ class _$SearchHouseholdsStateImpl extends _SearchHouseholdsState { abstract class _SearchHouseholdsState extends SearchHouseholdsState { const factory _SearchHouseholdsState( - {final int offset, - final int limit, - final bool loading, - final String? searchQuery, - final String? tag, - final List householdMembers}) = - _$SearchHouseholdsStateImpl; + {final int offset, + final int limit, + final bool loading, + final String? searchQuery, + final String? tag, + final List householdMembers, + final int totalResults}) = _$SearchHouseholdsStateImpl; const _SearchHouseholdsState._() : super._(); @override @@ -1989,6 +2665,8 @@ abstract class _SearchHouseholdsState extends SearchHouseholdsState { @override List get householdMembers; @override + int get totalResults; + @override @JsonKey(ignore: true) _$$SearchHouseholdsStateImplCopyWith<_$SearchHouseholdsStateImpl> get copyWith => throw _privateConstructorUsedError; @@ -1996,10 +2674,10 @@ abstract class _SearchHouseholdsState extends SearchHouseholdsState { /// @nodoc mixin _$HouseholdMemberWrapper { - HouseholdModel get household => throw _privateConstructorUsedError; - IndividualModel get headOfHousehold => throw _privateConstructorUsedError; - List get members => throw _privateConstructorUsedError; - List get projectBeneficiaries => + HouseholdModel? get household => throw _privateConstructorUsedError; + IndividualModel? get headOfHousehold => throw _privateConstructorUsedError; + List? get members => throw _privateConstructorUsedError; + List? get projectBeneficiaries => throw _privateConstructorUsedError; double? get distance => throw _privateConstructorUsedError; List? get tasks => throw _privateConstructorUsedError; @@ -2018,10 +2696,10 @@ abstract class $HouseholdMemberWrapperCopyWith<$Res> { _$HouseholdMemberWrapperCopyWithImpl<$Res, HouseholdMemberWrapper>; @useResult $Res call( - {HouseholdModel household, - IndividualModel headOfHousehold, - List members, - List projectBeneficiaries, + {HouseholdModel? household, + IndividualModel? headOfHousehold, + List? members, + List? projectBeneficiaries, double? distance, List? tasks, List? sideEffects, @@ -2042,32 +2720,32 @@ class _$HouseholdMemberWrapperCopyWithImpl<$Res, @pragma('vm:prefer-inline') @override $Res call({ - Object? household = null, - Object? headOfHousehold = null, - Object? members = null, - Object? projectBeneficiaries = null, + Object? household = freezed, + Object? headOfHousehold = freezed, + Object? members = freezed, + Object? projectBeneficiaries = freezed, Object? distance = freezed, Object? tasks = freezed, Object? sideEffects = freezed, Object? referrals = freezed, }) { return _then(_value.copyWith( - household: null == household + household: freezed == household ? _value.household : household // ignore: cast_nullable_to_non_nullable - as HouseholdModel, - headOfHousehold: null == headOfHousehold + as HouseholdModel?, + headOfHousehold: freezed == headOfHousehold ? _value.headOfHousehold : headOfHousehold // ignore: cast_nullable_to_non_nullable - as IndividualModel, - members: null == members + as IndividualModel?, + members: freezed == members ? _value.members : members // ignore: cast_nullable_to_non_nullable - as List, - projectBeneficiaries: null == projectBeneficiaries + as List?, + projectBeneficiaries: freezed == projectBeneficiaries ? _value.projectBeneficiaries : projectBeneficiaries // ignore: cast_nullable_to_non_nullable - as List, + as List?, distance: freezed == distance ? _value.distance : distance // ignore: cast_nullable_to_non_nullable @@ -2098,10 +2776,10 @@ abstract class _$$HouseholdMemberWrapperImplCopyWith<$Res> @override @useResult $Res call( - {HouseholdModel household, - IndividualModel headOfHousehold, - List members, - List projectBeneficiaries, + {HouseholdModel? household, + IndividualModel? headOfHousehold, + List? members, + List? projectBeneficiaries, double? distance, List? tasks, List? sideEffects, @@ -2121,32 +2799,32 @@ class __$$HouseholdMemberWrapperImplCopyWithImpl<$Res> @pragma('vm:prefer-inline') @override $Res call({ - Object? household = null, - Object? headOfHousehold = null, - Object? members = null, - Object? projectBeneficiaries = null, + Object? household = freezed, + Object? headOfHousehold = freezed, + Object? members = freezed, + Object? projectBeneficiaries = freezed, Object? distance = freezed, Object? tasks = freezed, Object? sideEffects = freezed, Object? referrals = freezed, }) { return _then(_$HouseholdMemberWrapperImpl( - household: null == household + household: freezed == household ? _value.household : household // ignore: cast_nullable_to_non_nullable - as HouseholdModel, - headOfHousehold: null == headOfHousehold + as HouseholdModel?, + headOfHousehold: freezed == headOfHousehold ? _value.headOfHousehold : headOfHousehold // ignore: cast_nullable_to_non_nullable - as IndividualModel, - members: null == members + as IndividualModel?, + members: freezed == members ? _value._members : members // ignore: cast_nullable_to_non_nullable - as List, - projectBeneficiaries: null == projectBeneficiaries + as List?, + projectBeneficiaries: freezed == projectBeneficiaries ? _value._projectBeneficiaries : projectBeneficiaries // ignore: cast_nullable_to_non_nullable - as List, + as List?, distance: freezed == distance ? _value.distance : distance // ignore: cast_nullable_to_non_nullable @@ -2171,10 +2849,10 @@ class __$$HouseholdMemberWrapperImplCopyWithImpl<$Res> class _$HouseholdMemberWrapperImpl implements _HouseholdMemberWrapper { const _$HouseholdMemberWrapperImpl( - {required this.household, - required this.headOfHousehold, - required final List members, - required final List projectBeneficiaries, + {this.household, + this.headOfHousehold, + final List? members, + final List? projectBeneficiaries, this.distance, final List? tasks, final List? sideEffects, @@ -2186,24 +2864,28 @@ class _$HouseholdMemberWrapperImpl implements _HouseholdMemberWrapper { _referrals = referrals; @override - final HouseholdModel household; + final HouseholdModel? household; @override - final IndividualModel headOfHousehold; - final List _members; + final IndividualModel? headOfHousehold; + final List? _members; @override - List get members { + List? get members { + final value = _members; + if (value == null) return null; if (_members is EqualUnmodifiableListView) return _members; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_members); + return EqualUnmodifiableListView(value); } - final List _projectBeneficiaries; + final List? _projectBeneficiaries; @override - List get projectBeneficiaries { + List? get projectBeneficiaries { + final value = _projectBeneficiaries; + if (value == null) return null; if (_projectBeneficiaries is EqualUnmodifiableListView) return _projectBeneficiaries; // ignore: implicit_dynamic_type - return EqualUnmodifiableListView(_projectBeneficiaries); + return EqualUnmodifiableListView(value); } @override @@ -2286,23 +2968,23 @@ class _$HouseholdMemberWrapperImpl implements _HouseholdMemberWrapper { abstract class _HouseholdMemberWrapper implements HouseholdMemberWrapper { const factory _HouseholdMemberWrapper( - {required final HouseholdModel household, - required final IndividualModel headOfHousehold, - required final List members, - required final List projectBeneficiaries, + {final HouseholdModel? household, + final IndividualModel? headOfHousehold, + final List? members, + final List? projectBeneficiaries, final double? distance, final List? tasks, final List? sideEffects, final List? referrals}) = _$HouseholdMemberWrapperImpl; @override - HouseholdModel get household; + HouseholdModel? get household; @override - IndividualModel get headOfHousehold; + IndividualModel? get headOfHousehold; @override - List get members; + List? get members; @override - List get projectBeneficiaries; + List? get projectBeneficiaries; @override double? get distance; @override diff --git a/packages/registration_delivery/lib/blocs/search_households/tag_by_search.dart b/packages/registration_delivery/lib/blocs/search_households/tag_by_search.dart index bb0bbb1f1..33ef8f30f 100644 --- a/packages/registration_delivery/lib/blocs/search_households/tag_by_search.dart +++ b/packages/registration_delivery/lib/blocs/search_households/tag_by_search.dart @@ -22,6 +22,8 @@ class TagSearchBloc extends SearchHouseholdsBloc { required super.sideEffectDataRepository, required super.addressRepository, required super.referralDataRepository, + required super.individualGlobalSearchRepository, + required super.houseHoldGlobalSearchRepository }) { on(handleSearchByTag); } @@ -38,9 +40,6 @@ class TagSearchBloc extends SearchHouseholdsBloc { ), ); - /* [TODO: Need to handle the Tag search based on Beneficary Type - current implementation is based on the individual based project - ] */ List individuals = []; List households = []; diff --git a/packages/registration_delivery/lib/data/repositories/local/household.dart b/packages/registration_delivery/lib/data/repositories/local/household.dart index f058194d6..31de2a1e8 100644 --- a/packages/registration_delivery/lib/data/repositories/local/household.dart +++ b/packages/registration_delivery/lib/data/repositories/local/household.dart @@ -4,7 +4,6 @@ import 'dart:math' as math; import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:drift/drift.dart'; -import 'package:registration_delivery/utils/utils.dart'; import '../../../models/entities/household.dart'; @@ -76,6 +75,11 @@ class HouseholdLocalRepository memberCount: household.memberCount, rowVersion: household.rowVersion, isDeleted: household.isDeleted, + additionalFields: household.additionalFields != null && + household.additionalFields.toString().isNotEmpty + ? HouseholdAdditionalFieldsMapper.fromJson( + household.additionalFields.toString()) + : null, auditDetails: (household.auditCreatedBy != null && household.auditCreatedTime != null) ? AuditDetails( diff --git a/packages/registration_delivery/lib/data/repositories/local/household_global_search.dart b/packages/registration_delivery/lib/data/repositories/local/household_global_search.dart new file mode 100644 index 000000000..26ffbd225 --- /dev/null +++ b/packages/registration_delivery/lib/data/repositories/local/household_global_search.dart @@ -0,0 +1,514 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:digit_data_model/data_model.dart'; +import 'package:drift/drift.dart'; +import 'package:flutter/material.dart'; +import 'package:registration_delivery/models/entities/task.dart'; + +import '../../../models/entities/household.dart'; +import '../../../models/entities/status.dart'; +import '../../../models/entities/task_resource.dart'; +import '../../../utils/global_search_parameters.dart'; + +class HouseHoldGlobalSearchRepository extends LocalRepository { + HouseHoldGlobalSearchRepository(super.sql, super.opLogManager); + + @override + FutureOr> search(EntitySearchModel query) { + throw UnimplementedError(); + } + + @override + DataModelType get type => throw UnimplementedError(); + + // Function to perform global search for households + houseHoldGlobalSearch(GlobalSearchParameters params) async { + dynamic selectQuery; + late int? count = params.totalCount == 0 ? 0 : params.totalCount; + + // Check if the filter contains status for registered or not registered + if (params.filter!.contains(Status.registered.name) || + params.filter!.contains(Status.notRegistered.name)) { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + var filterSelectQuery = nameSelectQuery; + + // Apply filters if present + if (params.filter != null && params.filter!.isNotEmpty) { + for (var filter in params.filter!) { + filterSelectQuery = + await filterSearch(filterSelectQuery, params, filter, super.sql); + } + } else { + filterSelectQuery = nameSelectQuery; + } + + // Return empty list if no results found + if (filterSelectQuery == null) { + return []; + } else { + // Get total count if offset is zero and filters are applied + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(filterSelectQuery, params, super.sql); + } + + await filterSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await filterSelectQuery.get(); + + return _returnHouseHoldModel(results, count); + } + } else if (params.filter!.isNotEmpty && params.filter != null) { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + var filterSelectQuery = nameSelectQuery; + + // Apply filters if present + if (params.filter != null && params.filter!.isNotEmpty) { + for (var filter in params.filter!) { + filterSelectQuery = + await filterSearch(filterSelectQuery, params, filter, super.sql); + } + } else { + filterSelectQuery = nameSelectQuery; + } + + // Return empty list if no results found + if (filterSelectQuery == null) { + return []; + } else { + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(filterSelectQuery, params, super.sql); + } + await filterSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await filterSelectQuery.get(); + var data = results + .map((e) { + final task = e.readTableOrNull(sql.task); + final resources = e.readTableOrNull(sql.taskResource); + + return TaskModel( + id: task.id, + createdBy: task.createdBy, + clientReferenceId: task.clientReferenceId, + rowVersion: task.rowVersion, + tenantId: task.tenantId, + isDeleted: task.isDeleted, + projectId: task.projectId, + projectBeneficiaryId: task.projectBeneficiaryId, + projectBeneficiaryClientReferenceId: + task.projectBeneficiaryClientReferenceId, + createdDate: task.createdDate, + status: task.status, + resources: resources == null + ? null + : [ + TaskResourceModel( + taskclientReferenceId: + resources.taskclientReferenceId, + clientReferenceId: resources.clientReferenceId, + id: resources.id, + productVariantId: resources.productVariantId, + taskId: resources.taskId, + deliveryComment: resources.deliveryComment, + quantity: resources.quantity, + rowVersion: resources.rowVersion, + ), + ], + ); + }) + .where((element) => element.isDeleted != true) + .toList(); + + return {"data": data, "total_count": count}; + } + } else { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + // Return empty list if no results found + if (nameSelectQuery == null) { + return []; + } else { + // Get total count if offset is zero and filters are applied + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(nameSelectQuery, params, super.sql); + } + await nameSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await nameSelectQuery.get(); + + return _returnHouseHoldModel(results, count); + } + } + } + + // Function to perform proximity search based on provided parameters + proximitySearch( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) { + if (!params.isProximityEnabled) { + return null; + } else if (params.isProximityEnabled) { + selectQuery = super.sql.address.select().join([ + joinHouseHoldAddress(sql), + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.household.clientReferenceId)) + ]) + ..where(buildAnd([ + sql.address.relatedClientReferenceId.isNotNull(), + sql.household.clientReferenceId.isNotNull(), + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + CustomExpression(''' + (6371393 * acos( + cos(${params.latitude! * math.pi / 180.0}) * cos((address.latitude * ${math.pi / 180.0})) + * cos((address.longitude * ${math.pi / 180.0}) - ${params.longitude! * math.pi / 180.0}) + + sin(${params.latitude! * math.pi / 180.0}) * sin((address.latitude * ${math.pi / 180.0})) + )) <= ${params.maxRadius!} + '''), + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + sql.address.longitude.isNotNull(), + sql.address.latitude.isNotNull(), + ])) + ..orderBy([ + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + OrderingTerm( + expression: CustomExpression(''' + (6371393 * acos( + cos(${params.latitude! * math.pi / 180.0}) * cos((address.latitude * ${math.pi / 180.0})) + * cos((address.longitude * ${math.pi / 180.0}) - ${params.longitude! * math.pi / 180.0}) + + sin(${params.latitude! * math.pi / 180.0}) * sin((address.latitude * ${math.pi / 180.0})) + )) + '''), + mode: OrderingMode.asc, + ), + ]); + } + return selectQuery; + } + + // Function to perform name search based on provided parameters + nameSearch( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) async { + if (params.nameSearch == null || params.nameSearch!.isEmpty) { + return selectQuery; + } else if (params.nameSearch != null || + params.nameSearch!.isNotEmpty && selectQuery == null) { + selectQuery = super + .sql + .individual + .select() + .join([joinName(sql), joinIndividualAddress(sql)]); + await searchByName(selectQuery, params, sql); + selectQuery = selectQuery.join([ + leftOuterJoin( + sql.householdMember, + sql.householdMember.individualClientReferenceId + .equalsExp(sql.individual.clientReferenceId)) + ]) + ..where(sql.householdMember.isHeadOfHousehold.equals(true)); + selectQuery.join([ + leftOuterJoin( + sql.household, + sql.household.clientReferenceId + .equalsExp(sql.householdMember.householdClientReferenceId)), + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.household.clientReferenceId)) + ]); + } else if (params.nameSearch != null && + params.nameSearch!.isNotEmpty && + selectQuery != null) { + selectQuery = selectQuery.join([ + joinName(sql), + ]); + selectQuery = searchByName(selectQuery, params, sql); + } + return selectQuery; + } + + // Function to search by name based on provided parameters + searchByName( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) { + return selectQuery.where(buildAnd([ + if (params.nameSearch != null) + buildOr([ + sql.name.givenName.contains( + params.nameSearch!, + ), + ]), + ])); + } + + filterSearch(selectQuery, GlobalSearchParameters params, String filter, + LocalSqlDataStore sql) async { + var sql = super.sql; + if (selectQuery == null) { + if (filter == Status.registered.name || + filter == Status.notRegistered.name) { + selectQuery = sql.household.select().join([ + if (params.nameSearch == null || !params.isProximityEnabled) + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.household.clientReferenceId)) + ]) + ..where(filter == Status.registered.name + ? sql.projectBeneficiary.beneficiaryClientReferenceId.isNotNull() + : sql.projectBeneficiary.beneficiaryClientReferenceId.isNull()); + } else { + var filterSearchQuery = + await filterTasks(selectQuery, filter, sql, params); + + selectQuery = filterSearchQuery; + } + } else if (selectQuery != null) { + if (filter == Status.registered.name || + filter == Status.notRegistered.name) { + selectQuery = selectQuery.join([ + if (params.nameSearch == null && !params.isProximityEnabled) + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.household.clientReferenceId)) + ]) + ..where(filter == Status.registered.name + ? sql.projectBeneficiary.beneficiaryClientReferenceId.isNotNull() + : sql.projectBeneficiary.beneficiaryClientReferenceId.isNull()); + } else { + var filterSearchQuery = + await filterTasks(selectQuery, filter, sql, params); + selectQuery = filterSearchQuery; + } + } + return selectQuery; + } + + filterTasks(selectQuery, String filter, LocalSqlDataStore sql, + GlobalSearchParameters params) { + final statusMap = { + Status.delivered.name: Status.delivered, + Status.notAdministered.name: Status.notAdministered, + Status.visited.name: Status.visited, + Status.notVisited.name: Status.notVisited, + Status.beneficiaryRefused.name: Status.beneficiaryRefused, + Status.beneficiaryReferred.name: Status.beneficiaryReferred, + Status.administeredSuccess.name: Status.administeredSuccess, + Status.administeredFailed.name: Status.administeredFailed, + Status.inComplete.name: Status.inComplete, + Status.toAdminister.name: Status.toAdminister, + Status.closeHousehold.name: Status.closeHousehold, + }; + var applyFilter = filter; + if (selectQuery == null) { + selectQuery = sql.select(sql.task).join([ + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.clientReferenceId + .equalsExp(sql.task.projectBeneficiaryClientReferenceId)), + leftOuterJoin( + sql.household, + sql.household.clientReferenceId + .equalsExp(sql.projectBeneficiary.beneficiaryClientReferenceId)) + ]) + ..where(sql.task.status.equals( + statusMap[applyFilter]!.toValue(), + )); + if (!(params.filter!.contains(Status.notRegistered.name))) { + selectQuery + .where(sql.projectBeneficiary.projectId.equals(params.projectId!)); + } + } else { + selectQuery = selectQuery.join([ + leftOuterJoin( + sql.task, + sql.task.projectBeneficiaryClientReferenceId + .equalsExp(sql.projectBeneficiary.clientReferenceId)) + ]) + ..where(sql.task.status.equals(statusMap[filter]!.toValue())); + + if (!(params.filter!.contains(Status.notRegistered.name))) { + selectQuery + .where(sql.projectBeneficiary.projectId.equals(params.projectId!)); + } + } + + return selectQuery; + } + + joinName(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.name, + sql.name.individualClientReferenceId.equalsExp( + sql.individual.clientReferenceId, + ), + ); + } + + joinHouseHoldAddress(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.household, + sql.household.clientReferenceId.equalsExp( + sql.address.relatedClientReferenceId, + ), + ); + } + + joinIndividualAddress(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.address, + sql.address.relatedClientReferenceId.equalsExp( + sql.individual.clientReferenceId, + ), + ); + } + + joinIndividual(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.individual, + sql.individual.clientReferenceId.equalsExp( + sql.name.individualClientReferenceId, + ), + ); + } + + _returnHouseHoldModel(results, totalCount) { + var data = results + .map((e) { + final household = e.readTable(sql.household); + final address = e.readTableOrNull(sql.address); + + return HouseholdModel( + id: household.id, + tenantId: household.tenantId, + clientReferenceId: household.clientReferenceId, + memberCount: household.memberCount, + rowVersion: household.rowVersion, + isDeleted: household.isDeleted, + additionalFields: household.additionalFields != null && + household.additionalFields.toString().isNotEmpty + ? HouseholdAdditionalFieldsMapper.fromJson( + household.additionalFields.toString()) + : null, + auditDetails: (household.auditCreatedBy != null && + household.auditCreatedTime != null) + ? AuditDetails( + createdBy: household.auditCreatedBy!, + createdTime: household.auditCreatedTime!, + lastModifiedBy: household.auditModifiedBy, + lastModifiedTime: household.auditModifiedTime, + ) + : null, + clientAuditDetails: (household.clientCreatedBy != null && + household.clientCreatedTime != null) + ? ClientAuditDetails( + createdBy: household.clientCreatedBy!, + createdTime: household.clientCreatedTime!, + lastModifiedBy: household.clientModifiedBy, + lastModifiedTime: household.clientModifiedTime, + ) + : null, + address: address == null + ? null + : AddressModel( + id: address.id, + relatedClientReferenceId: household.clientReferenceId, + tenantId: address.tenantId, + doorNo: address.doorNo, + latitude: address.latitude, + longitude: address.longitude, + landmark: address.landmark, + locationAccuracy: address.locationAccuracy, + addressLine1: address.addressLine1, + addressLine2: address.addressLine2, + city: address.city, + pincode: address.pincode, + locality: address.localityBoundaryCode != null + ? LocalityModel( + code: address.localityBoundaryCode!, + name: address.localityBoundaryName, + ) + : null, + type: address.type, + rowVersion: address.rowVersion, + auditDetails: (household.auditCreatedBy != null && + household.auditCreatedBy != null) + ? AuditDetails( + createdBy: household.auditCreatedBy!, + createdTime: household.auditCreatedTime!, + lastModifiedBy: household.auditModifiedBy, + lastModifiedTime: household.auditModifiedTime, + ) + : null, + clientAuditDetails: (household.clientCreatedBy != null && + household.clientCreatedTime != null) + ? ClientAuditDetails( + createdBy: household.clientCreatedBy!, + createdTime: household.clientCreatedTime!, + lastModifiedBy: household.clientModifiedBy, + lastModifiedTime: household.clientModifiedTime, + ) + : null, + ), + ); + }) + .where((element) => element.isDeleted != true) + .toList(); + + return {'total_count': totalCount, 'data': data}; + } + + // Executing custom select query on top of filterSelectQuery to get count + _getTotalCount(filterSelectQuery, GlobalSearchParameters params, + LocalSqlDataStore sql) async { + JoinedSelectStatement selectQuery = filterSelectQuery; + var query = + selectQuery.constructQuery().buffer.toString().replaceAll(';', ''); + var variables = selectQuery.constructQuery().introducedVariables; + var indexesLength = selectQuery.constructQuery().variableIndices; + + var totalCount; + + try { + totalCount = await sql + .customSelect('SELECT COUNT(*) AS total_count FROM ($query)', + variables: indexesLength.isNotEmpty + ? variables.map((e) => Variable(e.value)).toList() + : []) + .get(); + } catch (e) { + debugPrint('error in total $e'); + } + return totalCount == null ? 0 : totalCount.first.data['total_count']; + } +} diff --git a/packages/registration_delivery/lib/data/repositories/local/individual_global_search.dart b/packages/registration_delivery/lib/data/repositories/local/individual_global_search.dart new file mode 100644 index 000000000..abd395fef --- /dev/null +++ b/packages/registration_delivery/lib/data/repositories/local/individual_global_search.dart @@ -0,0 +1,482 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:digit_data_model/data_model.dart'; +import 'package:drift/drift.dart'; +import 'package:flutter/material.dart'; + +import '../../../models/entities/status.dart'; +import '../../../models/entities/task.dart'; +import '../../../models/entities/task_resource.dart'; +import '../../../utils/global_search_parameters.dart'; + +class IndividualGlobalSearchRepository extends LocalRepository { + IndividualGlobalSearchRepository(super.sql, super.opLogManager); + + @override + FutureOr> search(EntitySearchModel query) { + throw UnimplementedError(); + } + + @override + DataModelType get type => throw UnimplementedError(); + + individualGlobalSearch(GlobalSearchParameters params) async { + dynamic selectQuery; + late int? count = params.totalCount == 0 ? 0 : params.totalCount; + + // Check if the filter contains status for registered or not registered + if (params.filter!.contains(Status.registered.name) || + params.filter!.contains(Status.notRegistered.name)) { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + var filterSelectQuery = nameSelectQuery; + + if (params.filter != null && params.filter!.isNotEmpty) { + for (var filter in params.filter!) { + filterSelectQuery = + await filterSearch(filterSelectQuery, params, filter, super.sql); + } + } else { + filterSelectQuery = nameSelectQuery; + } + + if (filterSelectQuery == null) { + return []; + } + // Get total count if offset is zero and filters are applied + else { + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(filterSelectQuery, params, super.sql); + } + + await filterSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await filterSelectQuery.get(); + + return _returnIndividualModel(results, count); + } + } else if (params.filter!.isNotEmpty && params.filter != null) { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + var filterSelectQuery = nameSelectQuery; + + // Apply filters if present + if (params.filter != null && params.filter!.isNotEmpty) { + for (var filter in params.filter!) { + filterSelectQuery = + await filterSearch(filterSelectQuery, params, filter, super.sql); + } + } else { + filterSelectQuery = nameSelectQuery; + } + + // Return empty list if no results found + if (filterSelectQuery == null) { + return []; + } else { + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(filterSelectQuery, params, super.sql); + } + await filterSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await filterSelectQuery.get(); + var data = results + .map((e) { + final task = e.readTableOrNull(sql.task); + final resources = e.readTableOrNull(sql.taskResource); + + return TaskModel( + id: task.id, + createdBy: task.createdBy, + clientReferenceId: task.clientReferenceId, + rowVersion: task.rowVersion, + tenantId: task.tenantId, + isDeleted: task.isDeleted, + projectId: task.projectId, + projectBeneficiaryId: task.projectBeneficiaryId, + projectBeneficiaryClientReferenceId: + task.projectBeneficiaryClientReferenceId, + createdDate: task.createdDate, + status: task.status, + resources: resources == null + ? null + : [ + TaskResourceModel( + taskclientReferenceId: + resources.taskclientReferenceId, + clientReferenceId: resources.clientReferenceId, + id: resources.id, + productVariantId: resources.productVariantId, + taskId: resources.taskId, + deliveryComment: resources.deliveryComment, + quantity: resources.quantity, + rowVersion: resources.rowVersion, + ), + ], + ); + }) + .where((element) => element.isDeleted != true) + .toList(); + + return {"data": data, "total_count": count}; + } + } else { + var proximitySelectQuery = + await proximitySearch(selectQuery, params, super.sql); + + var nameSelectQuery = + await nameSearch(proximitySelectQuery, params, super.sql); + + // Return empty list if no results found + if (nameSelectQuery == null) { + return []; + } else { + // Get total count if offset is zero and filters are applied + if (params.offset == 0 && + params.filter != null && + params.filter!.isNotEmpty) { + count = await _getTotalCount(nameSelectQuery, params, super.sql); + } + await nameSelectQuery.limit(params.limit ?? 50, + offset: params.offset ?? 0); + + final results = await nameSelectQuery.get(); + + return _returnIndividualModel(results, count); + } + } + } + + proximitySearch( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) { + if (!params.isProximityEnabled) { + return null; + } else if (params.isProximityEnabled) { + selectQuery = super.sql.individual.select().join([ + joinIndividualAddress(sql), + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.individual.clientReferenceId)) + ]) + ..where(buildAnd([ + sql.address.relatedClientReferenceId.isNotNull(), + sql.individual.clientReferenceId.isNotNull(), + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + CustomExpression(''' + (6371393 * acos( + cos(${params.latitude! * math.pi / 180.0}) * cos((address.latitude * ${math.pi / 180.0})) + * cos((address.longitude * ${math.pi / 180.0}) - ${params.longitude! * math.pi / 180.0}) + + sin(${params.latitude! * math.pi / 180.0}) * sin((address.latitude * ${math.pi / 180.0})) + )) <= ${params.maxRadius!} + '''), + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + sql.address.longitude.isNotNull(), + sql.address.latitude.isNotNull(), + ])) + ..orderBy([ + if (params.latitude != null && + params.longitude != null && + params.maxRadius != null) + OrderingTerm( + expression: CustomExpression(''' + (6371393 * acos( + cos(${params.latitude! * math.pi / 180.0}) * cos((address.latitude * ${math.pi / 180.0})) + * cos((address.longitude * ${math.pi / 180.0}) - ${params.longitude! * math.pi / 180.0}) + + sin(${params.latitude! * math.pi / 180.0}) * sin((address.latitude * ${math.pi / 180.0})) + )) + '''), + mode: OrderingMode.asc, + ), + ]); + } + return selectQuery; + } + + // Function to perform name search based on provided parameters + nameSearch( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) async { + if (params.nameSearch == null || params.nameSearch!.isEmpty) { + return selectQuery; + } else if (params.nameSearch != null || + params.nameSearch!.isNotEmpty && selectQuery == null) { + selectQuery = super + .sql + .individual + .select() + .join([joinName(sql), joinIndividualAddress(sql)]); + await searchByName(selectQuery, params, sql); + selectQuery = selectQuery.join([ + leftOuterJoin( + sql.householdMember, + sql.householdMember.individualClientReferenceId + .equalsExp(sql.individual.clientReferenceId)) + ]) + ..where(sql.householdMember.isHeadOfHousehold.equals(true)); + selectQuery.join([ + leftOuterJoin( + sql.household, + sql.household.clientReferenceId + .equalsExp(sql.householdMember.householdClientReferenceId)), + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.household.clientReferenceId)) + ]); + } else if (params.nameSearch != null && + params.nameSearch!.isNotEmpty && + selectQuery != null) { + selectQuery = selectQuery.join([ + joinName(sql), + ]); + selectQuery = searchByName(selectQuery, params, sql); + } + return selectQuery; + } + + searchByName( + selectQuery, GlobalSearchParameters params, LocalSqlDataStore sql) { + return selectQuery.where(buildAnd([ + if (params.nameSearch != null) + buildOr([ + sql.name.givenName.contains( + params.nameSearch!, + ), + ]), + ])); + } + + filterSearch(selectQuery, GlobalSearchParameters params, String filter, + LocalSqlDataStore sql) async { + var sql = super.sql; + if (selectQuery == null) { + if (filter == Status.registered.name || + filter == Status.notRegistered.name) { + selectQuery = sql.individual.select().join([ + if (params.nameSearch == null || !params.isProximityEnabled) + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.individual.clientReferenceId)) + ]) + ..where(filter == Status.registered.name + ? sql.projectBeneficiary.beneficiaryClientReferenceId.isNotNull() + : sql.projectBeneficiary.beneficiaryClientReferenceId.isNull()); + } else { + var filterSearchQuery = + await filterTasks(selectQuery, filter, sql, params); + + selectQuery = filterSearchQuery; + } + } else if (selectQuery != null) { + if (filter == Status.registered.name || + filter == Status.notRegistered.name) { + selectQuery = selectQuery.join([ + if (params.nameSearch == null && !params.isProximityEnabled) + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.beneficiaryClientReferenceId + .equalsExp(sql.individual.clientReferenceId)) + ]) + ..where(filter == Status.registered.name + ? sql.projectBeneficiary.beneficiaryClientReferenceId.isNotNull() + : sql.projectBeneficiary.beneficiaryClientReferenceId.isNull()); + } else { + var filterSearchQuery = + await filterTasks(selectQuery, filter, sql, params); + selectQuery = filterSearchQuery; + } + } + return selectQuery; + } + + filterTasks(selectQuery, String filter, LocalSqlDataStore sql, + GlobalSearchParameters params) { + final statusMap = { + Status.delivered.name: Status.delivered, + Status.notAdministered.name: Status.notAdministered, + Status.visited.name: Status.visited, + Status.notVisited.name: Status.notVisited, + Status.beneficiaryRefused.name: Status.beneficiaryRefused, + Status.beneficiaryReferred.name: Status.beneficiaryReferred, + Status.administeredSuccess.name: Status.administeredSuccess, + Status.administeredFailed.name: Status.administeredFailed, + Status.inComplete.name: Status.inComplete, + Status.toAdminister.name: Status.toAdminister, + Status.closeHousehold.name: Status.closeHousehold, + }; + var applyFilter = filter; + if (selectQuery == null) { + selectQuery = sql.select(sql.task).join([ + leftOuterJoin( + sql.projectBeneficiary, + sql.projectBeneficiary.clientReferenceId + .equalsExp(sql.task.projectBeneficiaryClientReferenceId)), + leftOuterJoin( + sql.individual, + sql.individual.clientReferenceId + .equalsExp(sql.projectBeneficiary.beneficiaryClientReferenceId)), + ]) + ..where(sql.task.status.equals( + statusMap[applyFilter]!.toValue(), + )); + if (!(params.filter!.contains(Status.notRegistered.name))) { + selectQuery + .where(sql.projectBeneficiary.projectId.equals(params.projectId!)); + } + } else { + selectQuery = selectQuery.join([ + leftOuterJoin( + sql.task, + sql.task.projectBeneficiaryClientReferenceId + .equalsExp(sql.projectBeneficiary.clientReferenceId)) + ]) + ..where(sql.task.status.equals(statusMap[filter]!.toValue())); + + if (!(params.filter!.contains(Status.notRegistered.name))) { + selectQuery + .where(sql.projectBeneficiary.projectId.equals(params.projectId!)); + } + } + + return selectQuery; + } + + joinName(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.name, + sql.name.individualClientReferenceId.equalsExp( + sql.individual.clientReferenceId, + ), + ); + } + + joinIndividualAddress(LocalSqlDataStore sql) { + return leftOuterJoin( + sql.address, + sql.address.relatedClientReferenceId.equalsExp( + sql.individual.clientReferenceId, + ), + ); + } + + joinProjectBeneficiary(LocalSqlDataStore sql) { + return leftOuterJoin(sql.projectBeneficiary, + sql.projectBeneficiary.clientReferenceId.isNotNull()); + } + + // Executing custom select query on top of filterSelectQuery to get count + _getTotalCount(filterSelectQuery, GlobalSearchParameters params, + LocalSqlDataStore sql) async { + JoinedSelectStatement selectQuery = filterSelectQuery; + var query = + selectQuery.constructQuery().buffer.toString().replaceAll(';', ''); + var variables = selectQuery.constructQuery().introducedVariables; + var indexesLength = selectQuery.constructQuery().variableIndices; + + var totalCount; + + try { + totalCount = await sql + .customSelect('SELECT COUNT(*) AS total_count FROM ($query)', + variables: indexesLength.isNotEmpty + ? variables.map((e) => Variable(e.value)).toList() + : []) + .get(); + } catch (e) { + debugPrint('error in total $e'); + } + return totalCount == null ? 0 : totalCount.first.data['total_count']; + } + + _returnIndividualModel(results, int? count) { + var data = results + .map((e) { + final individual = e.readTableOrNull(sql.individual); + final address = e.readTableOrNull(sql.address); + final name = e.readTableOrNull(sql.name); + + return IndividualModel( + id: individual?.id, + tenantId: individual?.tenantId, + clientReferenceId: individual!.clientReferenceId, + dateOfBirth: individual.dateOfBirth, + name: NameModel( + givenName: name?.givenName, + individualClientReferenceId: individual.clientReferenceId, + tenantId: individual.tenantId, + auditDetails: AuditDetails( + createdBy: individual.auditCreatedBy!, + createdTime: individual.auditCreatedTime!, + lastModifiedBy: individual.auditModifiedBy, + lastModifiedTime: individual.auditModifiedTime, + ), + ), + rowVersion: individual.rowVersion, + isDeleted: individual.isDeleted, + auditDetails: AuditDetails( + createdBy: individual.auditCreatedBy!, + createdTime: individual.auditCreatedTime!, + lastModifiedBy: individual.auditModifiedBy, + lastModifiedTime: individual.auditModifiedTime, + ), + address: address == null + ? null + : [ + AddressModel( + id: address.id, + relatedClientReferenceId: + address.relatedClientReferenceId, + tenantId: address.tenantId, + doorNo: address.doorNo, + latitude: address.latitude, + longitude: address.longitude, + landmark: address.landmark, + locationAccuracy: address.locationAccuracy, + addressLine1: address.addressLine1, + addressLine2: address.addressLine2, + city: address.city, + pincode: address.pincode, + locality: address.localityBoundaryCode != null + ? LocalityModel( + code: address.localityBoundaryCode!, + name: address.localityBoundaryName, + ) + : null, + type: address.type, + rowVersion: address.rowVersion, + auditDetails: AuditDetails( + createdBy: individual.auditCreatedBy!, + createdTime: individual.auditCreatedTime!, + lastModifiedBy: individual.auditModifiedBy, + lastModifiedTime: individual.auditModifiedTime, + ), + ), + ], + ); + }) + .where((element) => element.isDeleted != true) + .toList(); + + return {'total_count': count, 'data': data}; + } +} diff --git a/packages/registration_delivery/lib/data/repositories/local/project_beneficiary.dart b/packages/registration_delivery/lib/data/repositories/local/project_beneficiary.dart index f263aff49..1a63c8013 100644 --- a/packages/registration_delivery/lib/data/repositories/local/project_beneficiary.dart +++ b/packages/registration_delivery/lib/data/repositories/local/project_beneficiary.dart @@ -3,7 +3,6 @@ import 'dart:async'; import 'package:digit_data_model/data_model.dart'; import 'package:drift/drift.dart'; import 'package:registration_delivery/models/entities/project_beneficiary.dart'; -import 'package:registration_delivery/utils/utils.dart'; class ProjectBeneficiaryLocalRepository extends LocalRepository< ProjectBeneficiaryModel, ProjectBeneficiarySearchModel> { diff --git a/packages/registration_delivery/lib/data/repositories/local/referral.dart b/packages/registration_delivery/lib/data/repositories/local/referral.dart index 9fe366ebf..5bd72f96d 100644 --- a/packages/registration_delivery/lib/data/repositories/local/referral.dart +++ b/packages/registration_delivery/lib/data/repositories/local/referral.dart @@ -4,7 +4,6 @@ import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:drift/drift.dart'; import 'package:registration_delivery/models/entities/referral.dart'; -import 'package:registration_delivery/utils/utils.dart'; class ReferralLocalRepository extends LocalRepository { diff --git a/packages/registration_delivery/lib/data/repositories/local/registration_delivery_address.dart b/packages/registration_delivery/lib/data/repositories/local/registration_delivery_address.dart index 30cf29c4e..426c71540 100644 --- a/packages/registration_delivery/lib/data/repositories/local/registration_delivery_address.dart +++ b/packages/registration_delivery/lib/data/repositories/local/registration_delivery_address.dart @@ -3,8 +3,6 @@ import 'dart:math' as math; import 'package:digit_data_model/data_model.dart'; import 'package:drift/drift.dart'; -import 'package:drift/native.dart'; -import 'package:registration_delivery/utils/utils.dart'; import '../../../models/entities/household.dart'; @@ -78,6 +76,11 @@ class RegistrationDeliveryAddressRepo extends AddressLocalRepository { memberCount: household.memberCount, rowVersion: household.rowVersion, isDeleted: household.isDeleted, + additionalFields: household.additionalFields != null && + household.additionalFields.toString().isNotEmpty + ? HouseholdAdditionalFieldsMapper.fromJson( + household.additionalFields.toString()) + : null, auditDetails: AuditDetails( createdBy: household.auditCreatedBy!, createdTime: household.auditCreatedTime!, diff --git a/packages/registration_delivery/lib/data/repositories/local/task.dart b/packages/registration_delivery/lib/data/repositories/local/task.dart index f54a89f5c..dbddb9607 100644 --- a/packages/registration_delivery/lib/data/repositories/local/task.dart +++ b/packages/registration_delivery/lib/data/repositories/local/task.dart @@ -2,12 +2,10 @@ import 'dart:async'; import 'package:collection/collection.dart'; import 'package:digit_data_model/data_model.dart'; -import 'package:digit_data_model/models/oplog/oplog_entry.dart'; import 'package:drift/drift.dart'; import 'package:registration_delivery/models/entities/task_resource.dart'; import '../../../models/entities/task.dart'; -import '../../../utils/utils.dart'; class TaskLocalRepository extends LocalRepository { TaskLocalRepository( @@ -289,16 +287,16 @@ class TaskLocalRepository extends LocalRepository { resourcesCompanions, mode: InsertMode.insertOrReplace, ); + } - if (addresses != null) { - final addressCompanions = addresses.companion; + if (addresses != null) { + final addressCompanions = addresses.companion; - batch.insert( - sql.address, - addressCompanions, - mode: InsertMode.insertOrReplace, - ); - } + batch.insert( + sql.address, + addressCompanions, + mode: InsertMode.insertOrReplace, + ); } await super.create( @@ -364,49 +362,51 @@ class TaskLocalRepository extends LocalRepository { TaskModel entity, { bool createOpLog = true, }) async { - final taskCompanion = entity.companion; - - final addressCompanion = entity.address - ?.copyWith( - relatedClientReferenceId: entity.clientReferenceId, - auditDetails: entity.auditDetails, - clientAuditDetails: entity.clientAuditDetails, - ) - .companion; - - final resourcesCompanions = entity.resources?.map((e) { - return e - .copyWith( - clientReferenceId: e.clientReferenceId, - taskclientReferenceId: entity.clientReferenceId, - ) - .companion; - }).toList() ?? - []; + return retryLocalCallOperation(() async { + final taskCompanion = entity.companion; - await sql.batch((batch) { - batch.update( - sql.task, - taskCompanion, - where: (table) => table.clientReferenceId.equals( - entity.clientReferenceId, - ), - ); + final addressCompanion = entity.address + ?.copyWith( + relatedClientReferenceId: entity.clientReferenceId, + auditDetails: entity.auditDetails, + clientAuditDetails: entity.clientAuditDetails, + ) + .companion; - if (addressCompanion != null) { + final resourcesCompanions = entity.resources?.map((e) { + return e + .copyWith( + clientReferenceId: e.clientReferenceId, + taskclientReferenceId: entity.clientReferenceId, + ) + .companion; + }).toList() ?? + []; + + await sql.batch((batch) { batch.update( - sql.address, - addressCompanion, - where: (table) => table.relatedClientReferenceId.equals( - addressCompanion.relatedClientReferenceId.value!, + sql.task, + taskCompanion, + where: (table) => table.clientReferenceId.equals( + entity.clientReferenceId, ), ); - } - batch.insertAllOnConflictUpdate(sql.taskResource, resourcesCompanions); - }); + if (addressCompanion != null) { + batch.update( + sql.address, + addressCompanion, + where: (table) => table.relatedClientReferenceId.equals( + addressCompanion.relatedClientReferenceId.value!, + ), + ); + } + + batch.insertAllOnConflictUpdate(sql.taskResource, resourcesCompanions); + }); - await super.update(entity, createOpLog: createOpLog); + await super.update(entity, createOpLog: createOpLog); + }); } @override diff --git a/packages/registration_delivery/lib/models/entities/additional_fields_type.dart b/packages/registration_delivery/lib/models/entities/additional_fields_type.dart index 62dc38b30..5906e3791 100644 --- a/packages/registration_delivery/lib/models/entities/additional_fields_type.dart +++ b/packages/registration_delivery/lib/models/entities/additional_fields_type.dart @@ -39,4 +39,14 @@ enum AdditionalFieldsType { latitude, @MappableValue("longitude") longitude, + @MappableValue("pregnantWomen") + pregnantWomen, + @MappableValue("children") + children, + @MappableValue("noOfRooms") + noOfRooms, + @MappableValue("houseStructureTypes") + houseStructureTypes, + @MappableValue("reasonOfRefusal") + reasonOfRefusal, } diff --git a/packages/registration_delivery/lib/models/entities/additional_fields_type.mapper.dart b/packages/registration_delivery/lib/models/entities/additional_fields_type.mapper.dart index 8e1f6fec5..62bd69053 100644 --- a/packages/registration_delivery/lib/models/entities/additional_fields_type.mapper.dart +++ b/packages/registration_delivery/lib/models/entities/additional_fields_type.mapper.dart @@ -59,6 +59,16 @@ class AdditionalFieldsTypeMapper extends EnumMapper { return AdditionalFieldsType.latitude; case "longitude": return AdditionalFieldsType.longitude; + case "pregnantWomen": + return AdditionalFieldsType.pregnantWomen; + case "children": + return AdditionalFieldsType.children; + case "noOfRooms": + return AdditionalFieldsType.noOfRooms; + case "houseStructureTypes": + return AdditionalFieldsType.houseStructureTypes; + case "reasonOfRefusal": + return AdditionalFieldsType.reasonOfRefusal; default: throw MapperException.unknownEnumValue(value); } @@ -101,6 +111,16 @@ class AdditionalFieldsTypeMapper extends EnumMapper { return "latitude"; case AdditionalFieldsType.longitude: return "longitude"; + case AdditionalFieldsType.pregnantWomen: + return "pregnantWomen"; + case AdditionalFieldsType.children: + return "children"; + case AdditionalFieldsType.noOfRooms: + return "noOfRooms"; + case AdditionalFieldsType.houseStructureTypes: + return "houseStructureTypes"; + case AdditionalFieldsType.reasonOfRefusal: + return "reasonOfRefusal"; } } } diff --git a/packages/registration_delivery/lib/models/entities/registration_delivery_enums.dart b/packages/registration_delivery/lib/models/entities/registration_delivery_enums.dart new file mode 100644 index 000000000..d83124cc3 --- /dev/null +++ b/packages/registration_delivery/lib/models/entities/registration_delivery_enums.dart @@ -0,0 +1,14 @@ +// Generated using mason. Do not modify by hand +import 'package:dart_mappable/dart_mappable.dart'; + +part 'registration_delivery_enums.mapper.dart'; + +@MappableEnum(caseStyle: CaseStyle.upperCase) +enum RegistrationDeliveryEnums { + @MappableValue("name") + name, + @MappableValue("userName") + userName, + @MappableValue("IEC") + iec, +} diff --git a/packages/registration_delivery/lib/models/entities/registration_delivery_enums.mapper.dart b/packages/registration_delivery/lib/models/entities/registration_delivery_enums.mapper.dart new file mode 100644 index 000000000..96206f505 --- /dev/null +++ b/packages/registration_delivery/lib/models/entities/registration_delivery_enums.mapper.dart @@ -0,0 +1,60 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, unnecessary_cast +// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter + +part of 'registration_delivery_enums.dart'; + +class RegistrationDeliveryEnumsMapper + extends EnumMapper { + RegistrationDeliveryEnumsMapper._(); + + static RegistrationDeliveryEnumsMapper? _instance; + static RegistrationDeliveryEnumsMapper ensureInitialized() { + if (_instance == null) { + MapperContainer.globals + .use(_instance = RegistrationDeliveryEnumsMapper._()); + } + return _instance!; + } + + static RegistrationDeliveryEnums fromValue(dynamic value) { + ensureInitialized(); + return MapperContainer.globals.fromValue(value); + } + + @override + RegistrationDeliveryEnums decode(dynamic value) { + switch (value) { + case "name": + return RegistrationDeliveryEnums.name; + case "userName": + return RegistrationDeliveryEnums.userName; + case "IEC": + return RegistrationDeliveryEnums.iec; + default: + throw MapperException.unknownEnumValue(value); + } + } + + @override + dynamic encode(RegistrationDeliveryEnums self) { + switch (self) { + case RegistrationDeliveryEnums.name: + return "name"; + case RegistrationDeliveryEnums.userName: + return "userName"; + case RegistrationDeliveryEnums.iec: + return "IEC"; + } + } +} + +extension RegistrationDeliveryEnumsMapperExtension + on RegistrationDeliveryEnums { + dynamic toValue() { + RegistrationDeliveryEnumsMapper.ensureInitialized(); + return MapperContainer.globals.toValue(this); + } +} diff --git a/packages/registration_delivery/lib/models/entities/status.dart b/packages/registration_delivery/lib/models/entities/status.dart index e7996833c..c3cb7c79f 100644 --- a/packages/registration_delivery/lib/models/entities/status.dart +++ b/packages/registration_delivery/lib/models/entities/status.dart @@ -2,17 +2,33 @@ import 'package:dart_mappable/dart_mappable.dart'; part 'status.mapper.dart'; + @MappableEnum(caseStyle: CaseStyle.upperCase) enum Status { - @MappableValue("DELIVERED") delivered, - @MappableValue("NOT_DELIVERED") notDelivered, - @MappableValue("VISITED") visited, - @MappableValue("NOT_VISITED") notVisited, - @MappableValue("BENEFICIARY_REFUSED") beneficiaryRefused, - @MappableValue("BENEFICIARY_REFERRED") beneficiaryReferred, - @MappableValue("ADMINISTERED_SUCCESS") administeredSuccess, - @MappableValue("ADMINISTERED_FAILED") administeredFailed, - @MappableValue("IN_COMPLETE") inComplete, - @MappableValue("TO_ADMINISTER") toAdminister, - ; -} \ No newline at end of file + @MappableValue("DELIVERED") + delivered, + @MappableValue("NOT_ADMINISTERED") + notAdministered, + @MappableValue("VISITED") + visited, + @MappableValue("NOT_VISITED") + notVisited, + @MappableValue("BENEFICIARY_REFUSED") + beneficiaryRefused, + @MappableValue("BENEFICIARY_REFERRED") + beneficiaryReferred, + @MappableValue("ADMINISTRATION_SUCCESS") + administeredSuccess, + @MappableValue("ADMINISTRATION_FAILED") + administeredFailed, + @MappableValue("IN_COMPLETE") + inComplete, + @MappableValue("TO_ADMINISTER") + toAdminister, + @MappableValue("REGISTERED") + registered, + @MappableValue("NOT_REGISTERED") + notRegistered, + @MappableValue("CLOSED_HOUSEHOLD") + closeHousehold, +} diff --git a/packages/registration_delivery/lib/models/entities/status.mapper.dart b/packages/registration_delivery/lib/models/entities/status.mapper.dart index dffb822cc..3f1896d6e 100644 --- a/packages/registration_delivery/lib/models/entities/status.mapper.dart +++ b/packages/registration_delivery/lib/models/entities/status.mapper.dart @@ -27,8 +27,8 @@ class StatusMapper extends EnumMapper { switch (value) { case "DELIVERED": return Status.delivered; - case "NOT_DELIVERED": - return Status.notDelivered; + case "NOT_ADMINISTERED": + return Status.notAdministered; case "VISITED": return Status.visited; case "NOT_VISITED": @@ -37,14 +37,20 @@ class StatusMapper extends EnumMapper { return Status.beneficiaryRefused; case "BENEFICIARY_REFERRED": return Status.beneficiaryReferred; - case "ADMINISTERED_SUCCESS": + case "ADMINISTRATION_SUCCESS": return Status.administeredSuccess; - case "ADMINISTERED_FAILED": + case "ADMINISTRATION_FAILED": return Status.administeredFailed; case "IN_COMPLETE": return Status.inComplete; case "TO_ADMINISTER": return Status.toAdminister; + case "REGISTERED": + return Status.registered; + case "NOT_REGISTERED": + return Status.notRegistered; + case "CLOSED_HOUSEHOLD": + return Status.closeHousehold; default: throw MapperException.unknownEnumValue(value); } @@ -55,8 +61,8 @@ class StatusMapper extends EnumMapper { switch (self) { case Status.delivered: return "DELIVERED"; - case Status.notDelivered: - return "NOT_DELIVERED"; + case Status.notAdministered: + return "NOT_ADMINISTERED"; case Status.visited: return "VISITED"; case Status.notVisited: @@ -66,13 +72,19 @@ class StatusMapper extends EnumMapper { case Status.beneficiaryReferred: return "BENEFICIARY_REFERRED"; case Status.administeredSuccess: - return "ADMINISTERED_SUCCESS"; + return "ADMINISTRATION_SUCCESS"; case Status.administeredFailed: - return "ADMINISTERED_FAILED"; + return "ADMINISTRATION_FAILED"; case Status.inComplete: return "IN_COMPLETE"; case Status.toAdminister: return "TO_ADMINISTER"; + case Status.registered: + return "REGISTERED"; + case Status.notRegistered: + return "NOT_REGISTERED"; + case Status.closeHousehold: + return "CLOSED_HOUSEHOLD"; } } } diff --git a/packages/registration_delivery/lib/pages/beneficiary/beneficiary_checklist.dart b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_checklist.dart new file mode 100644 index 000000000..16538f7fa --- /dev/null +++ b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_checklist.dart @@ -0,0 +1,526 @@ +import 'dart:math'; + +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/utils/constants.dart'; + +import '../../router/registration_delivery_router.gm.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../utils/utils.dart'; +import '../../widgets/back_navigation_help_header.dart'; +import '../../widgets/localized.dart'; + +@RoutePage() +class BeneficiaryChecklistPage extends LocalizedStatefulWidget { + final String? beneficiaryClientRefId; + const BeneficiaryChecklistPage({ + super.key, + this.beneficiaryClientRefId, + super.appLocalizations, + }); + + @override + State createState() => + _BeneficiaryChecklistPageState(); +} + +class _BeneficiaryChecklistPageState + extends LocalizedState { + String isStateChanged = ''; + var submitTriggered = false; + var validFields = true; + List controller = []; + List additionalController = []; + List? initialAttributes; + ServiceDefinitionModel? selectedServiceDefinition; + bool isControllersInitialized = false; + List visibleChecklistIndexes = []; + GlobalKey checklistFormKey = GlobalKey(); + + @override + void initState() { + context.read().add( + ServiceChecklistEvent( + value: Random().nextInt(100).toString(), + submitTriggered: true, + ), + ); + + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return PopScope( + canPop: false, + child: Scaffold( + body: BlocBuilder( + builder: (context, state) { + state.mapOrNull( + serviceDefinitionFetch: (value) { + selectedServiceDefinition = value.serviceDefinitionList + .where((element) => element.code + .toString() + .contains('IRS.TRAINING_SUPERVISION.DISTRIBUTOR')) + .toList() + .first; + + initialAttributes = selectedServiceDefinition?.attributes; + if (!isControllersInitialized) { + initialAttributes?.forEach((e) { + controller.add(TextEditingController()); + }); + + // Set the flag to true after initializing controllers + isControllersInitialized = true; + } + }, + ); + + return state.maybeMap( + orElse: () => Text(state.runtimeType.toString()), + serviceDefinitionFetch: (value) { + return ScrollableContent( + header: Column(children: [ + BackNavigationHelpHeaderWidget( + showHelp: false, + handleBack: () { + //TODO: direct go back is not working, need to check + Navigator.pop(context); + }, + ), + ]), + enableFixedButton: true, + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: + const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: DigitElevatedButton( + onPressed: () async { + // TODO: Submit checklist + final router = context.router; + submitTriggered = true; + + context.read().add( + const ServiceChecklistEvent( + value: '', + submitTriggered: true, + ), + ); + final isValid = + checklistFormKey.currentState?.validate(); + if (!isValid!) { + return; + } + final itemsAttributes = initialAttributes; + + var validChecklist = true; + + for (int i = 0; i < controller.length; i++) { + if (itemsAttributes?[i].required == true && + ((itemsAttributes?[i].dataType == 'Boolean' && + (controller[i].text == '')))) { + setState(() { + validFields = false; + validChecklist = false; + }); + } + } + + if (!validChecklist) { + return; + } + List attributes = []; + for (int i = 0; i < controller.length; i++) { + final attribute = initialAttributes; + attributes.add(ServiceAttributesModel( + attributeCode: '${attribute?[i].code}', + dataType: attribute?[i].dataType, + clientReferenceId: IdGen.i.identifier, + referenceId: widget.beneficiaryClientRefId, + value: attribute?[i].dataType != 'SingleValueList' + ? controller[i] + .text + .toString() + .trim() + .isNotEmpty + ? controller[i].text.toString() + : '' + : visibleChecklistIndexes.contains(i) + ? controller[i].text.toString() + : i18.checklist.notSelectedKey, + rowVersion: 1, + tenantId: attribute?[i].tenantId, + additionalDetails: null, + )); + } + + context.read().add( + ServiceCreateEvent( + serviceModel: ServiceModel( + createdAt: + DigitDateUtils.getDateFromTimestamp( + DateTime.now() + .toLocal() + .millisecondsSinceEpoch, + dateFormat: + Constants.checklistViewDateFormat, + ), + tenantId: selectedServiceDefinition!.tenantId, + clientId: + widget.beneficiaryClientRefId.toString(), + serviceDefId: selectedServiceDefinition?.id, + attributes: attributes, + rowVersion: 1, + accountId: + RegistrationDeliverySingleton().projectId, + additionalDetails: + RegistrationDeliverySingleton() + .boundary + ?.code, + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: + DateTime.now().millisecondsSinceEpoch, + ), + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: + DateTime.now().millisecondsSinceEpoch, + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid!, + lastModifiedTime: + DateTime.now().millisecondsSinceEpoch, + ), + ), + ), + ); + + DigitDialog.show( + context, + options: DigitDialogOptions( + titleText: localizations.translate(i18 + .deliverIntervention + .beneficiaryChecklistDialogTitle), + titlePadding: const EdgeInsets.only(top: kPadding), + barrierDismissible: false, + enableRecordPast: true, + dialogPadding: const EdgeInsets.fromLTRB( + kPadding, + kPadding, + kPadding, + 0, + ), + contentPadding: EdgeInsets.zero, + primaryAction: DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonYes, + ), + action: (ctx) { + Navigator.of(ctx).pop(); + ctx.router.push( + DeliverInterventionRoute(), + ); + }, + ), + secondaryAction: DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonNo, + ), + action: (ctx) { + Navigator.of(ctx).pop(); + ctx.router.push( + RefusedDeliveryRoute(), + ); + }, + ), + ), + ); + }, + child: Text( + localizations.translate(i18.common.coreCommonSubmit), + ), + ), + ), + children: [ + Form( + key: checklistFormKey, //assigning key to form + child: DigitCard( + padding: EdgeInsets.zero, + child: Column(children: [ + ...initialAttributes!.map(( + e, + ) { + int index = (initialAttributes ?? []).indexOf(e); + + return Column(children: [ + if (e.dataType == 'String' && + !(e.code ?? '').contains('.')) ...[ + DigitTextField( + onChange: (value) { + checklistFormKey.currentState?.validate(); + }, + isRequired: false, + controller: controller[index], + inputFormatter: [ + FilteringTextInputFormatter.allow(RegExp( + "[a-zA-Z0-9]", + )), + ], + validator: (value) { + if (((value == null || value == '') && + e.required == true)) { + return localizations + .translate("${e.code}_REQUIRED"); + } + if (e.regex != null) { + return (RegExp(e.regex!).hasMatch(value!)) + ? null + : localizations + .translate("${e.code}_REGEX"); + } + + return null; + }, + label: localizations.translate( + '${selectedServiceDefinition?.code}.${e.code}', + ), + ), + ] else if (e.dataType == 'Number' && + !(e.code ?? '').contains('.')) ...[ + DigitTextField( + onChange: (value) { + checklistFormKey.currentState?.validate(); + }, + textStyle: theme.textTheme.headlineMedium, + textInputType: TextInputType.number, + inputFormatter: [ + FilteringTextInputFormatter.allow(RegExp( + "[0-9]", + )), + ], + validator: (value) { + if (((value == null || value == '') && + e.required == true)) { + return localizations.translate( + i18.common.corecommonRequired, + ); + } + if (e.regex != null) { + return (RegExp(e.regex!).hasMatch(value!)) + ? null + : localizations + .translate("${e.code}_REGEX"); + } + + return null; + }, + controller: controller[index], + label: '${localizations.translate( + '${value.selectedServiceDefinition?.code}.${e.code}', + ).trim()} ${e.required == true ? '*' : ''}', + ), + ] else if (e.dataType == 'MultiValueList' && + !(e.code ?? '').contains('.')) ...[ + Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.all(8), + child: Column( + children: [ + Text( + '${localizations.translate( + '${selectedServiceDefinition?.code}.${e.code}', + )} ${e.required == true ? '*' : ''}', + style: theme.textTheme.headlineSmall, + ), + ], + ), + ), + ), + BlocBuilder( + builder: (context, state) { + return Column( + children: e.values! + .map((e) => DigitCheckboxTile( + label: e, + value: controller[index] + .text + .split('.') + .contains(e), + onChanged: (value) { + context + .read() + .add( + ServiceChecklistEvent( + value: e.toString(), + submitTriggered: + submitTriggered, + ), + ); + final String ele; + var val = controller[index] + .text + .split('.'); + if (val.contains(e)) { + val.remove(e); + ele = val.join("."); + } else { + ele = + "${controller[index].text}.$e"; + } + controller[index].value = + TextEditingController + .fromValue( + TextEditingValue( + text: ele, + ), + ).value; + }, + )) + .toList(), + ); + }, + ), + ] else if (e.dataType == 'Boolean') ...[ + if (!(e.code ?? '').contains('.')) + DigitCard( + child: Column( + children: [ + Align( + alignment: Alignment.topLeft, + child: Padding( + padding: EdgeInsets.zero, + child: Column( + children: [ + Text( + '${localizations.translate( + '${selectedServiceDefinition?.code}.${e.code}', + )} ${e.required == true ? '*' : ''}', + style: theme + .textTheme.headlineSmall, + ), + ], + ), + ), + ), + BlocBuilder( + builder: (context, state) { + return SelectionBox( + //label: e, + allowMultipleSelection: false, + width: 110, + valueMapper: (value) { + return value + ? localizations.translate( + i18.common + .coreCommonYes, + ) + : localizations.translate( + i18.common.coreCommonNo, + ); + }, + errorMessage: (!validFields && + (controller[index].text == + '')) + ? localizations.translate(i18 + .common + .corecommonRequired) + : null, + initialSelection: + controller[index].text == + 'true' + ? [true] + : controller[index] + .text == + 'false' + ? [false] + : [], + options: const [true, false], + onSelectionChanged: (curValue) { + if (curValue.isNotEmpty) { + context + .read() + .add( + ServiceChecklistEvent( + value: curValue + .toString(), + submitTriggered: + submitTriggered, + ), + ); + setState(() { + controller[index].value = + TextEditingValue( + text: curValue.first + .toString(), + ); + }); + } else { + controller[index].value = + const TextEditingValue( + text: '', + ); + } + }, + ); + }, + ), + ], + ), + ), + ], + ]); + }), + const SizedBox( + height: 15, + ), + ]), + ), + ), + ], + ); + }, + ); + }, + ), + ), + ); + } + + List getNextQuestions( + String parentCode, + List checklistItems, + ) { + final childCodePrefix = '$parentCode.'; + final nextCheckLists = checklistItems.where((item) { + return item.code!.startsWith(childCodePrefix) && + item.code?.split('.').length == parentCode.split('.').length + 2; + }).toList(); + + return nextCheckLists; + } + + int countDots(String inputString) { + int dotCount = 0; + for (int i = 0; i < inputString.length; i++) { + if (inputString[i] == '.') { + dotCount++; + } + } + + return dotCount; + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary/beneficiary_details.dart b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_details.dart index 77abaa774..e0543da70 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/beneficiary_details.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_details.dart @@ -29,10 +29,10 @@ class BeneficiaryDetailsPage extends LocalizedStatefulWidget { }); @override - State createState() => _BeneficiaryDetailsPageState(); + State createState() => BeneficiaryDetailsPageState(); } -class _BeneficiaryDetailsPageState +class BeneficiaryDetailsPageState extends LocalizedState { @override void initState() { @@ -54,9 +54,9 @@ class _BeneficiaryDetailsPageState final projectBeneficiary = RegistrationDeliverySingleton().beneficiaryType != BeneficiaryType.individual - ? [householdMemberWrapper.projectBeneficiaries.first] + ? [householdMemberWrapper.projectBeneficiaries?.first] : householdMemberWrapper.projectBeneficiaries - .where( + ?.where( (element) => element.beneficiaryClientReferenceId == state.selectedIndividual?.clientReferenceId, @@ -68,7 +68,7 @@ class _BeneficiaryDetailsPageState final taskData = state.householdMemberWrapper.tasks ?.where((element) => element.projectBeneficiaryClientReferenceId == - projectBeneficiary.first.clientReferenceId) + projectBeneficiary?.first?.clientReferenceId) .toList(); final bloc = context.read(); final lastDose = taskData != null && taskData.isNotEmpty @@ -186,6 +186,7 @@ class _BeneficiaryDetailsPageState context, variant, state.selectedIndividual, + state.householdMemberWrapper.household ), barrierDismissible: true, primaryAction: @@ -263,7 +264,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper - .headOfHousehold.name?.givenName + .headOfHousehold?.name?.givenName : state.selectedIndividual?.name ?.givenName ?? '--', @@ -275,7 +276,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper - .headOfHousehold.identifiers + .headOfHousehold?.identifiers : state.selectedIndividual ?.identifiers; if (identifiers == null || @@ -295,7 +296,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper - .headOfHousehold.identifiers + .headOfHousehold?.identifiers : state.selectedIndividual ?.identifiers; if (identifiers == null || @@ -316,7 +317,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper - .headOfHousehold.dateOfBirth + .headOfHousehold?.dateOfBirth : state.selectedIndividual ?.dateOfBirth; if (dob == null || dob.isEmpty) { @@ -348,7 +349,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper.headOfHousehold - .gender?.name.sentenceCase + ?.gender?.name.sentenceCase : state.selectedIndividual?.gender?.name .sentenceCase ?? '--', @@ -358,7 +359,7 @@ class _BeneficiaryDetailsPageState .beneficiaryType != BeneficiaryType.individual ? householdMemberWrapper - .headOfHousehold.mobileNumber + .headOfHousehold?.mobileNumber : state.selectedIndividual ?.mobileNumber ?? '--', @@ -366,11 +367,13 @@ class _BeneficiaryDetailsPageState .deliverIntervention .dateOfRegistrationLabel): () { final date = projectBeneficiary - .first.dateOfRegistration; + ?.first?.dateOfRegistration; final registrationDate = DateTime.fromMillisecondsSinceEpoch( - date, + date ?? + DateTime.now() + .millisecondsSinceEpoch, ); return DateFormat('dd MMMM yyyy') diff --git a/packages/registration_delivery/lib/pages/beneficiary/beneficiary_wrapper.dart b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_wrapper.dart index 5e8e49c48..c8fe2c357 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/beneficiary_wrapper.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/beneficiary_wrapper.dart @@ -56,6 +56,9 @@ class BeneficiaryWrapperPage extends StatelessWidget { final referral = context.repository(context); + final serviceDefinationRepo = context.repository(context); + return MultiBlocProvider( providers: [ BlocProvider( @@ -64,6 +67,12 @@ class BeneficiaryWrapperPage extends StatelessWidget { serviceDataRepository: service, ), ), + BlocProvider( + create: (_) => ServiceDefinitionBloc( + const ServiceDefinitionEmptyState(), + serviceDefinitionDataRepository: serviceDefinition, + )..add(const ServiceDefinitionFetchEvent()), + ), BlocProvider( create: (_) => FacilityBloc( facilityDataRepository: facilityRepository, @@ -132,7 +141,7 @@ class BeneficiaryWrapperPage extends StatelessWidget { )..add(DeliverInterventionSearchEvent( taskSearch: TaskSearchModel( projectBeneficiaryClientReferenceId: houseHoldOverviewState - .householdMemberWrapper.projectBeneficiaries + .householdMemberWrapper.projectBeneficiaries?.where((element) => element.projectId == RegistrationDeliverySingleton().projectId) .map((e) => e.clientReferenceId) .toList(), ))), @@ -146,7 +155,7 @@ class BeneficiaryWrapperPage extends StatelessWidget { )..add(ReferralSearchEvent(ReferralSearchModel( projectBeneficiaryClientReferenceId: houseHoldOverviewState .householdMemberWrapper.projectBeneficiaries - .map((e) => e.clientReferenceId) + ?.map((e) => e.clientReferenceId) .toList(), ))), child: BlocProvider( diff --git a/packages/registration_delivery/lib/pages/beneficiary/deliver_intervention.dart b/packages/registration_delivery/lib/pages/beneficiary/deliver_intervention.dart index 59341ffba..d33b76454 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/deliver_intervention.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/deliver_intervention.dart @@ -3,22 +3,21 @@ import 'package:collection/collection.dart'; import 'package:digit_components/digit_components.dart'; import 'package:digit_components/widgets/atoms/digit_stepper.dart'; import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/models/entities/deliver_strategy_type.dart'; +import 'package:registration_delivery/registration_delivery.dart'; +import 'package:registration_delivery/router/registration_delivery_router.gm.dart'; import 'package:registration_delivery/utils/extensions/extensions.dart'; +import 'package:registration_delivery/utils/utils.dart'; -import '../../blocs/delivery_intervention/deliver_intervention.dart'; -import '../../blocs/household_overview/household_overview.dart'; import '../../models/entities/additional_fields_type.dart'; -import '../../models/entities/deliver_strategy_type.dart'; import '../../models/entities/status.dart'; -import '../../models/entities/task.dart'; -import '../../models/entities/task_resource.dart'; -import '../../router/registration_delivery_router.gm.dart'; import '../../utils/i18_key_constants.dart' as i18; -import '../../utils/utils.dart'; import '../../widgets/back_navigation_help_header.dart'; import '../../widgets/beneficiary/resource_beneficiary_card.dart'; import '../../widgets/component_wrapper/product_variant_bloc_wrapper.dart'; @@ -36,10 +35,10 @@ class DeliverInterventionPage extends LocalizedStatefulWidget { @override State createState() => - _DeliverInterventionPageState(); + DeliverInterventionPageState(); } -class _DeliverInterventionPageState +class DeliverInterventionPageState extends LocalizedState { // Constants for form control keys static const _resourceDeliveredKey = 'resourceDelivered'; @@ -48,6 +47,8 @@ class _DeliverInterventionPageState static const _doseAdministrationKey = 'doseAdministered'; static const _dateOfAdministrationKey = 'dateOfAdministration'; final clickedStatus = ValueNotifier(false); + bool? shouldSubmit = false; + // Variable to track dose administration status bool doseAdministered = false; @@ -57,6 +58,78 @@ class _DeliverInterventionPageState // Initialize the currentStep variable to keep track of the current step in a process. int currentStep = 0; + @override + void initState() { + context.read().add(const LoadLocationEvent()); + super.initState(); + } + + Future handleCapturedLocationState( + LocationState locationState, + BuildContext context, + DeliverInterventionState deliverInterventionState, + FormGroup form, + HouseholdMemberWrapper householdMember, + ProjectBeneficiaryModel projectBeneficiary) async { + final lat = locationState.latitude; + final long = locationState.longitude; + context.read().add( + DeliverInterventionSubmitEvent( + task: _getTaskModel( + context, + form: form, + oldTask: RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.household + ? deliverInterventionState.tasks?.last + : null, + projectBeneficiaryClientReferenceId: + projectBeneficiary.clientReferenceId, + dose: deliverInterventionState.dose, + cycle: deliverInterventionState.cycle, + deliveryStrategy: DeliverStrategyType.direct.toValue(), + address: householdMember.members?.first.address?.first, + latitude: lat, + longitude: long, + ), + isEditing: (deliverInterventionState.tasks ?? []).isNotEmpty && + RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.household + ? true + : false, + boundaryModel: RegistrationDeliverySingleton().boundary!, + navigateToSummary: true, + householdMemberWrapper: householdMember), + ); + context.router.push(DeliverySummaryRoute()); + } + + void handleLocationState( + LocationState locationState, + BuildContext context, + DeliverInterventionState deliverInterventionState, + FormGroup form, + HouseholdMemberWrapper householdMember, + ProjectBeneficiaryModel projectBeneficiary) { + if (context.mounted) { + DigitComponentsUtils().showLocationCapturingDialog( + context, + localizations.translate(i18.common.locationCapturing), + DigitSyncDialogType.inProgress); + + Future.delayed(const Duration(seconds: 2), () { + // After delay, hide the initial dialog + DigitComponentsUtils().hideLocationDialog(context); + handleCapturedLocationState( + locationState, + context, + deliverInterventionState, + form, + householdMember, + projectBeneficiary); + }); + } + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -71,40 +144,38 @@ class _DeliverInterventionPageState }); } - return BlocBuilder( - builder: (context, locationState) { - return ProductVariantBlocWrapper( - child: BlocBuilder( - builder: (context, state) { - final householdMemberWrapper = state.householdMemberWrapper; - - final projectBeneficiary = - RegistrationDeliverySingleton().beneficiaryType != - BeneficiaryType.individual - ? [householdMemberWrapper.projectBeneficiaries.first] - : householdMemberWrapper.projectBeneficiaries - .where( - (element) => - element.beneficiaryClientReferenceId == - state.selectedIndividual?.clientReferenceId, - ) - .toList(); - - return Scaffold( - body: state.loading - ? const Center(child: CircularProgressIndicator()) - : BlocBuilder( - builder: (context, deliveryInterventionState) { - List? productVariants = - RegistrationDeliverySingleton() - .selectedProject - ?.additionalDetails - ?.projectType - ?.cycles - ?.isNotEmpty == - true - ? (fetchProductVariant( + return ProductVariantBlocWrapper( + child: BlocBuilder( + builder: (context, state) { + final householdMemberWrapper = state.householdMemberWrapper; + + final projectBeneficiary = + RegistrationDeliverySingleton().beneficiaryType != + BeneficiaryType.individual + ? [householdMemberWrapper.projectBeneficiaries!.first] + : householdMemberWrapper.projectBeneficiaries + ?.where( + (element) => + element.beneficiaryClientReferenceId == + state.selectedIndividual?.clientReferenceId, + ) + .toList(); + + return Scaffold( + body: state.loading + ? const Center(child: CircularProgressIndicator()) + : BlocBuilder( + builder: (context, deliveryInterventionState) { + List? productVariants = + RegistrationDeliverySingleton() + .selectedProject + ?.additionalDetails + ?.projectType + ?.cycles + ?.isNotEmpty == + true + ? (fetchProductVariant( RegistrationDeliverySingleton() .selectedProject ?.additionalDetails @@ -116,564 +187,395 @@ class _DeliverInterventionPageState .deliveries?[ deliveryInterventionState.dose - 1], state.selectedIndividual, - )?.productVariants) - : RegistrationDeliverySingleton() - .selectedProject - ?.additionalDetails - ?.projectType - ?.resources - ?.map((r) => DeliveryProductVariant( - productVariantId: r.productVariantId)) - .toList(); - - final int numberOfDoses = - (RegistrationDeliverySingleton() - .projectType - ?.cycles - ?.isNotEmpty == - true) - ? (RegistrationDeliverySingleton() - .projectType - ?.cycles?[ - deliveryInterventionState.cycle - - 1] - .deliveries - ?.length) ?? - 0 - : 0; - - final steps = generateSteps(numberOfDoses); - if ((productVariants ?? []).isEmpty) { - DigitToast.show( - context, - options: DigitToastOptions( - localizations.translate( - i18.deliverIntervention - .checkForProductVariantsConfig, - ), - true, - theme, + state.householdMemberWrapper.household) + ?.productVariants) + : RegistrationDeliverySingleton() + .selectedProject + ?.additionalDetails + ?.projectType + ?.resources + ?.map((r) => DeliveryProductVariant( + productVariantId: r.productVariantId)) + .toList(); + + final int numberOfDoses = (RegistrationDeliverySingleton() + .projectType + ?.cycles + ?.isNotEmpty == + true) + ? (RegistrationDeliverySingleton() + .projectType + ?.cycles?[deliveryInterventionState.cycle - 1] + .deliveries + ?.length) ?? + 0 + : 0; + + final steps = generateSteps(numberOfDoses); + if ((productVariants ?? []).isEmpty && context.mounted) { + SchedulerBinding.instance.addPostFrameCallback((_) { + DigitToast.show( + context, + options: DigitToastOptions( + localizations.translate( + i18.deliverIntervention + .checkForProductVariantsConfig, ), - ); - } - - return BlocBuilder( - builder: (context, productState) { - return productState.maybeWhen( - orElse: () => const Offstage(), - fetched: (productVariantsValue) { - final variant = productState.whenOrNull( - fetched: (productVariants) { - return productVariants; - }, - ); + true, + theme, + ), + ); + }); + } - return ReactiveFormBuilder( - form: () => buildForm( - context, - productVariants, - variant, - ), - builder: (context, form, child) { - return ScrollableContent( - enableFixedButton: true, - footer: BlocBuilder< - DeliverInterventionBloc, - DeliverInterventionState>( - builder: (context, state) { - return DigitCard( - margin: - const EdgeInsets.fromLTRB( - 0, kPadding, 0, 0), - padding: - const EdgeInsets.fromLTRB( - kPadding, - 0, - kPadding, - 0), - child: ValueListenableBuilder( - valueListenable: - clickedStatus, - builder: (context, - bool isClicked, _) { - return DigitElevatedButton( - onPressed: isClicked - ? null - : () async { - final deliveredProducts = ((form - .control( - _resourceDeliveredKey, - ) as FormArray) + return BlocBuilder( + builder: (context, productState) { + return productState.maybeWhen( + orElse: () => const Offstage(), + fetched: (productVariantsValue) { + final variant = productState.whenOrNull( + fetched: (productVariants) { + return productVariants; + }, + ); + + return ReactiveFormBuilder( + form: () => buildForm( + context, + productVariants, + variant, + ), + builder: (context, form, child) { + return ScrollableContent( + enableFixedButton: true, + footer: BlocBuilder( + builder: (context, state) { + return DigitCard( + margin: const EdgeInsets.fromLTRB( + 0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB( + kPadding, 0, kPadding, 0), + child: ValueListenableBuilder( + valueListenable: clickedStatus, + builder: + (context, bool isClicked, _) { + return BlocBuilder( + builder: + (context, locationState) { + return DigitElevatedButton( + onPressed: isClicked + ? null + : () async { + final deliveredProducts = + ((form.control( + _resourceDeliveredKey, + ) as FormArray) .value as List< ProductVariantModel?>); - if (hasDuplicatesOrEmptyResource( - deliveredProducts)) { - await DigitToast - .show( - context, - options: - DigitToastOptions( - localizations.translate(i18 + if (hasDuplicatesOrEmptyResource( + deliveredProducts)) { + await DigitToast + .show( + context, + options: + DigitToastOptions( + localizations + .translate(i18 .deliverIntervention .resourceDeliveredValidation), - true, - theme, - ), - ); - } else if ((((form - .control( - _quantityDistributedKey, - ) as FormArray) - .value) ?? - []) - .any((e) => e == 0)) { - await DigitToast - .show( - context, - options: - DigitToastOptions( - localizations.translate(i18 + true, + theme, + ), + ); + } else if ((((form + .control( + _quantityDistributedKey, + ) as FormArray) + .value) ?? + []) + .any((e) => e == 0)) { + await DigitToast + .show( + context, + options: + DigitToastOptions( + localizations + .translate(i18 .deliverIntervention .resourceCannotBeZero), - true, - theme, - ), - ); - } else { - final lat = - locationState - .latitude; - final long = - locationState - .longitude; - final shouldSubmit = - await DigitDialog - .show< - bool>( - context, - options: - DigitDialogOptions( - titleText: - localizations - .translate( - i18.deliverIntervention - .dialogTitle, - ), - contentText: - localizations - .translate( - i18.deliverIntervention - .dialogContent, - ), - primaryAction: - DigitDialogActions( - label: localizations - .translate( - i18.common - .coreCommonSubmit, - ), - action: - (ctx) { - clickedStatus.value = - true; - Navigator - .of( - context, - rootNavigator: - true, - ).pop( - true); - }, - ), - secondaryAction: - DigitDialogActions( - label: localizations - .translate( - i18.common - .coreCommonCancel, - ), - action: (context) => - Navigator - .of( - context, - rootNavigator: - true, - ).pop(false), - ), - ), - ); - - if (shouldSubmit ?? - false) { - if (context - .mounted) { - context - .read< - DeliverInterventionBloc>() - .add( - DeliverInterventionSubmitEvent( - task: - _getTaskModel( - context, - form: form, - oldTask: null, - projectBeneficiaryClientReferenceId: projectBeneficiary.first.clientReferenceId, - dose: deliveryInterventionState.dose, - cycle: deliveryInterventionState.cycle, - deliveryStrategy: DeliverStrategyType.direct.toValue(), - address: householdMemberWrapper.members.first.address?.first, - latitude: lat, - longitude: long, - ), - isEditing: - false, - boundaryModel: - RegistrationDeliverySingleton().boundary!, - ), - ); - - if (state - .futureDeliveries != - null && - state - .futureDeliveries! - .isNotEmpty && - RegistrationDeliverySingleton().projectType?.cycles?.isNotEmpty == - true) { - context - .router - .popUntilRouteWithName( - BeneficiaryWrapperRoute - .name, - ); - context - .router - .push( - SplashAcknowledgementRoute( - enableBackToSearch: - false, - ), - ); - } else { - final reloadState = - context - .read(); - - Future - .delayed( - const Duration( - milliseconds: - 1000, - ), - () { - reloadState - .add( - HouseholdOverviewReloadEvent( - projectId: RegistrationDeliverySingleton().projectId!, - projectBeneficiaryType: RegistrationDeliverySingleton().beneficiaryType!, - ), - ); - }, - ).then( - (value) { - context - .router - .popAndPush( - HouseholdAcknowledgementRoute( - enableViewHousehold: true, - ), - ); - }, - ); - } - } - } - } - }, - child: Center( - child: Text( - localizations - .translate( - i18.common - .coreCommonSubmit, - ), - ), + true, + theme, + ), + ); + } else { + context + .read< + LocationBloc>() + .add( + const LoadLocationEvent()); + handleLocationState( + locationState, + context, + deliveryInterventionState, + form, + householdMemberWrapper, + projectBeneficiary! + .first); + } + }, + child: Center( + child: Text( + localizations.translate( + i18.common + .coreCommonSubmit, ), - ); - }, - ), - ); + ), + ), + ); + }); }, ), - header: const Column(children: [ - BackNavigationHelpHeaderWidget( - showHelp: false, + ); + }, + ), + header: const Column(children: [ + BackNavigationHelpHeaderWidget( + showHelp: false, + ), + ]), + children: [ + Column( + children: [ + DigitCard( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + localizations.translate( + i18.deliverIntervention + .deliverInterventionLabel, + ), + style: theme + .textTheme.displayMedium, + ), + if (RegistrationDeliverySingleton() + .beneficiaryType == + BeneficiaryType.individual) + DigitTextFormField( + readOnly: true, + formControlName: + _doseAdministrationKey, + keyboardType: + TextInputType.number, + label: localizations + .translate(i18 + .deliverIntervention + .currentCycle), + ), + if (numberOfDoses > 1) + DigitStepper( + activeStep: + deliveryInterventionState + .dose - + 1, + stepRadius: 12.5, + steps: steps, + maxStepReached: 3, + lineLength: (MediaQuery.of( + context) + .size + .width - + 12.5 * + 2 * + steps.length - + 50) / + (steps.length - 1), + ), + DigitDateFormPicker( + isEnabled: false, + formControlName: + _dateOfAdministrationKey, + label: + localizations.translate( + i18.householdDetails + .dateOfRegistrationLabel, + ), + confirmText: + localizations.translate( + i18.common.coreCommonOk, + ), + cancelText: + localizations.translate( + i18.common.coreCommonCancel, + ), + isRequired: false, + padding: + const EdgeInsets.only( + top: kPadding, + ), + ), + ], ), - ]), - children: [ - Column( + ), + DigitCard( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, children: [ - DigitCard( - child: Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - mainAxisSize: - MainAxisSize.min, - children: [ - Text( - localizations.translate( - i18.deliverIntervention - .deliverInterventionLabel, - ), - style: theme.textTheme - .displayMedium, - ), - if (RegistrationDeliverySingleton() - .beneficiaryType == - BeneficiaryType - .individual) - DigitTextFormField( - readOnly: true, - formControlName: - _doseAdministrationKey, - keyboardType: - TextInputType - .number, - label: localizations - .translate(i18 - .deliverIntervention - .currentCycle), - ), - DigitStepper( - activeStep: - deliveryInterventionState - .dose - - 1, - stepRadius: 12.5, - steps: steps, - maxStepReached: 3, - lineLength: (MediaQuery.of( - context) - .size - .width - - 12.5 * - 2 * - steps - .length - - 50) / - (steps.length - 1), - ), - DigitDateFormPicker( - isEnabled: false, - formControlName: - _dateOfAdministrationKey, - label: localizations - .translate( - i18.householdDetails - .dateOfRegistrationLabel, - ), - confirmText: - localizations - .translate( - i18.common - .coreCommonOk, - ), - cancelText: - localizations - .translate( - i18.common - .coreCommonCancel, - ), - isRequired: false, - padding: - const EdgeInsets - .only( - top: kPadding, - ), - ), - ], + Text( + localizations.translate( + i18.deliverIntervention + .deliverInterventionResourceLabel, ), + style: theme + .textTheme.headlineLarge, ), - DigitCard( - child: Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - mainAxisSize: - MainAxisSize.min, - children: [ - Text( - localizations.translate( - i18.deliverIntervention - .deliverInterventionResourceLabel, - ), - style: theme.textTheme - .headlineLarge, - ), - ..._controllers.map((e) => - ResourceBeneficiaryCard( - form: form, - cardIndex: - _controllers - .indexOf(e), - totalItems: + ..._controllers.map((e) => + ResourceBeneficiaryCard( + form: form, + cardIndex: _controllers + .indexOf(e), + totalItems: + _controllers.length, + onDelete: (index) { + (form.control( + _resourceDeliveredKey, + ) as FormArray) + .removeAt( + index, + ); + (form.control( + _quantityDistributedKey, + ) as FormArray) + .removeAt( + index, + ); + _controllers.removeAt( + index, + ); + setState(() { + _controllers; + }); + }, + )), + Center( + child: DigitIconButton( + onPressed: ((form.control(_resourceDeliveredKey) + as FormArray) + .value ?? + []) + .length < + (productVariants ?? + []) + .length + ? () async { + addController(form); + setState(() { + _controllers.add( _controllers .length, - onDelete: (index) { - (form.control( - _resourceDeliveredKey, - ) as FormArray) - .removeAt( - index, - ); - (form.control( - _quantityDistributedKey, - ) as FormArray) - .removeAt( - index, - ); - _controllers - .removeAt( - index, ); - setState(() { - _controllers; - }); - }, - )), - Center( - child: DigitIconButton( - onPressed: ((form.control(_resourceDeliveredKey) as FormArray) - .value ?? - []) - .length < - (productVariants ?? - []) - .length - ? () async { - addController( - form); - setState(() { - _controllers - .add( - _controllers - .length, - ); - }); - } - : null, - icon: - Icons.add_circle, - iconColor: ((form.control(_resourceDeliveredKey) as FormArray) - .value ?? - []) - .length < - (productVariants ?? - []) - .length - ? theme - .colorScheme - .secondary - : theme - .colorScheme - .outline, - iconTextColor: ((form.control(_resourceDeliveredKey) as FormArray) - .value ?? - []) - .length < - (productVariants ?? - []) - .length - ? theme - .colorScheme - .secondary - : theme - .colorScheme - .outline, - iconText: - localizations - .translate( - i18.deliverIntervention - .resourceAddBeneficiary, - ), - ), - ), - ], + }); + } + : null, + icon: Icons.add_circle, + iconColor: ((form.control(_resourceDeliveredKey) + as FormArray) + .value ?? + []) + .length < + (productVariants ?? + []) + .length + ? theme.colorScheme + .secondary + : theme.colorScheme + .outline, + iconTextColor: ((form.control(_resourceDeliveredKey) + as FormArray) + .value ?? + []) + .length < + (productVariants ?? + []) + .length + ? theme.colorScheme + .secondary + : theme.colorScheme + .outline, + iconText: + localizations.translate( + i18.deliverIntervention + .resourceAddBeneficiary, + ), ), ), - DigitCard( - child: Column( - crossAxisAlignment: - CrossAxisAlignment - .start, - mainAxisSize: - MainAxisSize.min, - children: [ - Text( - localizations.translate( - i18.deliverIntervention - .deliveryCommentLabel, - ), - style: theme.textTheme - .headlineLarge, - ), - DigitReactiveSearchDropdown< - String>( - label: localizations - .translate( - i18.deliverIntervention - .deliveryCommentLabel, - ), - form: form, - menuItems: - RegistrationDeliverySingleton() - .deliveryCommentOptions! - .map((e) { - return localizations - .translate(e); - }).toList() - ..sort((a, b) => - a.compareTo( - b)), - formControlName: - _deliveryCommentKey, - valueMapper: (value) => - value, - emptyText: localizations - .translate(i18 - .common - .noMatchFound), - ) - ], + ], + ), + ), + DigitCard( + child: Column( + crossAxisAlignment: + CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + localizations.translate( + i18.deliverIntervention + .deliveryCommentHeading, ), + style: theme + .textTheme.headlineLarge, ), + DigitReactiveSearchDropdown< + String>( + label: + localizations.translate( + i18.deliverIntervention + .deliveryCommentLabel, + ), + form: form, + menuItems: + RegistrationDeliverySingleton() + .deliveryCommentOptions! + .map((e) { + return localizations + .translate(e); + }).toList() + ..sort((a, b) => + a.compareTo(b)), + formControlName: + _deliveryCommentKey, + valueMapper: (value) => value, + emptyText: localizations + .translate(i18 + .common.noMatchFound), + ) ], ), - ], - ); - }, - ); - }, - empty: () => Center( - child: Text( - localizations.translate( - i18.deliverIntervention - .checkForProductVariantsConfig, ), - ), - )); + ], + ), + ], + ); + }, + ); }, ); }, - ), - ); - }, - ), - ); - }, + ); + }, + ), + ); + }, + ), ); } @@ -696,8 +598,7 @@ class _DeliverInterventionPageState } } bool hasDuplicateProductIdOrNoProductId = - groupedVariants.values.any((variants) => variants.length > 1) || - deliveredProducts.any((ele) => ele?.productId == null); + deliveredProducts.any((ele) => ele?.productId == null); return hasDuplicateProductIdOrNoProductId; } @@ -724,6 +625,9 @@ class _DeliverInterventionPageState task ??= TaskModel( projectBeneficiaryClientReferenceId: projectBeneficiaryClientReferenceId, clientReferenceId: clientReferenceId, + address: address?.copyWith( + relatedClientReferenceId: clientReferenceId, + ), tenantId: RegistrationDeliverySingleton().tenantId, rowVersion: 1, auditDetails: AuditDetails( @@ -774,6 +678,10 @@ class _DeliverInterventionPageState additionalFields: TaskAdditionalFields( version: task.additionalFields?.version ?? 1, fields: [ + AdditionalField( + RegistrationDeliveryEnums.name.toValue(), + RegistrationDeliverySingleton().loggedInUser?.name, + ), AdditionalField( AdditionalFieldsType.dateOfDelivery.toValue(), DateTime.now().millisecondsSinceEpoch.toString(), @@ -829,11 +737,36 @@ class _DeliverInterventionPageState List? variants, ) { final bloc = context.read().state; + final overViewbloc = context.read().state; + _controllers.forEachIndexed((index, element) { + _controllers.removeAt(index); + }); // Add controllers for each product variant to the _controllers list. + if (_controllers.isEmpty) { + final int r = RegistrationDeliverySingleton() + .selectedProject + ?.additionalDetails + ?.projectType + ?.cycles == + null + ? 1 + : fetchProductVariant( + RegistrationDeliverySingleton() + .selectedProject + ?.additionalDetails + ?.projectType + ?.cycles![bloc.cycle - 1] + .deliveries?[bloc.dose - 1], + overViewbloc.selectedIndividual, + overViewbloc.householdMemberWrapper.household)! + .productVariants + ?.length ?? + 0; - _controllers - .addAll(productVariants!.map((e) => productVariants.indexOf(e))); + _controllers.addAll(List.generate(r, (index) => index) + .mapIndexed((index, element) => index)); + } return fb.group({ _doseAdministrationKey: FormControl( @@ -866,16 +799,18 @@ class _DeliverInterventionPageState _resourceDeliveredKey: FormArray( [ ..._controllers.map((e) => FormControl( - value: variants != null && - _controllers.indexOf(e) < variants.length - ? variants.firstWhereOrNull( - (element) => - element.id == - productVariants - .elementAt(_controllers.indexOf(e)) - .productVariantId, - ) - : null, + value: variants != null && variants.length < _controllers.length + ? variants.last + : (variants != null && + _controllers.indexOf(e) < variants.length + ? variants.firstWhereOrNull( + (element) => + element.id == + productVariants + ?.elementAt(_controllers.indexOf(e)) + .productVariantId, + ) + : null), )), ], ), diff --git a/packages/registration_delivery/lib/pages/beneficiary/delivery_summary_page.dart b/packages/registration_delivery/lib/pages/beneficiary/delivery_summary_page.dart new file mode 100644 index 000000000..3d06173d8 --- /dev/null +++ b/packages/registration_delivery/lib/pages/beneficiary/delivery_summary_page.dart @@ -0,0 +1,370 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/details_card.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:recase/recase.dart'; +import 'package:registration_delivery/blocs/delivery_intervention/deliver_intervention.dart'; +import 'package:registration_delivery/blocs/household_overview/household_overview.dart'; +import 'package:registration_delivery/models/entities/additional_fields_type.dart'; +import 'package:registration_delivery/models/entities/status.dart'; +import 'package:registration_delivery/router/registration_delivery_router.gm.dart'; +import 'package:registration_delivery/utils/constants.dart'; +import 'package:registration_delivery/utils/utils.dart'; +import 'package:registration_delivery/widgets/back_navigation_help_header.dart'; +import 'package:registration_delivery/widgets/component_wrapper/product_variant_bloc_wrapper.dart'; +import 'package:registration_delivery/widgets/showcase/showcase_button.dart'; + +import '../../../widgets/localized.dart'; +import '../../utils/i18_key_constants.dart' as i18; + +@RoutePage() +class DeliverySummaryPage extends LocalizedStatefulWidget { + const DeliverySummaryPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => DeliverySummaryPageState(); +} + +class DeliverySummaryPageState extends LocalizedState { + final clickedStatus = ValueNotifier(false); + + String getLocalizedMessage(String code) { + return localizations.translate(code); + } + + @override + Widget build(BuildContext context) { + return ProductVariantBlocWrapper( + child: Scaffold( + body: BlocConsumer( + listener: (context, deliverState) { + final router = context.router; + }, + builder: (context, deliverState) { + return ScrollableContent( + enableFixedButton: true, + header: Column(children: [ + const BackNavigationHelpHeaderWidget( + showHelp: false, + showcaseButton: ShowcaseButton(), + ), + Padding( + padding: + const EdgeInsets.only(bottom: kPadding, left: kPadding), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + localizations.translate( + i18.common.coreCommonSummaryDetails, + ), + style: DigitTheme + .instance.mobileTheme.textTheme.displayMedium, + ), + ), + ), + ]), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: ValueListenableBuilder( + valueListenable: clickedStatus, + builder: (context, bool isClicked, _) { + return DigitElevatedButton( + onPressed: isClicked + ? null + : () async { + final submit = await DigitDialog.show( + context, + options: DigitDialogOptions( + titleText: localizations.translate( + i18.deliverIntervention.dialogTitle), + contentText: localizations.translate( + i18.deliverIntervention.dialogContent), + primaryAction: DigitDialogActions( + label: localizations + .translate(i18.common.coreCommonSubmit), + action: (ctx) { + clickedStatus.value = true; + Navigator.of(context, rootNavigator: true) + .pop(true); + }, + ), + secondaryAction: DigitDialogActions( + label: localizations + .translate(i18.common.coreCommonCancel), + action: (context) => Navigator.of(context, + rootNavigator: true) + .pop(false), + ), + ), + ); + if (submit ?? false) { + if (context.mounted) { + context.read().add( + DeliverInterventionSubmitEvent( + task: deliverState.oldTask!, + isEditing: (deliverState.tasks ?? []) + .isNotEmpty && + RegistrationDeliverySingleton() + .beneficiaryType == + BeneficiaryType.household + ? true + : false, + boundaryModel: + RegistrationDeliverySingleton() + .boundary!, + ), + ); + + if (deliverState.futureDeliveries != null && + deliverState + .futureDeliveries!.isNotEmpty && + RegistrationDeliverySingleton() + .projectType + ?.cycles + ?.isNotEmpty == + true) { + context.router.popUntilRouteWithName( + BeneficiaryWrapperRoute.name, + ); + context.router.push( + SplashAcknowledgementRoute( + enableBackToSearch: false, + ), + ); + } else { + final reloadState = + context.read(); + + reloadState.add( + HouseholdOverviewReloadEvent( + projectId: + RegistrationDeliverySingleton() + .projectId!, + projectBeneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType!, + ), + ); + context.router.popAndPush( + HouseholdAcknowledgementRoute( + enableViewHousehold: true, + ), + ); + } + } + } + }, + child: Center( + child: Text( + localizations.translate(i18.common.coreCommonNext), + ), + ), + ); + }, + ), + ), + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + DigitCard( + child: LabelValueList( + heading: localizations.translate(i18 + .householdLocation.householdLocationLabelText), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.householdLocation.villageLabel), + value: deliverState.householdMemberWrapper + ?.household?.address?.locality?.code + .split('_') + .last + .titleCase ?? + localizations + .translate(i18.common.coreCommonNA), + isInline: true), + LabelValuePair( + label: localizations.translate( + i18.householdLocation.landmarkFormLabel), + value: deliverState.householdMemberWrapper + ?.household?.address?.landmark ?? + localizations + .translate(i18.common.coreCommonNA), + isInline: true), + ]), + ), + DigitCard( + child: LabelValueList( + heading: localizations.translate( + i18.householdDetails.householdDetailsLabel), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.beneficiaryDetails.totalMembers), + value: deliverState.householdMemberWrapper + ?.household?.memberCount + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate(i18 + .householdDetails + .noOfPregnantWomenCountLabel), + value: deliverState.householdMemberWrapper + ?.household?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.pregnantWomen + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate(i18 + .householdDetails + .noOfChildrenBelow5YearsLabel), + value: deliverState.householdMemberWrapper + ?.household?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.children + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + ]), + ), + DigitCard( + child: LabelValueList( + heading: localizations.translate( + i18.householdDetails.houseDetailsLabel), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.householdDetails.noOfRoomsLabel), + value: deliverState.householdMemberWrapper + ?.household?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.noOfRooms + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate( + i18.householdDetails.typeOfStructure), + value: (deliverState + .householdMemberWrapper + ?.household + ?.additionalFields + ?.fields + .where((h) => + h.key == + AdditionalFieldsType + .houseStructureTypes + .toValue()) + .firstOrNull + ?.value ?? + []) + .toString() + .split('|') + .map((item) => getLocalizedMessage(item)) + .toList() + .join(', '), + isInline: true), + ]), + ), + BlocBuilder( + builder: (context, productState) { + final variants = productState.whenOrNull( + fetched: (productVariants) { + final resourcesDelivered = deliverState + .oldTask?.resources + ?.map((e) => TaskResourceInfo( + productVariants + .where((p) => + p.id == e.productVariantId) + .firstOrNull + ?.sku ?? + productVariants + .where((p) => + p.id == e.productVariantId) + .firstOrNull + ?.variation ?? + i18.common.coreCommonNA, + e.quantity ?? '0')) + .toList(); + return resourcesDelivered; + }, + ); + return DigitCard( + child: LabelValueList( + heading: localizations.translate( + '${RegistrationDeliverySingleton().selectedProject?.name.toUpperCase()}_${i18.deliverIntervention.deliveryDetailsLabel}_${deliverState.oldTask?.status}'), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate(deliverState + .oldTask?.status == + Status.administeredFailed + .toValue() || + deliverState.oldTask?.status == + Status.beneficiaryRefused + .toValue() + ? i18.deliverIntervention + .reasonForRefusalLabel + : '${RegistrationDeliverySingleton().selectedProject?.name.toUpperCase()}_${i18.deliverIntervention.typeOfResourceUsed}'), + value: deliverState.oldTask?.status == + Status.administeredFailed + .toValue() || + deliverState.oldTask?.status == + Status.beneficiaryRefused + .toValue() + ? getLocalizedMessage(deliverState + .oldTask?.additionalFields?.fields + .where( + (d) => + d.key == + AdditionalFieldsType + .reasonOfRefusal + .toValue(), + ) + .firstOrNull + ?.value ?? + i18.common.coreCommonNA) + : variants + ?.map((e) => + '${getLocalizedMessage(e.productName)} : ${e.quantityDelivered}') + .toList() + .join('\n') ?? + localizations.translate( + i18.common.coreCommonNA), + ), + ]), + ); + }), + ], + ), + ) + ]); + }, + )), + ); + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary/dose_administered.dart b/packages/registration_delivery/lib/pages/beneficiary/dose_administered.dart index 5059661ff..74cb1f27a 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/dose_administered.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/dose_administered.dart @@ -37,10 +37,10 @@ class DoseAdministeredPage extends LocalizedStatefulWidget { }); @override - State createState() => _DoseAdministeredPageState(); + State createState() => DoseAdministeredPageState(); } -class _DoseAdministeredPageState extends LocalizedState { +class DoseAdministeredPageState extends LocalizedState { static const _doseAdministeredKey = 'doseAdministered'; bool doseAdministered = false; bool formSubmitted = false; @@ -108,9 +108,9 @@ class _DoseAdministeredPageState extends LocalizedState { } form.markAllAsTouched(); - if (!form.valid) + if (!form.valid) { return; - else { + } else { final doseAdministered = form .control(_doseAdministeredKey) .value as KeyValue; @@ -170,9 +170,12 @@ class _DoseAdministeredPageState extends LocalizedState { .millisecondsSinceEpoch(), ), resources: fetchProductVariant( - e, - overViewBloc.selectedIndividual, - ) + e, + overViewBloc + .selectedIndividual, + overViewBloc + .householdMemberWrapper + .household) ?.productVariants ?.map((variant) => TaskResourceModel( @@ -364,9 +367,10 @@ class _DoseAdministeredPageState extends LocalizedState { deliveryState.dose + 1; List skus = fetchProductVariant( - e, - overViewBloc.selectedIndividual, - )! + e, + overViewBloc.selectedIndividual, + overViewBloc.householdMemberWrapper + .household)! .productVariants! .map((ele) { final pv = variant!.firstWhere( @@ -416,12 +420,16 @@ class _DoseAdministeredPageState extends LocalizedState { localizations.translate( i18.beneficiaryDetails .beneficiaryAge, - ): localizations - .translate(fetchProductVariant( - deliveryState - .futureDeliveries?.first, - overViewBloc.selectedIndividual, - )! + ): localizations.translate( + fetchProductVariant( + deliveryState + .futureDeliveries + ?.first, + overViewBloc + .selectedIndividual, + overViewBloc + .householdMemberWrapper + .household)! .condition!), }, ), diff --git a/packages/registration_delivery/lib/pages/beneficiary/household_overview.dart b/packages/registration_delivery/lib/pages/beneficiary/household_overview.dart index e707a2690..cae3e78fb 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/household_overview.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/household_overview.dart @@ -11,6 +11,8 @@ import '../../blocs/delivery_intervention/deliver_intervention.dart'; import '../../blocs/household_overview/household_overview.dart'; import '../../blocs/search_households/search_bloc_common_wrapper.dart'; import '../../blocs/search_households/search_households.dart'; +import '../../models/entities/household.dart'; +import '../../models/entities/registration_delivery_enums.dart'; import '../../models/entities/status.dart'; import '../../router/registration_delivery_router.gm.dart'; import '../../utils/i18_key_constants.dart' as i18; @@ -61,89 +63,147 @@ class _HouseholdOverviewPageState return Scaffold( body: state.loading ? const Center(child: CircularProgressIndicator()) - : BlocBuilder( - builder: (ctx, state) { - if (state.loading) { - return const Center( - child: CircularProgressIndicator(), - ); - } - - return ScrollableContent( - header: BackNavigationHelpHeaderWidget( - handleBack: () { - context - .read() - .searchHouseholdsBloc - .add(const SearchHouseholdsClearEvent()); - }, - ), - enableFixedButton: true, - footer: Offstage( - offstage: - beneficiaryType == BeneficiaryType.individual, - child: BlocBuilder( - builder: (ctx, state) => DigitCard( - margin: - const EdgeInsets.fromLTRB(0, kPadding, 0, 0), - padding: const EdgeInsets.fromLTRB( - kPadding, 0, kPadding, 0), - child: state.tasks?.first.status == - Status.administeredSuccess.toValue() - ? DigitOutLineButton( + : ScrollableContent( + header: BackNavigationHelpHeaderWidget( + handleBack: (){ + context.read().add(const SearchHouseholdsEvent.clear()); + }, + ), + enableFixedButton: true, + footer: Offstage( + offstage: beneficiaryType == BeneficiaryType.individual, + child: BlocBuilder( + builder: (context, serviceDefinitionState) => + BlocBuilder( + builder: (ctx, deliverInterventionState) => DigitCard( + margin: + const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB( + kPadding, 0, kPadding, 0), + child: state.householdMemberWrapper.tasks?.lastOrNull?.status == + Status.administeredSuccess.toValue() + ? Padding( + padding: const EdgeInsets.symmetric( + vertical: kPadding), + child: DigitOutLineButton( label: localizations.translate( i18.memberCard .deliverDetailsUpdateLabel, ), - onPressed: () async { - await context.router - .push(DeliverInterventionRoute()); + onPressed: state.householdMemberWrapper.tasks?.lastOrNull?.status == Status.administeredSuccess.toValue() ? null :() { + serviceDefinitionState.when( + empty: () {}, + isloading: () {}, + serviceDefinitionFetch: + (value, model) { + if (value + .where((element) => element + .code + .toString() + .contains( + '${RegistrationDeliverySingleton().selectedProject?.name}.${RegistrationDeliveryEnums.iec.toValue()}')) + .toList() + .isEmpty) { + context.router.push( + DeliverInterventionRoute(), + ); + } else { + navigateToChecklist(ctx); + } + }); }, - ) - : DigitElevatedButton( - onPressed: () async { - final bloc = - ctx.read(); + ), + ) + : DigitElevatedButton( + onPressed: (state.householdMemberWrapper + .projectBeneficiaries ?? + []) + .isEmpty || + state.householdMemberWrapper.tasks + ?.lastOrNull?.status == + Status.closeHousehold.toValue() + ? null + : () async { + final bloc = ctx + .read(); - final projectId = - RegistrationDeliverySingleton() - .projectId!; + final projectId = + RegistrationDeliverySingleton() + .projectId!; - bloc.add( - HouseholdOverviewReloadEvent( - projectId: projectId, - projectBeneficiaryType: - beneficiaryType, - ), - ); + bloc.add( + HouseholdOverviewReloadEvent( + projectId: projectId, + projectBeneficiaryType: + beneficiaryType, + ), + ); - await context.router - .push(DeliverInterventionRoute()); - }, - child: Center( - child: Text( - localizations.translate( - i18.householdOverView - .householdOverViewActionText, - ), + serviceDefinitionState.when( + empty: () {}, + isloading: () {}, + serviceDefinitionFetch: + (value, model) { + if (value + .where((element) => element + .code + .toString() + .contains( + '${RegistrationDeliverySingleton().selectedProject?.name}.${RegistrationDeliveryEnums.iec.toValue()}')) + .toList() + .isEmpty) { + context.router.push( + DeliverInterventionRoute(), + ); + } else { + navigateToChecklist(ctx); + } + }); + }, + child: Center( + child: Text( + localizations.translate( + i18.householdOverView + .householdOverViewActionText, ), ), ), - ), + ), ), ), - slivers: [ - SliverToBoxAdapter( - child: DigitCard( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.max, - children: [ - Align( - alignment: Alignment.centerLeft, - child: DigitIconButton( - onPressed: () => DigitActionDialog.show( + ), + ), + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.max, + children: [ + if ((state.householdMemberWrapper + .projectBeneficiaries ?? + []) + .isNotEmpty) + Align( + alignment: Alignment.centerLeft, + child: DigitIconButton( + onPressed: () { + final projectId = + RegistrationDeliverySingleton() + .projectId!; + + final bloc = + context.read(); + bloc.add( + HouseholdOverviewReloadEvent( + projectId: projectId, + projectBeneficiaryType: + beneficiaryType, + ), + ); + DigitActionDialog.show( context, widget: ActionCard( items: [ @@ -154,12 +214,6 @@ class _HouseholdOverviewPageState .householdOverViewEditLabel, ), action: () async { - final projectId = - RegistrationDeliverySingleton() - .projectId!; - - final bloc = context.read< - HouseholdOverviewBloc>(); Navigator.of( context, rootNavigator: true, @@ -170,29 +224,30 @@ class _HouseholdOverviewPageState .householdMemberWrapper; final timestamp = wrapper - .projectBeneficiaries - .first - .dateOfRegistration; - // [TODO ] + .headOfHousehold + ?.clientAuditDetails + ?.createdTime; final date = DateTime .fromMillisecondsSinceEpoch( - timestamp, + timestamp ?? + DateTime.now() + .millisecondsSinceEpoch, ); final address = - wrapper.household.address; + wrapper.household?.address; if (address == null) return; final projectBeneficiary = state .householdMemberWrapper .projectBeneficiaries - .firstWhereOrNull( + ?.firstWhereOrNull( (element) => element .beneficiaryClientReferenceId == wrapper.household - .clientReferenceId, + ?.clientReferenceId, ); await context.router.root.push( @@ -200,10 +255,13 @@ class _HouseholdOverviewPageState initialState: BeneficiaryRegistrationEditHouseholdState( addressModel: address, - individualModel: - wrapper.members, - householdModel: - wrapper.household, + individualModel: state + .householdMemberWrapper + .members ?? + [], + householdModel: state + .householdMemberWrapper + .household!, registrationDate: date, projectBeneficiaryModel: projectBeneficiary, @@ -213,552 +271,514 @@ class _HouseholdOverviewPageState ], ), ); - - bloc.add( - HouseholdOverviewReloadEvent( - projectId: projectId, - projectBeneficiaryType: - beneficiaryType, - ), - ); }, ), - ActionCardModel( - icon: Icons.delete, - label: localizations.translate(i18 - .householdOverView - .householdOverViewDeleteLabel), - action: () => DigitDialog.show( - context, - options: DigitDialogOptions( - titleText: localizations - .translate(i18 - .householdOverView - .householdOverViewActionCardTitle), - primaryAction: - DigitDialogActions( - label: localizations - .translate(i18 - .householdOverView - .householdOverViewPrimaryActionLabel), - action: (ctx) { - Navigator.of( - ctx, - rootNavigator: true, - ) - ..pop() - ..pop(); - context.router.push( - ReasonForDeletionRoute( - isHousholdDelete: - true, - ), - ); - }, - ), - secondaryAction: - DigitDialogActions( - label: localizations - .translate(i18 - .householdOverView - .householdOverViewSecondaryActionLabel), - action: (context) { - Navigator.of( - context, - rootNavigator: true, - ).pop(); - }, - ), - ), - ), - ), ], ), - ), - iconText: localizations.translate( - i18.householdOverView - .householdOverViewEditIconText, - ), - icon: Icons.edit, + ); + }, + iconText: localizations.translate( + i18.householdOverView + .householdOverViewEditIconText, ), + icon: Icons.edit, ), - BlocBuilder( - builder: (ctx, state) => Offstage( - offstage: beneficiaryType == - BeneficiaryType.individual, - child: Align( - alignment: Alignment.centerLeft, - child: DigitIconButton( - icon: state.tasks?.first.status == - Status.administeredSuccess - .toValue() - ? Icons.check_circle - : Icons.info_rounded, - iconText: localizations.translate( - state.tasks?.first.status == - Status.administeredSuccess - .toValue() - ? i18.householdOverView - .householdOverViewDeliveredIconLabel - : i18.householdOverView - .householdOverViewNotDeliveredIconLabel, - ), - iconTextColor: - state.tasks?.first.status == - Status.administeredSuccess - .toValue() - ? DigitTheme - .instance - .colorScheme - .onSurfaceVariant - : DigitTheme.instance - .colorScheme.error, - iconColor: - state.tasks?.first.status == - Status.administeredSuccess - .toValue() - ? DigitTheme - .instance - .colorScheme - .onSurfaceVariant - : DigitTheme.instance - .colorScheme.error, - ), + ), + // BlocBuilder( + // builder: (ctx, deliverInterventionState) => + // Offstage( + // offstage: beneficiaryType == + // BeneficiaryType.individual, + // child: Align( + // alignment: Alignment.centerLeft, + // child: DigitIconButton( + // icon: getStatusAttributes(state, + // deliverInterventionState)['icon'], + // iconText: localizations.translate( + // getStatusAttributes(state, + // deliverInterventionState)[ + // 'textLabel'], + // ), // [TODO: map task status accordingly based on projectBeneficiaries and tasks] + // iconTextColor: getStatusAttributes(state, + // deliverInterventionState)['color'], + // iconColor: getStatusAttributes(state, + // deliverInterventionState)['color'], + // ), + // ), + // ), + // ), + Padding( + padding: const EdgeInsets.only( + left: kPadding, + right: kPadding, + ), + child: Text( + localizations.translate(i18.householdOverView + .householdOverViewLabel), + style: theme.textTheme.displayMedium, + ), + ), + Padding( + padding: const EdgeInsets.only( + left: kPadding, + right: kPadding, + ), + child: BlocBuilder( + builder: (ctx, deliverInterventionState) { + return Column( + children: [ + DigitTableCard( + element: { + localizations.translate(i18 + .householdOverView + .householdOverViewHouseholdHeadNameLabel): + state + .householdMemberWrapper + .headOfHousehold + ?.name + ?.givenName ?? + localizations.translate( + i18.common.coreCommonNA), + localizations.translate( + i18.householdLocation + .administrationAreaFormLabel, + ): RegistrationDeliverySingleton() + .boundary + ?.name, + localizations.translate( + i18.deliverIntervention + .memberCountText, + ): state.householdMemberWrapper + .household?.memberCount, + localizations.translate(i18 + .beneficiaryDetails + .status): localizations.translate( + getStatusAttributes(state, + deliverInterventionState)[ + 'textLabel'], + ) + }, ), - ), - ), - Padding( - padding: const EdgeInsets.only( - left: kPadding, - right: kPadding, - ), - child: Text( - localizations.translate(i18 - .householdOverView - .householdOverViewLabel), - style: theme.textTheme.displayMedium, - ), - ), - Padding( - padding: const EdgeInsets.only( - left: kPadding, - right: kPadding, - ), - child: DigitTableCard( - element: { - localizations.translate(i18 - .householdOverView - .householdOverViewHouseholdHeadNameLabel): - state - .householdMemberWrapper - .headOfHousehold - .name - ?.givenName, - localizations.translate( - i18.householdLocation - .administrationAreaFormLabel, - ): RegistrationDeliverySingleton() - .boundary - ?.name, - localizations.translate( - i18.deliverIntervention - .memberCountText, - ): state.householdMemberWrapper - .household.memberCount, - }, - ), - ), - Column( - children: state - .householdMemberWrapper.members + ], + ); + }), + ), + Column( + children: + (state.householdMemberWrapper.members ?? []) .map( - (e) { - final isHead = state - .householdMemberWrapper - .headOfHousehold - .clientReferenceId == - e.clientReferenceId; - final projectBeneficiaryId = state + (e) { + final isHead = state .householdMemberWrapper - .projectBeneficiaries - .firstWhereOrNull((b) => - b.beneficiaryClientReferenceId == - e.clientReferenceId) - ?.clientReferenceId; - - final projectBeneficiary = - beneficiaryType != - BeneficiaryType.individual - ? [ - state - .householdMemberWrapper - .projectBeneficiaries - .first, - ] - : state.householdMemberWrapper - .projectBeneficiaries - .where( - (element) => - element - .beneficiaryClientReferenceId == - e.clientReferenceId, - ) - .toList(); - - final taskdata = projectBeneficiary - .isNotEmpty - ? state.householdMemberWrapper.tasks - ?.where((element) => - element - .projectBeneficiaryClientReferenceId == - projectBeneficiary.first - .clientReferenceId) - .toList() - : null; - final referralData = projectBeneficiary - .isNotEmpty - ? state.householdMemberWrapper - .referrals - ?.where((element) => - element - .projectBeneficiaryClientReferenceId == - projectBeneficiary.first - .clientReferenceId) - .toList() - : null; - final sideEffectData = taskdata != - null && - taskdata.isNotEmpty - ? state.householdMemberWrapper - .sideEffects - ?.where((element) => - element - .taskClientReferenceId == - taskdata - .last.clientReferenceId) - .toList() - : null; - final ageInYears = - DigitDateUtils.calculateAge( - DigitDateUtils - .getFormattedDateToDateTime( - e.dateOfBirth!, - ) ?? - DateTime.now(), - ).years; - final ageInMonths = - DigitDateUtils.calculateAge( - DigitDateUtils - .getFormattedDateToDateTime( - e.dateOfBirth!, - ) ?? - DateTime.now(), - ).months; - final currentCycle = - RegistrationDeliverySingleton() - .projectType - ?.cycles - ?.firstWhereOrNull( - (e) => - (e.startDate) < - DateTime.now() - .millisecondsSinceEpoch && - (e.endDate) > - DateTime.now() - .millisecondsSinceEpoch, - ); - - final isBeneficiaryRefused = - checkIfBeneficiaryRefused( - taskdata, - ); - final isBeneficiaryReferred = - checkIfBeneficiaryReferred( - referralData, - currentCycle, - ); - - return MemberCard( - isHead: isHead, - individual: e, - tasks: taskdata, - sideEffects: sideEffectData, - editMemberAction: () async { - final bloc = ctx - .read(); - - Navigator.of( - context, - rootNavigator: true, - ).pop(); - - final address = e.address; - if (address == null || - address.isEmpty) { - return; - } - - final projectId = - RegistrationDeliverySingleton() - .projectId!; - - await context.router.root.push( - BeneficiaryRegistrationWrapperRoute( - initialState: - BeneficiaryRegistrationEditIndividualState( - individualModel: e, - householdModel: state - .householdMemberWrapper - .household, - addressModel: address.first, - projectBeneficiaryModel: state + .headOfHousehold + ?.clientReferenceId == + e.clientReferenceId; + final projectBeneficiaryId = state + .householdMemberWrapper + .projectBeneficiaries + ?.firstWhereOrNull((b) => + b.beneficiaryClientReferenceId == + e.clientReferenceId) + ?.clientReferenceId; + + final projectBeneficiary = state + .householdMemberWrapper + .projectBeneficiaries + ?.where( + (element) => + element + .beneficiaryClientReferenceId == + (RegistrationDeliverySingleton() + .beneficiaryType == + BeneficiaryType.individual + ? e.clientReferenceId + : state .householdMemberWrapper - .projectBeneficiaries - .firstWhereOrNull( - (element) => - element - .beneficiaryClientReferenceId == - (RegistrationDeliverySingleton() - .beneficiaryType == - BeneficiaryType - .individual - ? e - .clientReferenceId - : state - .householdMemberWrapper - .household - .clientReferenceId), - ), - ), - children: [ - IndividualDetailsRoute( - isHeadOfHousehold: isHead, - ), - ], - ), - ); - - bloc.add( - HouseholdOverviewReloadEvent( - projectId: projectId, - projectBeneficiaryType: - beneficiaryType, - ), + .household + ?.clientReferenceId), + ) + .toList(); + + final taskData = (projectBeneficiary ?? []) + .isNotEmpty + ? state.householdMemberWrapper.tasks + ?.where((element) => + element + .projectBeneficiaryClientReferenceId == + projectBeneficiary + ?.first.clientReferenceId) + .toList() + : null; + final referralData = (projectBeneficiary ?? + []) + .isNotEmpty + ? state.householdMemberWrapper.referrals + ?.where((element) => + element + .projectBeneficiaryClientReferenceId == + projectBeneficiary + ?.first.clientReferenceId) + .toList() + : null; + final sideEffectData = taskData != null && + taskData.isNotEmpty + ? state + .householdMemberWrapper.sideEffects + ?.where((element) => + element.taskClientReferenceId == + taskData.lastOrNull?.clientReferenceId) + .toList() + : null; + final ageInYears = e.dateOfBirth != null + ? DigitDateUtils.calculateAge( + DigitDateUtils + .getFormattedDateToDateTime( + e.dateOfBirth!, + ) ?? + DateTime.now(), + ).years + : 0; + final ageInMonths = e.dateOfBirth != null + ? DigitDateUtils.calculateAge( + DigitDateUtils + .getFormattedDateToDateTime( + e.dateOfBirth!, + ) ?? + DateTime.now(), + ).months + : 0; + final currentCycle = + RegistrationDeliverySingleton() + .projectType + ?.cycles + ?.firstWhereOrNull( + (e) => + (e.startDate) < + DateTime.now() + .millisecondsSinceEpoch && + (e.endDate) > + DateTime.now() + .millisecondsSinceEpoch, ); - }, - setAsHeadAction: () { - ctx - .read() - .add( - HouseholdOverviewSetAsHeadEvent( - individualModel: e, - projectId: - RegistrationDeliverySingleton() - .projectId!, - householdModel: state - .householdMemberWrapper - .household, - projectBeneficiaryType: - beneficiaryType, - ), - ); - Navigator.of( - context, - rootNavigator: true, - ).pop(); - }, - deleteMemberAction: () { - DigitDialog.show( - context, - options: DigitDialogOptions( - titlePadding: - const EdgeInsets.fromLTRB( - kPadding * 2, - kPadding * 2, - kPadding * 2, - kPadding / 2, - ), - titleText: - localizations.translate(i18 - .householdOverView - .householdOverViewActionCardTitle), - primaryAction: - DigitDialogActions( - label: localizations.translate(i18 - .householdOverView - .householdOverViewPrimaryActionLabel), - action: (ctx) { - Navigator.of( - context, - rootNavigator: true, - ) - ..pop() - ..pop(); - context - .read< - HouseholdOverviewBloc>() - .add( - HouseholdOverviewEvent - .selectedIndividual( - individualModel: e, - ), - ); - - context.router - .popUntilRouteWithName( - SearchBeneficiaryRoute - .name, - ); - context.router.push( - ReasonForDeletionRoute( - isHousholdDelete: false, - ), - ); - }, - ), - secondaryAction: - DigitDialogActions( - label: localizations.translate(i18 - .householdOverView - .householdOverViewSecondaryActionLabel), - action: (context) { - Navigator.of( - context, - rootNavigator: true, - ).pop(); - }, - ), - ), - ); - }, - isNotEligible: - RegistrationDeliverySingleton() - .projectType - ?.cycles != - null - ? !checkEligibilityForAgeAndSideEffect( - DigitDOBAge( - years: ageInYears, - months: ageInMonths, - ), - RegistrationDeliverySingleton() - .projectType, - (taskdata ?? []) - .isNotEmpty - ? taskdata?.last - : null, - sideEffectData, - ) - : false, - name: e.name?.givenName ?? ' - ', - years: (e.dateOfBirth == null - ? null - : DigitDateUtils.calculateAge( - DigitDateUtils - .getFormattedDateToDateTime( - e.dateOfBirth!, - ) ?? - DateTime.now(), - ).years) ?? - 0, - months: (e.dateOfBirth == null - ? null - : DigitDateUtils.calculateAge( - DigitDateUtils - .getFormattedDateToDateTime( - e.dateOfBirth!, - ) ?? - DateTime.now(), - ).months) ?? - 0, - gender: e.gender?.name, - isBeneficiaryRefused: - isBeneficiaryRefused && - !checkStatus( - taskdata, - currentCycle, - ), - isBeneficiaryReferred: - isBeneficiaryReferred, - isDelivered: taskdata == null - ? false - : taskdata.isNotEmpty && - !checkStatus( - taskdata, - currentCycle, - ) - // TODO Need to pass the cycle - ? true - : false, - localizations: localizations, - projectBeneficiaryClientReferenceId: - projectBeneficiaryId, - ); - }, - ).toList(), - ), - const SizedBox( - height: kPadding, - ), - Center( - child: DigitIconButton( - onPressed: () async { - final bloc = context - .read(); + final isBeneficiaryRefused = + checkIfBeneficiaryRefused( + taskData, + ); + final isBeneficiaryReferred = + checkIfBeneficiaryReferred( + referralData, + currentCycle, + ); + + return MemberCard( + isHead: isHead, + individual: e, + projectBeneficiaries: + projectBeneficiary ?? [], + tasks: taskData, + sideEffects: sideEffectData, + editMemberAction: () async { + final bloc = + ctx.read(); - final wrapper = - state.householdMemberWrapper; - final address = - wrapper.household.address; + Navigator.of( + context, + rootNavigator: true, + ).pop(); - if (address == null) return; + final address = e.address; + if (address == null || + address.isEmpty) { + return; + } final projectId = RegistrationDeliverySingleton() .projectId!; - await context.router.push( + bloc.add( + HouseholdOverviewReloadEvent( + projectId: projectId, + projectBeneficiaryType: + beneficiaryType, + ), + ); + + await context.router.root.push( BeneficiaryRegistrationWrapperRoute( initialState: - BeneficiaryRegistrationAddMemberState( - addressModel: address, - householdModel: wrapper.household, + BeneficiaryRegistrationEditIndividualState( + individualModel: e, + householdModel: state + .householdMemberWrapper + .household!, + addressModel: address.first, + projectBeneficiaryModel: state + .householdMemberWrapper + .projectBeneficiaries + ?.firstWhereOrNull( + (element) => + element + .beneficiaryClientReferenceId == + (RegistrationDeliverySingleton() + .beneficiaryType == + BeneficiaryType + .individual + ? e.clientReferenceId + : state + .householdMemberWrapper + .household + ?.clientReferenceId), + ), ), children: [ - IndividualDetailsRoute(), + IndividualDetailsRoute( + isHeadOfHousehold: isHead, + ), ], ), ); - bloc.add( - HouseholdOverviewReloadEvent( - projectId: projectId, - projectBeneficiaryType: - beneficiaryType, + }, + setAsHeadAction: () { + ctx.read().add( + HouseholdOverviewSetAsHeadEvent( + individualModel: e, + projectId: + RegistrationDeliverySingleton() + .projectId!, + householdModel: state + .householdMemberWrapper + .household!, + projectBeneficiaryType: + beneficiaryType, + ), + ); + + Navigator.of( + context, + rootNavigator: true, + ).pop(); + }, + deleteMemberAction: () { + DigitDialog.show( + context, + options: DigitDialogOptions( + titlePadding: + const EdgeInsets.fromLTRB( + kPadding * 2, + kPadding * 2, + kPadding * 2, + kPadding / 2, + ), + titleText: localizations.translate(i18 + .householdOverView + .householdOverViewActionCardTitle), + primaryAction: DigitDialogActions( + label: localizations.translate(i18 + .householdOverView + .householdOverViewPrimaryActionLabel), + action: (ctx) { + Navigator.of( + context, + rootNavigator: true, + ) + ..pop() + ..pop(); + context + .read< + HouseholdOverviewBloc>() + .add( + HouseholdOverviewEvent + .selectedIndividual( + individualModel: e, + ), + ); + context.router.push( + ReasonForDeletionRoute( + isHousholdDelete: false, + ), + ); + }, + ), + secondaryAction: DigitDialogActions( + label: localizations.translate(i18 + .householdOverView + .householdOverViewSecondaryActionLabel), + action: (context) { + Navigator.of( + context, + rootNavigator: true, + ).pop(); + }, + ), ), ); }, - iconText: localizations.translate( - i18.householdOverView - .householdOverViewAddActionText, - ), - icon: Icons.add_circle, - ), - ), - const SizedBox( - height: kPadding, + isNotEligible: RegistrationDeliverySingleton() + .projectType + ?.cycles != + null + ? !checkEligibilityForAgeAndSideEffect( + DigitDOBAge( + years: ageInYears, + months: ageInMonths, + ), + RegistrationDeliverySingleton() + .projectType, + (taskData ?? []).isNotEmpty + ? taskData?.lastOrNull + : null, + sideEffectData, + ) + : false, + name: e.name?.givenName ?? ' - - ', + years: (e.dateOfBirth == null + ? null + : DigitDateUtils.calculateAge( + DigitDateUtils + .getFormattedDateToDateTime( + e.dateOfBirth!, + ) ?? + DateTime.now(), + ).years), + months: (e.dateOfBirth == null + ? null + : DigitDateUtils.calculateAge( + DigitDateUtils + .getFormattedDateToDateTime( + e.dateOfBirth!, + ) ?? + DateTime.now(), + ).months), + gender: e.gender?.name, + isBeneficiaryRefused: + isBeneficiaryRefused && + !checkStatus( + taskData, + currentCycle, + ), + isBeneficiaryReferred: + isBeneficiaryReferred, + isDelivered: taskData == null + ? false + : taskData.isNotEmpty && + !checkStatus( + taskData, + currentCycle, + ) + ? true + : false, + localizations: localizations, + projectBeneficiaryClientReferenceId: + projectBeneficiaryId, + ); + }, + ).toList(), + ), + const SizedBox( + height: kPadding, + ), + Center( + child: DigitIconButton( + buttonDisabled: (state.householdMemberWrapper + .projectBeneficiaries ?? + []) + .isEmpty, + onPressed: (state.householdMemberWrapper + .projectBeneficiaries ?? + []) + .isEmpty + ? null + : () => addIndividual( + context, + state.householdMemberWrapper + .household!, + ), + iconText: localizations.translate( + i18.householdOverView + .householdOverViewAddActionText, ), - ], + icon: Icons.add_circle, + ), + ), + const SizedBox( + height: kPadding, ), - ), + ], ), - ], - ); - }, + ), + ), + ], ), ); }, ), ); } + + addIndividual(BuildContext context, HouseholdModel household) async { + final bloc = context.read(); + + final address = household.address; + + if (address == null) return; + bloc.add( + HouseholdOverviewReloadEvent( + projectId: RegistrationDeliverySingleton().projectId!, + projectBeneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!, + ), + ); + await context.router.push( + BeneficiaryRegistrationWrapperRoute( + initialState: BeneficiaryRegistrationAddMemberState( + addressModel: address, + householdModel: household, + ), + children: [ + IndividualDetailsRoute(), + ], + ), + ); + } + + getStatusAttributes(HouseholdOverviewState state, + DeliverInterventionState deliverInterventionState) { + var textLabel = + i18.householdOverView.householdOverViewNotRegisteredIconLabel; + var color = DigitTheme.instance.colorScheme.error; + var icon = Icons.info_rounded; + + if ((state.householdMemberWrapper.projectBeneficiaries ?? []).isNotEmpty) { + textLabel = state.householdMemberWrapper.tasks?.isNotEmpty ?? false + ? getTaskStatus(state.householdMemberWrapper.tasks ?? []).toValue() + : Status.registered.toValue(); + + color = state.householdMemberWrapper.tasks?.isNotEmpty ?? false + ? (state.householdMemberWrapper.tasks?.lastOrNull?.status == + Status.administeredSuccess.toValue() + ? DigitTheme.instance.colorScheme.onSurfaceVariant + : DigitTheme.instance.colorScheme.error) + : DigitTheme.instance.colorScheme.onSurfaceVariant; + + icon = state.householdMemberWrapper.tasks?.isNotEmpty ?? false + ? (state.householdMemberWrapper.tasks?.lastOrNull?.status == + Status.administeredSuccess.toValue() + ? Icons.check_circle + : Icons.info_rounded) + : Icons.check_circle; + } else { + textLabel = i18.householdOverView.householdOverViewNotRegisteredIconLabel; + color = DigitTheme.instance.colorScheme.error; + icon = Icons.info_rounded; + } + + return {'textLabel': textLabel, 'color': color, 'icon': icon}; + } + + void navigateToChecklist(BuildContext ctx) async { + await context.router.push(BeneficiaryChecklistRoute()); + } } diff --git a/packages/registration_delivery/lib/pages/beneficiary/record_past_delivery_details.dart b/packages/registration_delivery/lib/pages/beneficiary/record_past_delivery_details.dart index 53dc77eb2..2199df0d0 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/record_past_delivery_details.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/record_past_delivery_details.dart @@ -31,10 +31,10 @@ class RecordPastDeliveryDetailsPage extends LocalizedStatefulWidget { @override State createState() => - _RecordPastDeliveryDetailsPageState(); + RecordPastDeliveryDetailsPageState(); } -class _RecordPastDeliveryDetailsPageState +class RecordPastDeliveryDetailsPageState extends LocalizedState { static const _recordDoseAdministeredKey = 'recordDoseAdministered'; @override @@ -144,7 +144,7 @@ class _RecordPastDeliveryDetailsPageState taskSearch: TaskSearchModel( projectBeneficiaryClientReferenceId: bloc.state .householdMemberWrapper.projectBeneficiaries - .map((e) => e.clientReferenceId) + ?.map((e) => e.clientReferenceId) .toList(), ), )); diff --git a/packages/registration_delivery/lib/pages/beneficiary/refer_beneficiary.dart b/packages/registration_delivery/lib/pages/beneficiary/refer_beneficiary.dart index f0ab5c886..256fb74ef 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/refer_beneficiary.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/refer_beneficiary.dart @@ -31,10 +31,10 @@ class ReferBeneficiaryPage extends LocalizedStatefulWidget { required this.projectBeneficiaryClientRefId, }); @override - State createState() => _ReferBeneficiaryPageState(); + State createState() => ReferBeneficiaryPageState(); } -class _ReferBeneficiaryPageState extends LocalizedState { +class ReferBeneficiaryPageState extends LocalizedState { static const _dateOfReferralKey = 'dateOfReferral'; static const _administrativeUnitKey = 'administrativeUnit'; static const _referredByKey = 'referredBy'; @@ -380,7 +380,8 @@ class _ReferBeneficiaryPageState extends LocalizedState { return fb.group({ _dateOfReferralKey: FormControl(value: DateTime.now()), _administrativeUnitKey: FormControl( - value: RegistrationDeliverySingleton().boundary!.name), + value: localizations.translate( + RegistrationDeliverySingleton().boundary!.name.toString())), _referredByKey: FormControl( value: RegistrationDeliverySingleton().loggedInUserUuid, validators: [Validators.required], diff --git a/packages/registration_delivery/lib/pages/beneficiary/refused_delivery.dart b/packages/registration_delivery/lib/pages/beneficiary/refused_delivery.dart new file mode 100644 index 000000000..033d184ac --- /dev/null +++ b/packages/registration_delivery/lib/pages/beneficiary/refused_delivery.dart @@ -0,0 +1,331 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/models/entities/additional_fields_type.dart'; +import 'package:registration_delivery/registration_delivery.dart'; +import 'package:registration_delivery/router/registration_delivery_router.gm.dart'; +import 'package:registration_delivery/utils/extensions/extensions.dart'; + +import '../../models/entities/status.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../widgets/back_navigation_help_header.dart'; +import '../../widgets/localized.dart'; +import '../../widgets/showcase/config/showcase_constants.dart'; +import '../../widgets/showcase/showcase_button.dart'; + +@RoutePage() +class RefusedDeliveryPage extends LocalizedStatefulWidget { + const RefusedDeliveryPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => RefusedDeliveryPageState(); +} + +class RefusedDeliveryPageState extends LocalizedState { + static const _dataOfRefusalKey = 'dateOfAdministration'; + static const _reasonOfRefusal = 'reasonOfRefusal'; + static const _deliveryCommentKey = 'deliveryComment'; + + @override + void initState() { + final registrationState = context.read().state; + + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final bloc = context.read(); + final router = context.router; + + return Scaffold( + body: ReactiveFormBuilder( + form: () => buildForm(), + builder: (_, form, __) => + BlocBuilder( + builder: (context, registrationState) { + return ScrollableContent( + enableFixedButton: true, + header: const Column( + children: [ + BackNavigationHelpHeaderWidget( + showcaseButton: ShowcaseButton(), + showHelp: false, + ), + ], + ), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: + const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: DigitElevatedButton( + onPressed: () { + form.markAllAsTouched(); + + if (form.control(_reasonOfRefusal).value == null) { + setState(() { + form + .control(_reasonOfRefusal) + .setErrors({'': true}); + }); + } + + if (!form.valid) return; + + final reasonOfRefusal = + form.control(_reasonOfRefusal).value; + + final refusalComment = + form.control(_deliveryCommentKey).value; + + final projectBeneficiary = + RegistrationDeliverySingleton().beneficiaryType != + BeneficiaryType.individual + ? [ + registrationState.householdMemberWrapper + .projectBeneficiaries?.first + ] + : registrationState.householdMemberWrapper + .projectBeneficiaries + ?.where( + (element) => + element + .beneficiaryClientReferenceId == + registrationState.selectedIndividual + ?.clientReferenceId, + ) + .toList(); + + // Determine the status based on the reason of refusal + String status; + if (reasonOfRefusal == + Status.beneficiaryRefused.toValue()) { + status = Status.beneficiaryRefused.toValue(); + } else { + status = Status.administeredFailed.toValue(); + } + final oldTask = + RegistrationDeliverySingleton().beneficiaryType != + BeneficiaryType.individual + ? registrationState + .householdMemberWrapper.tasks?.last + : null; + + context.read().add( + DeliverInterventionSubmitEvent( + navigateToSummary: true, + householdMemberWrapper: + registrationState.householdMemberWrapper, + task: _getTaskModel( + oldTask, + projectBeneficiary + ?.first?.clientReferenceId, + status, + reasonOfRefusal, + refusalComment, + registrationState.householdMemberWrapper + .members?.first.address?.first), + isEditing: false, + boundaryModel: + RegistrationDeliverySingleton().boundary!, + ), + ); + context.router.push(DeliverySummaryRoute()); + }, + child: Center( + child: Text( + localizations.translate( + i18.householdLocation.actionLabel, + ), + ), + ), + ), + ), + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB( + 0, 0, 0, kPadding), + child: Text( + localizations.translate( + i18.deliverIntervention + .refusedDeliveryLabel, + ), + style: theme.textTheme.displayMedium, + ), + ), + Column(children: [ + refusedDeliveryShowcaseData.dateOfVisit + .buildWith( + child: DigitDateFormPicker( + isEnabled: false, + formControlName: _dataOfRefusalKey, + label: localizations.translate( + i18.deliverIntervention + .refusedDeliveryVisitDateLabel, + ), + confirmText: localizations.translate( + i18.common.coreCommonOk, + ), + cancelText: localizations.translate( + i18.common.coreCommonCancel, + ), + isRequired: false, + padding: const EdgeInsets.only( + top: kPadding, + ), + ), + ), + const SizedBox( + height: kPadding, + ), + refusedDeliveryShowcaseData.reasonOfRefusal + .buildWith( + child: LabeledField( + label: localizations.translate( + i18.deliverIntervention + .reasonForRefusalLabel, + ), + isRequired: true, + child: SelectionBox( + width: MediaQuery.of(context).size.width * + .36, + allowMultipleSelection: false, + options: RegistrationDeliverySingleton() + .refusalReasons ?? + [], + onSelectionChanged: (value) { + form + .control(_reasonOfRefusal) + .markAsTouched(); + setState(() { + if (value.isNotEmpty) { + form + .control(_reasonOfRefusal) + .value = value.first; + } else { + form + .control(_reasonOfRefusal) + .value = null; + setState(() { + form + .control(_reasonOfRefusal) + .setErrors({'': true}); + }); + } + }); + }, + valueMapper: (value) { + return localizations.translate( + 'REASON_${value.toString()}'); + }, + errorMessage: form + .control(_reasonOfRefusal) + .hasErrors && + form + .control(_reasonOfRefusal) + .touched + ? localizations.translate( + i18.common.corecommonRequired) + : null, + ), + ), + ), + refusedDeliveryShowcaseData.comments.buildWith( + child: DigitTextFormField( + formControlName: _deliveryCommentKey, + label: localizations.translate(i18 + .deliverIntervention + .reasonForRefusalCommentLabel), + ), + ), + ]), + ], + ), + ), + ), + ], + ); + }, + )), + ); + } + + _getTaskModel( + TaskModel? oldTask, + String? projectBeneficiaryClientReferenceId, + String status, + String? reasonOfRefusal, + String? refusalComment, + AddressModel? address, + ) { + var task = oldTask; + var clientReferenceId = task?.clientReferenceId ?? IdGen.i.identifier; + task ??= TaskModel( + projectBeneficiaryClientReferenceId: projectBeneficiaryClientReferenceId, + clientReferenceId: clientReferenceId, + address: address?.copyWith( + relatedClientReferenceId: clientReferenceId, + ), + tenantId: RegistrationDeliverySingleton().tenantId, + rowVersion: 1, + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton().loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + ), + projectId: RegistrationDeliverySingleton().projectId, + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton().loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: RegistrationDeliverySingleton().loggedInUserUuid, + lastModifiedTime: context.millisecondsSinceEpoch(), + ), + ); + + task = task.copyWith( + status: status, + address: address?.copyWith( + relatedClientReferenceId: clientReferenceId, + ), + additionalFields: TaskAdditionalFields( + version: 1, + fields: [ + AdditionalField( + AdditionalFieldsType.reasonOfRefusal.toValue(), + reasonOfRefusal, + ), + if (refusalComment != null) + AdditionalField( + AdditionalFieldsType.deliveryComment.toValue(), + refusalComment, + ), + ], + ), + ); + + return task; + } + + FormGroup buildForm() { + return fb.group({ + _dataOfRefusalKey: + FormControl(value: DateTime.now(), validators: []), + _reasonOfRefusal: + FormControl(value: null, validators: [Validators.required]), + _deliveryCommentKey: FormControl(value: null), + }); + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary/side_effects.dart b/packages/registration_delivery/lib/pages/beneficiary/side_effects.dart index 02bacb784..3f479f68c 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/side_effects.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/side_effects.dart @@ -32,10 +32,10 @@ class SideEffectsPage extends LocalizedStatefulWidget { }); @override - State createState() => _SideEffectsPageState(); + State createState() => SideEffectsPageState(); } -class _SideEffectsPageState extends LocalizedState { +class SideEffectsPageState extends LocalizedState { List symptomsValues = []; List symptomsTypes = []; bool symptomsSelected = true; diff --git a/packages/registration_delivery/lib/pages/beneficiary/widgets/household_acknowledgement.dart b/packages/registration_delivery/lib/pages/beneficiary/widgets/household_acknowledgement.dart index 639439d26..8ff5bcfc5 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/widgets/household_acknowledgement.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/widgets/household_acknowledgement.dart @@ -20,10 +20,10 @@ class HouseholdAcknowledgementPage extends LocalizedStatefulWidget { @override State createState() => - _HouseholdAcknowledgementPageState(); + HouseholdAcknowledgementPageState(); } -class _HouseholdAcknowledgementPageState +class HouseholdAcknowledgementPageState extends LocalizedState { @override Widget build(BuildContext context) { @@ -34,6 +34,8 @@ class _HouseholdAcknowledgementPageState builder: (context, householdState) { return DigitAcknowledgement.success( action: () { + context + .read().add(const SearchHouseholdsEvent.clear()); final parent = context.router.parent() as StackRouter; // Pop twice to navigate back to the previous screen parent.popUntilRoot(); diff --git a/packages/registration_delivery/lib/pages/beneficiary/widgets/past_delivery.dart b/packages/registration_delivery/lib/pages/beneficiary/widgets/past_delivery.dart index ebbbfaf28..ba7118d19 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/widgets/past_delivery.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/widgets/past_delivery.dart @@ -4,6 +4,7 @@ import 'package:digit_components/models/digit_table_model.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; import 'package:registration_delivery/blocs/app_localization.dart'; +import 'package:registration_delivery/registration_delivery.dart'; import '../../../blocs/delivery_intervention/deliver_intervention.dart'; import '../../../utils/i18_key_constants.dart' as i18; @@ -15,6 +16,7 @@ Widget buildTableContent( BuildContext context, List? variant, IndividualModel? individualModel, + HouseholdModel? householdModel, ) { // Calculate the current cycle. If deliverInterventionState.cycle is negative, set it to 0. final currentCycle = @@ -44,7 +46,7 @@ Widget buildTableContent( final item = projectType.cycles?[currentCycle - 1].deliveries?[currentDose - 1]; final productVariants = - fetchProductVariant(item, individualModel)?.productVariants; + fetchProductVariant(item, individualModel, householdModel)?.productVariants; final numRows = productVariants?.length ?? 0; const rowHeight = 84; const paddingHeight = (kPadding * 2); @@ -72,9 +74,9 @@ Widget buildTableContent( element: { localizations.translate( i18.beneficiaryDetails.beneficiaryAge, - ): fetchProductVariant(item, individualModel)?.condition != null + ): fetchProductVariant(item, individualModel, householdModel)?.condition != null ? localizations.translate( - fetchProductVariant(item, individualModel)!.condition!) + fetchProductVariant(item, individualModel, householdModel)!.condition!) : null, }, ), @@ -82,11 +84,11 @@ Widget buildTableContent( thickness: 1.0, ), // Build the DigitTable with the data - fetchProductVariant(item, individualModel)?.productVariants != null + fetchProductVariant(item, individualModel, householdModel)?.productVariants != null ? DigitTable( headerList: headerListResource, tableData: [ - ...fetchProductVariant(item, individualModel)! + ...fetchProductVariant(item, individualModel, householdModel )! .productVariants! .map( (e) { @@ -102,7 +104,7 @@ Widget buildTableContent( // Display the dose information in the first column if it's the first row, // otherwise, display an empty cell. - fetchProductVariant(item, individualModel) + fetchProductVariant(item, individualModel, householdModel) ?.productVariants ?.indexOf(e) == 0 @@ -121,7 +123,7 @@ Widget buildTableContent( ), ], columnWidth: columnWidth, - height: ((fetchProductVariant(item, individualModel) + height: ((fetchProductVariant(item, individualModel, householdModel) ?.productVariants ?? []) .length + diff --git a/packages/registration_delivery/lib/pages/beneficiary/widgets/record_delivery_cycle.dart b/packages/registration_delivery/lib/pages/beneficiary/widgets/record_delivery_cycle.dart index 55061ef97..ca9a04d45 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/widgets/record_delivery_cycle.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/widgets/record_delivery_cycle.dart @@ -28,10 +28,10 @@ class RecordDeliveryCycle extends LocalizedStatefulWidget { }); @override - State createState() => _RecordDeliveryCycleState(); + State createState() => RecordDeliveryCycleState(); } -class _RecordDeliveryCycleState extends LocalizedState { +class RecordDeliveryCycleState extends LocalizedState { bool isExpanded = false; bool isDivider = false; diff --git a/packages/registration_delivery/lib/pages/beneficiary/widgets/splash_acknowledgement.dart b/packages/registration_delivery/lib/pages/beneficiary/widgets/splash_acknowledgement.dart index 6369cf16f..e1b7e02a0 100644 --- a/packages/registration_delivery/lib/pages/beneficiary/widgets/splash_acknowledgement.dart +++ b/packages/registration_delivery/lib/pages/beneficiary/widgets/splash_acknowledgement.dart @@ -19,10 +19,10 @@ class SplashAcknowledgementPage extends LocalizedStatefulWidget { @override State createState() => - _SplashAcknowledgementPageState(); + SplashAcknowledgementPageState(); } -class _SplashAcknowledgementPageState +class SplashAcknowledgementPageState extends LocalizedState { @override void initState() { diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_acknowledgement.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_acknowledgement.dart index f47a66997..10b7e82b8 100644 --- a/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_acknowledgement.dart +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_acknowledgement.dart @@ -1,58 +1,58 @@ -import 'package:auto_route/auto_route.dart'; -import 'package:digit_components/digit_components.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; - -import '../../../utils/i18_key_constants.dart' as i18; -import '../../../widgets/localized.dart'; -import '../../blocs/search_households/search_bloc_common_wrapper.dart'; -import '../../router/registration_delivery_router.gm.dart'; - -@RoutePage() -class BeneficiaryAcknowledgementPage extends LocalizedStatefulWidget { - final bool? enableViewHousehold; - - const BeneficiaryAcknowledgementPage({ - super.key, - super.appLocalizations, - this.enableViewHousehold, - }); - - @override - State createState() => - _BeneficiaryAcknowledgementPageState(); -} - -class _BeneficiaryAcknowledgementPageState - extends LocalizedState { - @override - Widget build(BuildContext context) { - return Scaffold( - body: DigitAcknowledgement.success( - action: () { - context.router.maybePop(); - }, - secondaryAction: () { - final bloc = context.read(); - - context.router.popAndPush( - BeneficiaryWrapperRoute( - wrapper: bloc.state.householdMembers.first, - ), - ); - }, - enableViewHousehold: widget.enableViewHousehold ?? false, - secondaryLabel: localizations.translate( - i18.householdDetails.viewHouseHoldDetailsAction, - ), - actionLabel: - localizations.translate(i18.acknowledgementSuccess.actionLabelText), - description: localizations.translate( - i18.acknowledgementSuccess.acknowledgementDescriptionText, - ), - label: localizations - .translate(i18.acknowledgementSuccess.acknowledgementLabelText), - ), - ); - } -} +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +import '../../../utils/i18_key_constants.dart' as i18; +import '../../../widgets/localized.dart'; +import '../../blocs/search_households/search_bloc_common_wrapper.dart'; +import '../../router/registration_delivery_router.gm.dart'; + +@RoutePage() +class BeneficiaryAcknowledgementPage extends LocalizedStatefulWidget { + final bool? enableViewHousehold; + + const BeneficiaryAcknowledgementPage({ + super.key, + super.appLocalizations, + this.enableViewHousehold, + }); + + @override + State createState() => + BeneficiaryAcknowledgementPageState(); +} + +class BeneficiaryAcknowledgementPageState + extends LocalizedState { + @override + Widget build(BuildContext context) { + return Scaffold( + body: DigitAcknowledgement.success( + action: () { + context.router.maybePop(); + }, + secondaryAction: () { + final bloc = context.read(); + + context.router.popAndPush( + BeneficiaryWrapperRoute( + wrapper: bloc.state.householdMembers.first, + ), + ); + }, + enableViewHousehold: widget.enableViewHousehold ?? false, + secondaryLabel: localizations.translate( + i18.householdDetails.viewHouseHoldDetailsAction, + ), + actionLabel: + localizations.translate(i18.acknowledgementSuccess.actionLabelText), + description: localizations.translate( + i18.acknowledgementSuccess.acknowledgementDescriptionText, + ), + label: localizations + .translate(i18.acknowledgementSuccess.acknowledgementLabelText), + ), + ); + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_registration_wrapper.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_registration_wrapper.dart index b6f73e6f3..09f6adf47 100644 --- a/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_registration_wrapper.dart +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/beneficiary_registration_wrapper.dart @@ -1,55 +1,111 @@ -import 'package:auto_route/auto_route.dart'; -import 'package:digit_data_model/models/entities/individual.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:registration_delivery/models/entities/project_beneficiary.dart'; - -import '../../blocs/beneficiary_registration/beneficiary_registration.dart'; -import '../../models/entities/household.dart'; -import '../../models/entities/household_member.dart'; -import '../../utils/extensions/extensions.dart'; -import '../../utils/utils.dart'; - -@RoutePage() -class BeneficiaryRegistrationWrapperPage extends StatelessWidget - implements AutoRouteWrapper { - final BeneficiaryRegistrationState initialState; - - const BeneficiaryRegistrationWrapperPage({ - super.key, - required this.initialState, - }); - - @override - Widget build(BuildContext context) { - return const AutoRouter(); - } - - @override - Widget wrappedRoute(BuildContext context) { - final beneficiaryType = RegistrationDeliverySingleton().beneficiaryType; - final individual = - context.repository(context); - - final household = - context.repository(context); - - final householdMember = context - .repository(context); - - final projectBeneficiary = context.repository(context); - - return BlocProvider( - create: (context) => BeneficiaryRegistrationBloc( - initialState, - individualRepository: individual, - householdRepository: household, - householdMemberRepository: householdMember, - projectBeneficiaryRepository: projectBeneficiary, - beneficiaryType: beneficiaryType!, - ), - child: this, - ); - } -} +import 'package:auto_route/auto_route.dart'; +import 'package:digit_data_model/models/entities/individual.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/registration_delivery.dart'; + +import '../../utils/extensions/extensions.dart'; + +@RoutePage() +class BeneficiaryRegistrationWrapperPage extends StatelessWidget + implements AutoRouteWrapper { + final BeneficiaryRegistrationState initialState; + + const BeneficiaryRegistrationWrapperPage({ + super.key, + required this.initialState, + }); + + @override + Widget build(BuildContext context) { + return const AutoRouter(); + } + + @override + Widget wrappedRoute(BuildContext context) { + final beneficiaryType = RegistrationDeliverySingleton().beneficiaryType; + final individual = + context.repository(context); + + final household = + context.repository(context); + + final householdMember = context + .repository(context); + + final projectBeneficiary = context.repository(context); + final task = context.repository(context); + final sideEffect = + context.repository(context); + final referral = + context.repository(context); + + return BlocProvider( + create: (_) => HouseholdOverviewBloc( + HouseholdOverviewState( + householdMemberWrapper: HouseholdMemberWrapper( + household: initialState.householdModel, + headOfHousehold: initialState.maybeWhen( + orElse: () => null, + editHousehold: (addressModel, + householdModel, + individualModel, + registrationDate, + projectBeneficiaryModel, + loading, + headOfHousehold) => + headOfHousehold), + members: initialState.maybeWhen( + orElse: () => null, + editHousehold: (addressModel, + householdModel, + individualModel, + registrationDate, + projectBeneficiaryModel, + loading, + headOfHousehold) => + individualModel, + ), + projectBeneficiaries: initialState.maybeWhen( + orElse: () => null, + editHousehold: (addressModel, + householdModel, + individualModel, + registrationDate, + projectBeneficiaryModel, + loading, + headOfHousehold) => + projectBeneficiaryModel != null + ? [projectBeneficiaryModel] + : [], + ), + ), + ), + individualRepository: individual, + householdRepository: household, + householdMemberRepository: householdMember, + projectBeneficiaryRepository: projectBeneficiary, + beneficiaryType: RegistrationDeliverySingleton().beneficiaryType!, + taskDataRepository: task, + sideEffectDataRepository: sideEffect, + referralDataRepository: referral) + ..add(HouseholdOverviewReloadEvent( + projectId: RegistrationDeliverySingleton().selectedProject!.id, + projectBeneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!)), + child: BlocProvider( + create: (context) => BeneficiaryRegistrationBloc( + initialState, + individualRepository: individual, + householdRepository: household, + householdMemberRepository: householdMember, + projectBeneficiaryRepository: projectBeneficiary, + taskDataRepository: task, + beneficiaryType: beneficiaryType!, + ), + child: this, + ), + ); + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/house_details.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/house_details.dart new file mode 100644 index 000000000..08e42399c --- /dev/null +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/house_details.dart @@ -0,0 +1,343 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; +import 'package:digit_data_model/data_model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/registration_delivery.dart'; +import 'package:registration_delivery/router/registration_delivery_router.gm.dart'; +import 'package:registration_delivery/utils/extensions/extensions.dart'; + +import '../../models/entities/additional_fields_type.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../../widgets/back_navigation_help_header.dart'; +import '../../widgets/localized.dart'; +import '../../widgets/showcase/config/showcase_constants.dart'; +import '../../widgets/showcase/showcase_button.dart'; + +@RoutePage() +class HouseDetailsPage extends LocalizedStatefulWidget { + const HouseDetailsPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => HouseDetailsPageState(); +} + +class HouseDetailsPageState extends LocalizedState { + static const _noOfRoomsKey = 'noOfRooms'; + static const _householdStructureKey = 'householdStructure'; + List? selectedHouseStructureTypes; + + @override + void initState() { + final registrationState = context.read().state; + + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final bloc = context.read(); + final router = context.router; + + return Scaffold( + body: ReactiveFormBuilder( + form: () => buildForm(bloc.state), + builder: (_, form, __) => BlocBuilder( + builder: (context, registrationState) { + return ScrollableContent( + enableFixedButton: true, + header: const Column( + children: [ + BackNavigationHelpHeaderWidget( + showcaseButton: ShowcaseButton(), + showHelp: false, + ), + ], + ), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: + const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: DigitElevatedButton( + onPressed: () { + form.markAllAsTouched(); + if (form.control(_householdStructureKey).value == + null) { + setState(() { + form + .control(_householdStructureKey) + .setErrors({'': true}); + }); + } + + if (!form.valid) return; + selectedHouseStructureTypes = + form.control(_householdStructureKey).value; + + final noOfRooms = + form.control(_noOfRoomsKey).value as int; + registrationState.maybeWhen( + orElse: () { + return; + }, + create: ( + address, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold, + ) { + var houseModel = HouseholdModel( + clientReferenceId: IdGen.i.identifier, + tenantId: + RegistrationDeliverySingleton().tenantId, + rowVersion: 1, + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: + context.millisecondsSinceEpoch(), + ), + memberCount: householdModel?.memberCount, + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: + context.millisecondsSinceEpoch(), + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + additionalFields: HouseholdAdditionalFields( + version: 1, + fields: [ + ...?householdModel + ?.additionalFields?.fields + .where((e) => + e.key != + AdditionalFieldsType + .houseStructureTypes + .toValue() && + e.key != + AdditionalFieldsType + .noOfRooms + .toValue()), + AdditionalField( + AdditionalFieldsType + .houseStructureTypes + .toValue(), + selectedHouseStructureTypes + ?.join("|") + .toString(), + ), + AdditionalField( + AdditionalFieldsType.noOfRooms + .toValue(), + noOfRooms, + ) + ])); + + bloc.add( + BeneficiaryRegistrationSaveHouseDetailsEvent( + model: houseModel, + ), + ); + router.push(HouseHoldDetailsRoute()); + }, + editHousehold: ( + address, + householdModel, + individuals, + registrationDate, + projectBeneficiaryModel, + loading, + headOfHousehold, + ) { + var houseModel = householdModel.copyWith( + additionalFields: HouseholdAdditionalFields( + version: 1, + fields: [ + ...?householdModel.additionalFields?.fields + .where((e) => + e.key != + AdditionalFieldsType + .houseStructureTypes + .toValue() && + e.key != + AdditionalFieldsType.noOfRooms + .toValue()), + AdditionalField( + AdditionalFieldsType.houseStructureTypes + .toValue(), + selectedHouseStructureTypes + ?.join("|") + .toString(), + ), + AdditionalField( + AdditionalFieldsType.noOfRooms.toValue(), + noOfRooms, + ) + ])); + // TODO [Linking of Voucher for Household based project need to be handled] + + bloc.add( + BeneficiaryRegistrationSaveHouseDetailsEvent( + model: houseModel, + ), + ); + router.push(HouseHoldDetailsRoute()); + }, + ); + }, + child: Center( + child: Text( + localizations.translate( + i18.householdLocation.actionLabel, + ), + ), + ), + ), + ), + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB( + 0, 0, 0, kPadding), + child: Text( + localizations.translate( + i18.householdDetails.houseDetailsLabel, + ), + style: theme.textTheme.displayMedium, + ), + ), + Column(children: [ + houseShowcaseData.typeOfStructure.buildWith( + child: SelectionBox( + isRequired: true, + title: localizations.translate( + i18.householdDetails.typeOfStructure), + equalWidthOptions: true, + allowMultipleSelection: false, + options: RegistrationDeliverySingleton() + .houseStructureTypes ?? + [], + initialSelection: registrationState + .householdModel + ?.additionalFields + ?.fields + .where((e) => + e.key == + AdditionalFieldsType + .houseStructureTypes + .toValue()) + .first + .value + .toString() + .split("|"), + onSelectionChanged: (values) { + form + .control(_householdStructureKey) + .markAsTouched(); + if (values.isEmpty) { + form + .control(_householdStructureKey) + .value = null; + setState(() { + form + .control(_householdStructureKey) + .setErrors({'': true}); + }); + } else { + setState(() { + form + .control(_householdStructureKey) + .value = values; + }); + } + }, + valueMapper: (value) { + return localizations + .translate(value.toString()); + }, + errorMessage: form + .control(_householdStructureKey) + .hasErrors && + form + .control(_householdStructureKey) + .touched + ? localizations.translate(i18 + .householdDetails + .selectStructureTypeError) + : null, + ), + ), + houseShowcaseData.noOfRooms.buildWith( + child: DigitIntegerFormPicker( + minimum: 1, + maximum: 20, + form: form, + formControlName: _noOfRoomsKey, + label: localizations.translate( + i18.householdDetails.noOfRoomsLabel, + ), + incrementer: true, + ), + ), + ]), + ], + ), + ), + ), + ], + ); + }, + )), + ); + } + + FormGroup buildForm(BeneficiaryRegistrationState state) { + return fb.group({ + _noOfRoomsKey: FormControl( + value: state.householdModel?.additionalFields?.fields + .where((h) => + h.key == AdditionalFieldsType.noOfRooms.toValue()) + .firstOrNull + ?.value != + null + ? int.tryParse(state.householdModel?.additionalFields?.fields + .where((h) => + h.key == AdditionalFieldsType.noOfRooms.toValue()) + .firstOrNull + ?.value + .toString() ?? + '1') + : 1), + _householdStructureKey: FormControl>( + value: state.householdModel?.additionalFields?.fields + .where((e) => + e.key == AdditionalFieldsType.houseStructureTypes.toValue()) + .first + .value + .toString() + .split("|"), + ) + }); + } +} diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/household_details.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/household_details.dart index 385ac6363..8d0f29b23 100644 --- a/packages/registration_delivery/lib/pages/beneficiary_registration/household_details.dart +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/household_details.dart @@ -1,9 +1,14 @@ import 'package:auto_route/auto_route.dart'; import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/atoms/text_block.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/blocs/household_overview/household_overview.dart'; +import 'package:registration_delivery/blocs/search_households/search_households.dart'; +import 'package:registration_delivery/models/entities/additional_fields_type.dart'; import 'package:registration_delivery/utils/extensions/extensions.dart'; import '../../blocs/beneficiary_registration/beneficiary_registration.dart'; @@ -24,12 +29,14 @@ class HouseHoldDetailsPage extends LocalizedStatefulWidget { }); @override - State createState() => _HouseHoldDetailsPageState(); + State createState() => HouseHoldDetailsPageState(); } -class _HouseHoldDetailsPageState extends LocalizedState { +class HouseHoldDetailsPageState extends LocalizedState { static const _dateOfRegistrationKey = 'dateOfRegistration'; static const _memberCountKey = 'memberCount'; + static const _pregnantWomenCountKey = 'pregnantWomenCount'; + static const _childrenCountKey = 'childrenCount'; @override Widget build(BuildContext context) { @@ -40,117 +47,249 @@ class _HouseHoldDetailsPageState extends LocalizedState { return Scaffold( body: ReactiveFormBuilder( form: () => buildForm(bloc.state), - builder: (context, form, child) => BlocBuilder< - BeneficiaryRegistrationBloc, BeneficiaryRegistrationState>( - builder: (context, registrationState) { - return ScrollableContent( - header: const Column(children: [ - BackNavigationHelpHeaderWidget( - showHelp: false, - showcaseButton: ShowcaseButton(), - ), - ]), - footer: DigitCard( - margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), - padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), - child: DigitElevatedButton( - onPressed: () { - form.markAllAsTouched(); - if (!form.valid) return; + builder: (context, form, child) { + int pregnantWomen = form.control(_pregnantWomenCountKey).value; + int children = form.control(_childrenCountKey).value; + int memberCount = form.control(_memberCountKey).value; + return BlocConsumer( + listener: (context, state) { + if (state is BeneficiaryRegistrationPersistedState && state.isEdit) { + final overviewBloc = + context.read(); - final memberCount = - form.control(_memberCountKey).value as int; + overviewBloc.add( + HouseholdOverviewReloadEvent( + projectId: RegistrationDeliverySingleton() + .projectId + .toString(), + projectBeneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType ?? + BeneficiaryType.household, + ), + ); + HouseholdMemberWrapper memberWrapper = + overviewBloc.state.householdMemberWrapper; + final route = router.parent() as StackRouter; + route.popUntilRouteWithName( + SearchBeneficiaryRoute.name); + route.push(BeneficiaryWrapperRoute( + wrapper: memberWrapper)); + } + }, + builder: (context, registrationState) { + return ScrollableContent( + header: const Column(children: [ + BackNavigationHelpHeaderWidget( + showHelp: false, + showcaseButton: ShowcaseButton(), + ), + ]), + enableFixedButton: true, + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: DigitElevatedButton( + onPressed: () { + form.markAllAsTouched(); + if (!form.valid) return; - final dateOfRegistration = - form.control(_dateOfRegistrationKey).value as DateTime; + final memberCount = + form.control(_memberCountKey).value as int; - registrationState.maybeWhen( - orElse: () { - return; - }, - create: ( - addressModel, - householdModel, - individualModel, - registrationDate, - searchQuery, - loading, - isHeadOfHousehold, - ) { - var household = householdModel; - household ??= HouseholdModel( - tenantId: RegistrationDeliverySingleton().tenantId, - clientReferenceId: IdGen.i.identifier, - rowVersion: 1, - clientAuditDetails: ClientAuditDetails( - createdBy: RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context.millisecondsSinceEpoch(), - lastModifiedBy: RegistrationDeliverySingleton() - .loggedInUserUuid, - lastModifiedTime: context.millisecondsSinceEpoch(), - ), - auditDetails: AuditDetails( - createdBy: RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context.millisecondsSinceEpoch(), - lastModifiedBy: RegistrationDeliverySingleton() - .loggedInUserUuid, - lastModifiedTime: context.millisecondsSinceEpoch(), - ), - ); + final dateOfRegistration = form + .control(_dateOfRegistrationKey) + .value as DateTime; + //[TODO: Use pregnant women form value based on project config + final pregnantWomen = + form.control(_pregnantWomenCountKey).value as int; + final children = + form.control(_childrenCountKey).value as int; - household = household.copyWith( - memberCount: memberCount, - address: addressModel, - ); + if (memberCount < (pregnantWomen + children)) { + DigitToast.show(context, + options: DigitToastOptions( + localizations.translate( + i18.householdDetails.memberCountError), + true, + theme)); + } else { + registrationState.maybeWhen( + orElse: () { + return; + }, + create: ( + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold, + ) { + var household = householdModel; + household ??= HouseholdModel( + tenantId: + RegistrationDeliverySingleton().tenantId, + clientReferenceId: + householdModel?.clientReferenceId ?? + IdGen.i.identifier, + rowVersion: 1, + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + ); - bloc.add( - BeneficiaryRegistrationSaveHouseholdDetailsEvent( - household: household!, - registrationDate: dateOfRegistration, - ), - ); - context.router.push( - IndividualDetailsRoute(isHeadOfHousehold: true), - ); - }, - editHousehold: ( - addressModel, - householdModel, - individuals, - registrationDate, - projectBeneficiaryModel, - loading, - ) { - var household = householdModel.copyWith( - memberCount: memberCount, - address: addressModel, - clientAuditDetails: - (householdModel.clientAuditDetails?.createdBy != - null && - householdModel.clientAuditDetails - ?.createdTime != - null) - ? ClientAuditDetails( - createdBy: householdModel - .clientAuditDetails!.createdBy, - createdTime: householdModel - .clientAuditDetails!.createdTime, - lastModifiedBy: householdModel - .clientAuditDetails!.lastModifiedBy, - lastModifiedTime: - DateTime.now().millisecondsSinceEpoch, - ) - : null, - rowVersion: householdModel.rowVersion, - ); + household = household.copyWith( + rowVersion: 1, + tenantId: + RegistrationDeliverySingleton().tenantId, + clientReferenceId: + householdModel?.clientReferenceId ?? + IdGen.i.identifier, + memberCount: memberCount, + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid + .toString(), + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + address: addressModel, + additionalFields: HouseholdAdditionalFields( + version: 1, + fields: [ + //[TODO: Use pregnant women form value based on project config + ...?householdModel + ?.additionalFields?.fields + .where((e) => + e.key != + AdditionalFieldsType + .pregnantWomen + .toValue() && + e.key != + AdditionalFieldsType.children + .toValue()), + AdditionalField( + AdditionalFieldsType.pregnantWomen + .toValue(), + pregnantWomen, + ), + AdditionalField( + AdditionalFieldsType.children.toValue(), + children, + ) + ])); - bloc.add( - BeneficiaryRegistrationUpdateHouseholdDetailsEvent( - household: household.copyWith( - clientAuditDetails: - (addressModel.clientAuditDetails?.createdBy != + bloc.add( + BeneficiaryRegistrationSaveHouseholdDetailsEvent( + household: household, + registrationDate: dateOfRegistration, + ), + ); + context.router.push( + IndividualDetailsRoute(isHeadOfHousehold: true), + ); + }, + editHousehold: ( + addressModel, + householdModel, + individuals, + registrationDate, + projectBeneficiaryModel, + loading, + isHeadOfHousehold, + ) { + var household = householdModel.copyWith( + memberCount: memberCount, + address: addressModel, + clientAuditDetails: (householdModel + .clientAuditDetails + ?.createdBy != + null && + householdModel.clientAuditDetails + ?.createdTime != + null) + ? ClientAuditDetails( + createdBy: householdModel + .clientAuditDetails!.createdBy, + createdTime: householdModel + .clientAuditDetails!.createdTime, + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: DateTime.now() + .millisecondsSinceEpoch, + ) + : null, + rowVersion: householdModel.rowVersion, + additionalFields: HouseholdAdditionalFields( + version: householdModel + .additionalFields?.version ?? + 1, + fields: [ + //[TODO: Use pregnant women form value based on project config + ...?householdModel + .additionalFields?.fields + .where((e) => + e.key != + AdditionalFieldsType + .pregnantWomen + .toValue() && + e.key != + AdditionalFieldsType.children + .toValue()), + AdditionalField( + AdditionalFieldsType.pregnantWomen + .toValue(), + pregnantWomen, + ), + AdditionalField( + AdditionalFieldsType.children.toValue(), + children, + ) + ])); + + bloc.add( + BeneficiaryRegistrationUpdateHouseholdDetailsEvent( + household: household.copyWith( + clientAuditDetails: (addressModel + .clientAuditDetails + ?.createdBy != null && addressModel.clientAuditDetails ?.createdTime != @@ -167,10 +306,11 @@ class _HouseHoldDetailsPageState extends LocalizedState { context.millisecondsSinceEpoch(), ) : null, - ), - addressModel: addressModel.copyWith( - clientAuditDetails: - (addressModel.clientAuditDetails?.createdBy != + ), + addressModel: addressModel.copyWith( + clientAuditDetails: (addressModel + .clientAuditDetails + ?.createdBy != null && addressModel.clientAuditDetails ?.createdTime != @@ -187,93 +327,168 @@ class _HouseHoldDetailsPageState extends LocalizedState { context.millisecondsSinceEpoch(), ) : null, - ), - ), - ); + ), + ), + ); - (router.parent() as StackRouter).maybePop(); - }, - ); - }, - child: Center( - child: Text( - registrationState.mapOrNull( - editHousehold: (value) => localizations - .translate(i18.common.coreCommonSave), - ) ?? - localizations - .translate(i18.householdDetails.actionLabel), + }, + ); + } + }, + child: Center( + child: Text( + registrationState.mapOrNull( + editHousehold: (value) => localizations + .translate(i18.common.coreCommonSave), + ) ?? + localizations + .translate(i18.householdDetails.actionLabel), + ), ), ), ), - ), - slivers: [ - SliverToBoxAdapter( - child: DigitCard( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: const EdgeInsets.only(bottom: kPadding), - child: Text( - localizations.translate( + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + TextBlock( + padding: const EdgeInsets.only(top: kPadding), + heading: localizations.translate( i18.householdDetails.householdDetailsLabel, ), - style: theme.textTheme.displayMedium, + headingStyle: theme.textTheme.displayMedium, + body: localizations.translate( + i18.householdDetails.householdDetailsDescription, + ), ), - ), - Column(children: [ - householdDetailsShowcaseData.dateOfRegistration - .buildWith( - child: DigitDateFormPicker( - isEnabled: false, - formControlName: _dateOfRegistrationKey, - label: localizations.translate( - i18.householdDetails.dateOfRegistrationLabel, + Column(children: [ + householdDetailsShowcaseData.dateOfRegistration + .buildWith( + child: DigitDateFormPicker( + isEnabled: false, + formControlName: _dateOfRegistrationKey, + label: localizations.translate( + i18.householdDetails.dateOfRegistrationLabel, + ), + isRequired: false, + confirmText: localizations.translate( + i18.common.coreCommonOk, + ), + cancelText: localizations.translate( + i18.common.coreCommonCancel, + ), ), - isRequired: false, - confirmText: localizations.translate( - i18.common.coreCommonOk, + ), + //[TODO: Use pregnant women form value based on project config + householdDetailsShowcaseData + .numberOfPregnantWomenInHousehold + .buildWith( + child: DigitIntegerFormPicker( + minimum: 0, + maximum: 10, + onChange: () { + int pregnantWomen = form + .control(_pregnantWomenCountKey) + .value; + int children = + form.control(_childrenCountKey).value; + int memberCount = + form.control(_memberCountKey).value; + form.control(_memberCountKey).value = + memberCount < (children + pregnantWomen) + ? children + pregnantWomen + : memberCount; + }, + form: form, + formControlName: _pregnantWomenCountKey, + label: localizations.translate( + i18.householdDetails + .noOfPregnantWomenCountLabel, + ), + incrementer: true, ), - cancelText: localizations.translate( - i18.common.coreCommonCancel, + ), + householdDetailsShowcaseData + .numberOfChildrenBelow5InHousehold + .buildWith( + child: DigitIntegerFormPicker( + minimum: 0, + maximum: 20, + onChange: () { + int pregnantWomen = form + .control(_pregnantWomenCountKey) + .value; + int children = + form.control(_childrenCountKey).value; + int memberCount = + form.control(_memberCountKey).value; + form.control(_memberCountKey).value = + memberCount <= (children + pregnantWomen) + ? children + pregnantWomen + : memberCount; + }, + form: form, + formControlName: _childrenCountKey, + label: localizations.translate( + i18.householdDetails + .noOfChildrenBelow5YearsLabel, + ), + incrementer: true, ), ), - ), - householdDetailsShowcaseData - .numberOfMembersLivingInHousehold - .buildWith( - child: DigitIntegerFormPicker( - minimum: 1, - form: form, - formControlName: _memberCountKey, - label: localizations.translate( - i18.householdDetails.noOfMembersCountLabel, + householdDetailsShowcaseData + .numberOfMembersLivingInHousehold + .buildWith( + child: DigitIntegerFormPicker( + minimum: children + pregnantWomen != 0 + ? children + pregnantWomen + : 1, + maximum: 30, + onChange: () { + int pregnantWomen = form + .control(_pregnantWomenCountKey) + .value; + int children = + form.control(_childrenCountKey).value; + int memberCount = + form.control(_memberCountKey).value; + if (memberCount <= pregnantWomen + children) { + form.control(_memberCountKey).value = + (children + pregnantWomen); + } + }, + form: form, + formControlName: _memberCountKey, + label: localizations.translate( + i18.householdDetails.noOfMembersCountLabel, + ), + incrementer: true, ), - incrementer: true, ), - ), - ]), - const SizedBox(height: 16), - ], + ]), + const SizedBox(height: 16), + ], + ), ), ), - ), - ], - ); - }, - ), + ], + ); + }, + ); + }, ), ); } FormGroup buildForm(BeneficiaryRegistrationState state) { - final household = state.mapOrNull( - editHousehold: (value) { - return value.householdModel; - }, - ); + final household = state.mapOrNull(editHousehold: (value) { + return value.householdModel; + }, create: (value) { + return value.householdModel; + }); final registrationDate = state.mapOrNull( editHousehold: (value) { @@ -285,7 +500,41 @@ class _HouseHoldDetailsPageState extends LocalizedState { return fb.group({ _dateOfRegistrationKey: FormControl(value: registrationDate, validators: []), - _memberCountKey: FormControl(value: household?.memberCount ?? 1), + _memberCountKey: FormControl( + value: household?.memberCount ?? 1, + ), + _pregnantWomenCountKey: FormControl( + value: household?.additionalFields?.fields + .where((h) => + h.key == AdditionalFieldsType.pregnantWomen.toValue()) + .firstOrNull + ?.value != + null + ? int.tryParse(household?.additionalFields?.fields + .where((h) => + h.key == AdditionalFieldsType.pregnantWomen.toValue()) + .firstOrNull + ?.value + .toString() ?? + '0') + : 0, + ), + _childrenCountKey: FormControl( + value: household?.additionalFields?.fields + .where( + (h) => h.key == AdditionalFieldsType.children.toValue()) + .firstOrNull + ?.value != + null + ? int.tryParse(household?.additionalFields?.fields + .where( + (h) => h.key == AdditionalFieldsType.children.toValue()) + .firstOrNull + ?.value + .toString() ?? + '0') + : 0, + ) }); } } diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/household_location.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/household_location.dart index 87d9c9642..ef237cd63 100644 --- a/packages/registration_delivery/lib/pages/beneficiary_registration/household_location.dart +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/household_location.dart @@ -1,5 +1,7 @@ import 'package:auto_route/auto_route.dart'; import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/text_block.dart'; +import 'package:digit_components/widgets/digit_sync_dialog.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:digit_data_model/models/entities/address_type.dart'; import 'package:flutter/material.dart'; @@ -25,11 +27,10 @@ class HouseholdLocationPage extends LocalizedStatefulWidget { }); @override - State createState() => _HouseholdLocationPageState(); + State createState() => HouseholdLocationPageState(); } -class _HouseholdLocationPageState - extends LocalizedState { +class HouseholdLocationPageState extends LocalizedState { static const _administrationAreaKey = 'administrationArea'; static const _addressLine1Key = 'addressLine1'; static const _addressLine2Key = 'addressLine2'; @@ -40,6 +41,27 @@ class _HouseholdLocationPageState static const _accuracyKey = 'accuracy'; static const maxLength = 64; + @override + void initState() { + final regState = context.read().state; + context.read().add(const LoadLocationEvent()); + regState.maybeMap( + orElse: () => false, + editHousehold: (value) => false, + create: (value) { + WidgetsBinding.instance.addPostFrameCallback((_) { + // Show the dialog after the first frame is built + DigitComponentsUtils().showLocationCapturingDialog( + context, + localizations.translate(i18.common.locationCapturing), + DigitSyncDialogType.inProgress, + ); + }); + return true; + }); + super.initState(); + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -47,306 +69,326 @@ class _HouseholdLocationPageState final router = context.router; return Scaffold( - body: ReactiveFormBuilder( - form: () => buildForm(bloc.state), - builder: (_, form, __) => BlocListener( - listener: (context, locationState) { - final lat = locationState.latitude; - final lng = locationState.longitude; - final accuracy = locationState.accuracy; - - form.control(_latKey).value ??= lat; - form.control(_lngKey).value ??= lng; - form.control(_accuracyKey).value ??= accuracy; - }, - listenWhen: (previous, current) { - final lat = form.control(_latKey).value; - final lng = form.control(_lngKey).value; - final accuracy = form.control(_accuracyKey).value; + body: BlocBuilder(builder: (context, registrationState) { + return ReactiveFormBuilder( + form: () => buildForm(bloc.state), + builder: (_, form, __) => BlocListener( + listener: (context, locationState) { + registrationState.maybeMap( + orElse: () => false, + create: (value) { + if (locationState.accuracy != null) { + //Hide the dialog after 1 seconds + Future.delayed(const Duration(seconds: 1), () { + DigitComponentsUtils().hideLocationDialog(context); + }); + } + }); + if (locationState.accuracy != null) { + final lat = locationState.latitude; + final lng = locationState.longitude; + final accuracy = locationState.accuracy; - return lat != null || lng != null || accuracy != null - ? false - : true; - }, - child: BlocBuilder( - builder: (context, registrationState) { - return ScrollableContent( - enableFixedButton: true, - header: const Column( - children: [ - BackNavigationHelpHeaderWidget( - showcaseButton: ShowcaseButton(), - showHelp: false, - ), - ], - ), - footer: DigitCard( - margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), - padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), - child: BlocBuilder( - builder: (context, locationState) { - return DigitElevatedButton( - onPressed: () { - form.markAllAsTouched(); - if (!form.valid) return; + form.control(_latKey).value ??= lat; + form.control(_lngKey).value ??= lng; + form.control(_accuracyKey).value ??= accuracy; + } + }, + listenWhen: (previous, current) { + final lat = form.control(_latKey).value; + final lng = form.control(_lngKey).value; + final accuracy = form.control(_accuracyKey).value; - final addressLine1 = - form.control(_addressLine1Key).value as String?; - final addressLine2 = - form.control(_addressLine2Key).value as String?; - final landmark = - form.control(_landmarkKey).value as String?; - final postalCode = - form.control(_postalCodeKey).value as String?; + return lat != null || lng != null || accuracy != null + ? false + : true; + }, + child: ScrollableContent( + enableFixedButton: true, + header: const Column( + children: [ + BackNavigationHelpHeaderWidget( + showcaseButton: ShowcaseButton(), + showHelp: false, + ), + ], + ), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: BlocBuilder( + builder: (context, locationState) { + return DigitElevatedButton( + onPressed: () { + form.markAllAsTouched(); + if (!form.valid) return; - registrationState.maybeWhen( - orElse: () { - return; - }, - create: ( - address, - householdModel, - individualModel, - registrationDate, - searchQuery, - loading, - isHeadOfHousehold, - ) { - var addressModel = AddressModel( - addressLine1: addressLine1 != null && - addressLine1.trim().isNotEmpty - ? addressLine1 - : null, - addressLine2: addressLine2 != null && - addressLine2.trim().isNotEmpty - ? addressLine2 - : null, - landmark: landmark != null && - landmark.trim().isNotEmpty - ? landmark - : null, - pincode: postalCode != null && - postalCode.trim().isNotEmpty - ? postalCode - : null, - type: AddressType.correspondence, - latitude: form.control(_latKey).value ?? - locationState.latitude, - longitude: form.control(_lngKey).value ?? - locationState.longitude, - locationAccuracy: - form.control(_accuracyKey).value ?? - locationState.accuracy, - locality: LocalityModel( - code: RegistrationDeliverySingleton() - .boundary! - .code!, - name: RegistrationDeliverySingleton() - .boundary! - .name, - ), - tenantId: - RegistrationDeliverySingleton().tenantId, - rowVersion: 1, - auditDetails: AuditDetails( - createdBy: RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context.millisecondsSinceEpoch(), - ), - clientAuditDetails: ClientAuditDetails( - createdBy: RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context.millisecondsSinceEpoch(), - lastModifiedBy: - RegistrationDeliverySingleton() - .loggedInUserUuid, - lastModifiedTime: - context.millisecondsSinceEpoch(), - ), - ); + final addressLine1 = + form.control(_addressLine1Key).value as String?; + final addressLine2 = + form.control(_addressLine2Key).value as String?; + final landmark = + form.control(_landmarkKey).value as String?; + final postalCode = + form.control(_postalCodeKey).value as String?; + registrationState.maybeWhen( + orElse: () { + return; + }, + create: ( + address, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold, + ) { + var addressModel = AddressModel( + addressLine1: addressLine1 != null && + addressLine1.trim().isNotEmpty + ? addressLine1 + : null, + addressLine2: addressLine2 != null && + addressLine2.trim().isNotEmpty + ? addressLine2 + : null, + landmark: + landmark != null && landmark.trim().isNotEmpty + ? landmark + : null, + pincode: postalCode != null && + postalCode.trim().isNotEmpty + ? postalCode + : null, + type: AddressType.correspondence, + latitude: form.control(_latKey).value ?? + locationState.latitude, + longitude: form.control(_lngKey).value ?? + locationState.longitude, + locationAccuracy: + form.control(_accuracyKey).value ?? + locationState.accuracy, + locality: LocalityModel( + code: RegistrationDeliverySingleton() + .boundary! + .code!, + name: RegistrationDeliverySingleton() + .boundary! + .name, + ), + tenantId: + RegistrationDeliverySingleton().tenantId, + rowVersion: 1, + auditDetails: AuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + ), + clientAuditDetails: ClientAuditDetails( + createdBy: RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context.millisecondsSinceEpoch(), + lastModifiedBy: RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: + context.millisecondsSinceEpoch(), + ), + ); - bloc.add( - BeneficiaryRegistrationSaveAddressEvent( - addressModel, - ), - ); - router.push(HouseHoldDetailsRoute()); - }, - editHousehold: ( - address, - householdModel, - individuals, - registrationDate, - projectBeneficiaryModel, - loading, - ) { - var addressModel = address.copyWith( - addressLine1: addressLine1 != null && - addressLine1.trim().isNotEmpty - ? addressLine1 - : null, - addressLine2: addressLine2 != null && - addressLine2.trim().isNotEmpty - ? addressLine2 - : null, - landmark: landmark != null && - landmark.trim().isNotEmpty - ? landmark - : null, - locality: address.locality, - pincode: postalCode != null && - postalCode.trim().isNotEmpty - ? postalCode - : null, - type: AddressType.correspondence, - latitude: form.control(_latKey).value, - longitude: form.control(_lngKey).value, - locationAccuracy: - form.control(_accuracyKey).value, - ); - // TODO [Linking of Voucher for Household based project need to be handled] + bloc.add( + BeneficiaryRegistrationSaveAddressEvent( + addressModel, + ), + ); + router.push(HouseDetailsRoute()); + }, + editHousehold: ( + address, + householdModel, + individuals, + registrationDate, + projectBeneficiaryModel, + loading, + headOfHousehold, + ) { + var addressModel = address.copyWith( + addressLine1: addressLine1 != null && + addressLine1.trim().isNotEmpty + ? addressLine1 + : null, + addressLine2: addressLine2 != null && + addressLine2.trim().isNotEmpty + ? addressLine2 + : null, + landmark: + landmark != null && landmark.trim().isNotEmpty + ? landmark + : null, + locality: address.locality, + pincode: postalCode != null && + postalCode.trim().isNotEmpty + ? postalCode + : null, + type: AddressType.correspondence, + latitude: form.control(_latKey).value, + longitude: form.control(_lngKey).value, + locationAccuracy: + form.control(_accuracyKey).value, + ); + // TODO [Linking of Voucher for Household based project need to be handled] - bloc.add( - BeneficiaryRegistrationSaveAddressEvent( - addressModel, - ), - ); - router.push(HouseHoldDetailsRoute()); - }, - ); - }, - child: Center( - child: Text( - localizations.translate( - i18.householdLocation.actionLabel, - ), + bloc.add( + BeneficiaryRegistrationSaveAddressEvent( + addressModel, + ), + ); + router.push(HouseDetailsRoute()); + }, + ); + }, + child: Center( + child: Text( + localizations.translate( + i18.householdLocation.actionLabel, ), ), - ); - }, - ), + ), + ); + }, ), - slivers: [ - SliverToBoxAdapter( - child: DigitCard( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - Padding( - padding: - const EdgeInsets.fromLTRB(0, 0, 0, kPadding), - child: Text( - localizations.translate( + ), + slivers: [ + SliverToBoxAdapter( + child: DigitCard( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + TextBlock( + padding: const EdgeInsets.only(top: kPadding), + heading: localizations.translate( + i18.householdLocation.householdLocationLabelText, + ), + headingStyle: theme.textTheme.displayMedium, + body: localizations.translate( + i18.householdLocation + .householdLocationDescriptionText, + )), + Column(children: [ + householdLocationShowcaseData.administrativeArea + .buildWith( + child: DigitTextFormField( + formControlName: _administrationAreaKey, + label: localizations.translate( i18.householdLocation - .householdLocationLabelText, + .administrationAreaFormLabel, ), - style: theme.textTheme.displayMedium, + readOnly: true, + validationMessages: { + 'required': (_) => localizations.translate( + i18.householdLocation + .administrationAreaRequiredValidation, + ), + }, ), ), - Column(children: [ - householdLocationShowcaseData.administrativeArea - .buildWith( - child: DigitTextFormField( - formControlName: _administrationAreaKey, - label: localizations.translate( - i18.householdLocation - .administrationAreaFormLabel, - ), - readOnly: true, - isRequired: true, - validationMessages: { - 'required': (_) => localizations.translate( - i18.householdLocation - .administrationAreaRequiredValidation, - ), - }, + householdLocationShowcaseData.gpsAccuracy.buildWith( + child: DigitTextFormField( + formControlName: _accuracyKey, + label: localizations.translate( + i18.householdLocation.gpsAccuracyLabel, ), + readOnly: true, + validationMessages: { + 'required': (_) => localizations.translate( + i18.common.corecommonRequired, + ), + }, ), - householdLocationShowcaseData.addressLine1 - .buildWith( - child: DigitTextFormField( - formControlName: _addressLine1Key, - label: localizations.translate( - i18.householdLocation - .householdAddressLine1LabelText, - ), - validationMessages: { - 'required': (_) => localizations.translate( - i18.common.min2CharsRequired, - ), - 'maxLength': (object) => localizations - .translate(i18.common.maxCharsRequired) - .replaceAll('{}', maxLength.toString()), - }, + ), + householdLocationShowcaseData.addressLine1.buildWith( + child: DigitTextFormField( + formControlName: _addressLine1Key, + label: localizations.translate( + i18.householdLocation + .householdAddressLine1LabelText, ), + validationMessages: { + 'required': (_) => localizations.translate( + i18.common.min2CharsRequired, + ), + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', maxLength.toString()), + }, ), - householdLocationShowcaseData.addressLine2 - .buildWith( - child: DigitTextFormField( - formControlName: _addressLine2Key, - label: localizations.translate( - i18.householdLocation - .householdAddressLine2LabelText, - ), - validationMessages: { - 'required': (_) => localizations.translate( - i18.common.min2CharsRequired, - ), - 'maxLength': (object) => localizations - .translate(i18.common.maxCharsRequired) - .replaceAll('{}', maxLength.toString()), - }, + ), + householdLocationShowcaseData.addressLine2.buildWith( + child: DigitTextFormField( + formControlName: _addressLine2Key, + label: localizations.translate( + i18.householdLocation + .householdAddressLine2LabelText, ), + validationMessages: { + 'required': (_) => localizations.translate( + i18.common.min2CharsRequired, + ), + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', maxLength.toString()), + }, ), - householdLocationShowcaseData.landmark.buildWith( - child: DigitTextFormField( - formControlName: _landmarkKey, - label: localizations.translate( - i18.householdLocation.landmarkFormLabel, - ), - validationMessages: { - 'required': (_) => localizations.translate( - i18.common.min2CharsRequired, - ), - 'maxLength': (object) => localizations - .translate(i18.common.maxCharsRequired) - .replaceAll('{}', maxLength.toString()), - }, + ), + householdLocationShowcaseData.landmark.buildWith( + child: DigitTextFormField( + formControlName: _landmarkKey, + label: localizations.translate( + i18.householdLocation.landmarkFormLabel, ), + validationMessages: { + 'required': (_) => localizations.translate( + i18.common.min2CharsRequired, + ), + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', maxLength.toString()), + }, ), - householdLocationShowcaseData.postalCode.buildWith( - child: DigitTextFormField( - keyboardType: TextInputType.text, - formControlName: _postalCodeKey, - label: localizations.translate( - i18.householdLocation.postalCodeFormLabel, - ), - validationMessages: { - 'required': (_) => localizations.translate( - i18.common.min2CharsRequired, - ), - 'maxLength': (object) => localizations - .translate(i18.common.maxCharsRequired) - .replaceAll('{}', '6'), - }, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - ], + ), + householdLocationShowcaseData.postalCode.buildWith( + child: DigitTextFormField( + keyboardType: TextInputType.text, + formControlName: _postalCodeKey, + label: localizations.translate( + i18.householdLocation.postalCodeFormLabel, ), + validationMessages: { + 'required': (_) => localizations.translate( + i18.common.min2CharsRequired, + ), + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', '6'), + }, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], ), - ]), - ], - ), + ), + ]), + ], ), ), - ], - ); - }, + ), + ], + ), ), - ), - ), + ); + }), ); } @@ -358,7 +400,7 @@ class _HouseholdLocationPageState return fb.group({ _administrationAreaKey: FormControl( value: localizations.translate( - RegistrationDeliverySingleton().boundary!.code.toString()), + RegistrationDeliverySingleton().boundary!.name.toString()), validators: [Validators.required], ), _addressLine1Key: diff --git a/packages/registration_delivery/lib/pages/beneficiary_registration/individual_details.dart b/packages/registration_delivery/lib/pages/beneficiary_registration/individual_details.dart index 19dfa02a9..b8e28a752 100644 --- a/packages/registration_delivery/lib/pages/beneficiary_registration/individual_details.dart +++ b/packages/registration_delivery/lib/pages/beneficiary_registration/individual_details.dart @@ -4,6 +4,7 @@ import 'package:digit_components/digit_components.dart'; import 'package:digit_components/utils/date_utils.dart'; import 'package:digit_components/widgets/atoms/digit_checkbox.dart'; import 'package:digit_components/widgets/atoms/digit_toaster.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; import 'package:digit_components/widgets/digit_dob_picker.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:digit_scanner/blocs/scanner.dart'; @@ -13,12 +14,12 @@ import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:intl/intl.dart'; import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/blocs/search_households/search_households.dart'; import 'package:registration_delivery/utils/constants.dart'; import 'package:registration_delivery/utils/extensions/extensions.dart'; import '../../blocs/beneficiary_registration/beneficiary_registration.dart'; -import '../../blocs/search_households/search_bloc_common_wrapper.dart'; -import '../../blocs/search_households/search_households.dart'; +import '../../blocs/household_overview/household_overview.dart'; import '../../router/registration_delivery_router.gm.dart'; import '../../utils/i18_key_constants.dart' as i18; import '../../utils/utils.dart'; @@ -38,11 +39,10 @@ class IndividualDetailsPage extends LocalizedStatefulWidget { }); @override - State createState() => _IndividualDetailsPageState(); + State createState() => IndividualDetailsPageState(); } -class _IndividualDetailsPageState - extends LocalizedState { +class IndividualDetailsPageState extends LocalizedState { static const _individualNameKey = 'individualName'; static const _idTypeKey = 'idType'; static const _idNumberKey = 'idNumber'; @@ -70,25 +70,28 @@ class _IndividualDetailsPageState state.mapOrNull( persisted: (value) { if (value.navigateToRoot) { - (router.parent() as StackRouter).maybePop(); - } else { - router.popUntil((route) => - route.settings.name == SearchBeneficiaryRoute.name); - context.read().searchHouseholdsBloc.add( - SearchHouseholdsEvent.searchByHousehold( - householdModel: value.householdModel, - projectId: RegistrationDeliverySingleton().projectId!, - isProximityEnabled: false, - ), - ); - router.push(BeneficiaryAcknowledgementRoute( - enableViewHousehold: true, - )); + final overviewBloc = context.read(); + + overviewBloc.add( + HouseholdOverviewReloadEvent( + projectId: + RegistrationDeliverySingleton().projectId.toString(), + projectBeneficiaryType: + RegistrationDeliverySingleton().beneficiaryType ?? + BeneficiaryType.household, + ), + ); + HouseholdMemberWrapper memberWrapper = + overviewBloc.state.householdMemberWrapper; + final route = router.parent() as StackRouter; + route.popUntilRouteWithName(SearchBeneficiaryRoute.name); + route.push(BeneficiaryWrapperRoute(wrapper: memberWrapper)); } }, ); }, builder: (context, state) { + // context. return ScrollableContent( enableFixedButton: true, header: const Column(children: [ @@ -104,250 +107,206 @@ class _IndividualDetailsPageState valueListenable: clickedStatus, builder: (context, bool isClicked, _) { return DigitElevatedButton( - onPressed: isClicked - ? null - : () async { - final age = DigitDateUtils.calculateAge( - form.control(_dobKey).value as DateTime?, - ); - if ((age.years == 0 && age.months == 0) || - age.years >= 150 && age.months > 0) { - form.control(_dobKey).setErrors({'': true}); - } - if (form.control(_idTypeKey).value == null) { - form.control(_idTypeKey).setErrors({'': true}); - } - if (form.control(_genderKey).value == null) { - form.control(_genderKey).setErrors({'': true}); - } - final userId = RegistrationDeliverySingleton() - .loggedInUserUuid; - final projectId = - RegistrationDeliverySingleton().projectId; - form.markAllAsTouched(); - if (!form.valid) return; - FocusManager.instance.primaryFocus?.unfocus(); + onPressed: () async { + final age = DigitDateUtils.calculateAge( + form.control(_dobKey).value as DateTime?, + ); + if ((age.years == 0 && age.months == 0) || + age.years >= 150 && age.months > 0) { + form.control(_dobKey).setErrors({'': true}); + } + if (form.control(_idTypeKey).value == null) { + form.control(_idTypeKey).setErrors({'': true}); + } + if (form.control(_genderKey).value == null) { + setState(() { + form.control(_genderKey).setErrors({'': true}); + }); + } + final userId = + RegistrationDeliverySingleton().loggedInUserUuid; + final projectId = + RegistrationDeliverySingleton().projectId; + form.markAllAsTouched(); + if (!form.valid) return; + FocusManager.instance.primaryFocus?.unfocus(); - state.maybeWhen( - orElse: () { - return; - }, - create: ( - addressModel, - householdModel, - individualModel, - registrationDate, - searchQuery, - loading, - isHeadOfHousehold, - ) async { - final individual = _getIndividualModel( - context, - form: form, - oldIndividual: null, - ); + state.maybeWhen( + orElse: () { + return; + }, + create: ( + addressModel, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + searchQuery, + loading, + isHeadOfHousehold, + ) async { + final individual = _getIndividualModel( + context, + form: form, + oldIndividual: null, + ); - final boundary = - RegistrationDeliverySingleton().boundary; + final boundary = + RegistrationDeliverySingleton().boundary; - bloc.add( - BeneficiaryRegistrationSaveIndividualDetailsEvent( - model: individual, - isHeadOfHousehold: - widget.isHeadOfHousehold, - ), - ); - final scannerBloc = - context.read(); - - if (scannerBloc.state.duplicate) { - DigitToast.show( - context, - options: DigitToastOptions( - localizations.translate( - i18.deliverIntervention - .resourceAlreadyScanned, - ), - true, - theme, - ), - ); - } else { - final submit = await DigitDialog.show( - context, - options: DigitDialogOptions( - titleText: localizations.translate( - i18.deliverIntervention.dialogTitle, - ), - contentText: localizations.translate( - i18.deliverIntervention.dialogContent, - ), - primaryAction: DigitDialogActions( - label: localizations.translate( - i18.common.coreCommonSubmit, - ), - action: (context) { - clickedStatus.value = true; - Navigator.of( - context, - rootNavigator: true, - ).pop(true); - }, - ), - secondaryAction: DigitDialogActions( - label: localizations.translate( - i18.common.coreCommonCancel, - ), - action: (context) => Navigator.of( - context, - rootNavigator: true, - ).pop(false), - ), - ), - ); - - if (submit ?? false) { - if (context.mounted) { - final scannerBloc = - context.read(); + bloc.add( + BeneficiaryRegistrationSaveIndividualDetailsEvent( + model: individual, + isHeadOfHousehold: widget.isHeadOfHousehold, + ), + ); + final scannerBloc = + context.read(); - bloc.add( - BeneficiaryRegistrationCreateEvent( - projectId: projectId!, - userUuid: userId!, - boundary: boundary!, - tag: scannerBloc - .state.qrCodes.isNotEmpty - ? scannerBloc - .state.qrCodes.first - : null, - ), - ); - } - } - } - }, - editIndividual: ( - householdModel, - individualModel, - addressModel, - projectBeneficiaryModel, - loading, - ) { - final scannerBloc = - context.read(); - final individual = _getIndividualModel( - context, - form: form, - oldIndividual: individualModel, - ); - final tag = - scannerBloc.state.qrCodes.isNotEmpty - ? scannerBloc.state.qrCodes.first - : null; + if (scannerBloc.state.duplicate) { + DigitToast.show( + context, + options: DigitToastOptions( + localizations.translate( + i18.deliverIntervention + .resourceAlreadyScanned, + ), + true, + theme, + ), + ); + } else { + clickedStatus.value = true; + final scannerBloc = + context.read(); + bloc.add( + BeneficiaryRegistrationSummaryEvent( + projectId: projectId!, + userUuid: userId!, + boundary: boundary!, + tag: scannerBloc.state.qrCodes.isNotEmpty + ? scannerBloc.state.qrCodes.first + : null, + ), + ); + router.push(SummaryRoute()); + } + }, + editIndividual: ( + householdModel, + individualModel, + addressModel, + projectBeneficiaryModel, + loading, + ) { + final scannerBloc = + context.read(); + final individual = _getIndividualModel( + context, + form: form, + oldIndividual: individualModel, + ); + final tag = scannerBloc.state.qrCodes.isNotEmpty + ? scannerBloc.state.qrCodes.first + : null; - if (tag != null && - tag != projectBeneficiaryModel?.tag && - scannerBloc.state.duplicate) { - DigitToast.show( - context, - options: DigitToastOptions( - localizations.translate( - i18.deliverIntervention - .resourceAlreadyScanned, - ), - true, - theme, - ), - ); - } else { - bloc.add( - BeneficiaryRegistrationUpdateIndividualDetailsEvent( - addressModel: addressModel, - householdModel: householdModel, - model: individual.copyWith( - clientAuditDetails: (individual - .clientAuditDetails - ?.createdBy != - null && - individual.clientAuditDetails - ?.createdTime != - null) - ? ClientAuditDetails( - createdBy: individual - .clientAuditDetails! - .createdBy, - createdTime: individual - .clientAuditDetails! - .createdTime, - lastModifiedBy: - RegistrationDeliverySingleton() - .loggedInUserUuid, - lastModifiedTime: context - .millisecondsSinceEpoch(), - ) - : null, - ), - tag: scannerBloc - .state.qrCodes.isNotEmpty - ? scannerBloc.state.qrCodes.first - : null, - ), - ); - } - }, - addMember: ( - addressModel, - householdModel, - loading, - ) { - final individual = _getIndividualModel( - context, - form: form, - ); + if (tag != null && + tag != projectBeneficiaryModel?.tag && + scannerBloc.state.duplicate) { + DigitToast.show( + context, + options: DigitToastOptions( + localizations.translate( + i18.deliverIntervention + .resourceAlreadyScanned, + ), + true, + theme, + ), + ); + } else { + bloc.add( + BeneficiaryRegistrationUpdateIndividualDetailsEvent( + addressModel: addressModel, + householdModel: householdModel, + model: individual.copyWith( + clientAuditDetails: (individual + .clientAuditDetails + ?.createdBy != + null && + individual.clientAuditDetails + ?.createdTime != + null) + ? ClientAuditDetails( + createdBy: individual + .clientAuditDetails!.createdBy, + createdTime: individual + .clientAuditDetails! + .createdTime, + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: context + .millisecondsSinceEpoch(), + ) + : null, + ), + tag: scannerBloc.state.qrCodes.isNotEmpty + ? scannerBloc.state.qrCodes.first + : null, + ), + ); + } + }, + addMember: ( + addressModel, + householdModel, + loading, + ) { + final individual = _getIndividualModel( + context, + form: form, + ); - if (context.mounted) { - final scannerBloc = - context.read(); + if (context.mounted) { + final scannerBloc = + context.read(); - if (scannerBloc.state.duplicate) { - DigitToast.show( - context, - options: DigitToastOptions( - localizations.translate( - i18.deliverIntervention - .resourceAlreadyScanned, - ), - true, - theme, - ), - ); - } else { - bloc.add( - BeneficiaryRegistrationAddMemberEvent( - beneficiaryType: - RegistrationDeliverySingleton() - .beneficiaryType!, - householdModel: householdModel, - individualModel: individual, - addressModel: addressModel, - userUuid: - RegistrationDeliverySingleton() - .loggedInUserUuid!, - projectId: - RegistrationDeliverySingleton() - .projectId!, - tag: scannerBloc - .state.qrCodes.isNotEmpty - ? scannerBloc.state.qrCodes.first - : null, - ), - ); - } - } - }, - ); - }, + if (scannerBloc.state.duplicate) { + DigitToast.show( + context, + options: DigitToastOptions( + localizations.translate( + i18.deliverIntervention + .resourceAlreadyScanned, + ), + true, + theme, + ), + ); + } else { + bloc.add( + BeneficiaryRegistrationAddMemberEvent( + beneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType!, + householdModel: householdModel, + individualModel: individual, + addressModel: addressModel, + userUuid: RegistrationDeliverySingleton() + .loggedInUserUuid!, + projectId: RegistrationDeliverySingleton() + .projectId!, + tag: scannerBloc.state.qrCodes.isNotEmpty + ? scannerBloc.state.qrCodes.first + : null, + ), + ); + } + } + }, + ); + }, child: Center( child: Text( state.mapOrNull( @@ -378,200 +337,211 @@ class _IndividualDetailsPageState style: theme.textTheme.displayMedium, ), ), - Column( - children: [ - individualDetailsShowcaseData.nameOfIndividual - .buildWith( - child: DigitTextFormField( - formControlName: 'individualName', - label: localizations.translate( - i18.individualDetails.nameLabelText, - ), - isRequired: true, - validationMessages: { - 'required': (object) => - localizations.translate( - '${i18.individualDetails.nameLabelText}_IS_REQUIRED', - ), - 'maxLength': (object) => localizations - .translate(i18.common.maxCharsRequired) - .replaceAll('{}', maxLength.toString()), - }, - ), - ), - Offstage( - offstage: !widget.isHeadOfHousehold, - child: DigitCheckbox( - label: localizations.translate( - i18.individualDetails.checkboxLabelText, - ), - value: widget.isHeadOfHousehold, + Column(children: [ + individualDetailsShowcaseData.nameOfIndividual + .buildWith( + child: DigitTextFormField( + formControlName: _individualNameKey, + label: localizations.translate( + i18.individualDetails.nameLabelText, ), + isRequired: true, + validationMessages: { + 'required': (object) => localizations.translate( + '${i18.individualDetails.nameLabelText}_IS_REQUIRED', + ), + 'maxLength': (object) => localizations + .translate(i18.common.maxCharsRequired) + .replaceAll('{}', maxLength.toString()), + }, ), - DigitReactiveSearchDropdown( + ), + Offstage( + offstage: !widget.isHeadOfHousehold, + child: DigitCheckbox( label: localizations.translate( - i18.individualDetails.idTypeLabelText, + i18.individualDetails.checkboxLabelText, ), - form: form, - menuItems: RegistrationDeliverySingleton() - .idTypeOptions! - .map( - (e) { - return e; - }, - ).toList(), - formControlName: _idTypeKey, - valueMapper: (value) { - return localizations.translate(value); - }, - onSelected: (value) { - setState(() { - if (value == 'DEFAULT') { - form.control(_idNumberKey).value = - IdGen.i.identifier.toString(); - } else { - form.control(_idNumberKey).value = null; - } - }); + value: widget.isHeadOfHousehold, + ), + ), + DigitReactiveSearchDropdown( + label: localizations.translate( + i18.individualDetails.idTypeLabelText, + ), + form: form, + menuItems: RegistrationDeliverySingleton() + .idTypeOptions! + .map( + (e) { + return e; }, - isRequired: true, - validationMessage: localizations.translate( - i18.common.corecommonRequired, - ), - emptyText: localizations - .translate(i18.common.noMatchFound), + ).toList(), + formControlName: _idTypeKey, + valueMapper: (value) { + return localizations.translate(value); + }, + onSelected: (value) { + setState(() { + if (value == 'DEFAULT') { + form.control(_idNumberKey).value = + IdGen.i.identifier.toString(); + } else { + form.control(_idNumberKey).value = null; + } + }); + }, + isRequired: true, + validationMessage: localizations.translate( + i18.common.corecommonRequired, ), - if (form.control(_idTypeKey).value != 'DEFAULT') - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - ReactiveFormConsumer( - builder: (context, formGroup, child) { - return DigitTextFormField( - readOnly: - form.control(_idTypeKey).value == - 'DEFAULT', - isRequired: form - .control(_idNumberKey) - .validators - .isNotEmpty, - formControlName: _idNumberKey, - label: localizations.translate( - i18.individualDetails - .idNumberLabelText, - ), - validationMessages: { - 'required': (object) => - localizations.translate( - '${i18.individualDetails.idNumberLabelText}_IS_REQUIRED', - ), - }, - padding: const EdgeInsets.only( - top: kPadding * 2, - left: kPadding / 2, - right: kPadding / 2, - ), - ); - }, - ), - const SizedBox(height: 4), - ], + emptyText: localizations + .translate(i18.common.noMatchFound), + ), + if (form.control(_idTypeKey).value != 'DEFAULT') + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ReactiveFormConsumer( + builder: (context, formGroup, child) { + return DigitTextFormField( + readOnly: + form.control(_idTypeKey).value == + 'DEFAULT', + isRequired: form + .control(_idNumberKey) + .validators + .isNotEmpty, + formControlName: _idNumberKey, + label: localizations.translate( + i18.individualDetails.idNumberLabelText, + ), + validationMessages: { + 'required': (object) => + localizations.translate( + '${i18.individualDetails.idNumberLabelText}_IS_REQUIRED', + ), + }, + padding: const EdgeInsets.only( + top: kPadding * 2, + left: kPadding / 2, + right: kPadding / 2, + ), + ); + }, + ), + const SizedBox(height: 4), + ], + ), + if (form.control(_idTypeKey).value == 'DEFAULT') + const SizedBox( + height: kPadding, + ), + individualDetailsShowcaseData.dateOfBirth.buildWith( + child: DigitDobPicker( + datePickerFormControl: _dobKey, + datePickerLabel: localizations.translate( + i18.individualDetails.dobLabelText, ), - if (form.control(_idTypeKey).value == 'DEFAULT') - const SizedBox( - height: kPadding, + ageFieldLabel: localizations.translate( + i18.individualDetails.ageLabelText, ), - individualDetailsShowcaseData.dateOfBirth.buildWith( - child: DigitDobPicker( - datePickerFormControl: _dobKey, - datePickerLabel: localizations.translate( - i18.individualDetails.dobLabelText, - ), - ageFieldLabel: localizations.translate( - i18.individualDetails.ageLabelText, - ), - yearsHintLabel: localizations.translate( - i18.individualDetails.yearsHintText, - ), - monthsHintLabel: localizations.translate( - i18.individualDetails.monthsHintText, - ), - separatorLabel: localizations.translate( - i18.individualDetails.separatorLabelText, - ), - yearsAndMonthsErrMsg: localizations.translate( - i18.individualDetails.yearsAndMonthsErrorText, - ), - initialDate: before150Years, - onChangeOfFormControl: (formControl) { - // Handle changes to the control's value here - final value = formControl.value; - if (value == null) { + yearsHintLabel: localizations.translate( + i18.individualDetails.yearsHintText, + ), + monthsHintLabel: localizations.translate( + i18.individualDetails.monthsHintText, + ), + separatorLabel: localizations.translate( + i18.individualDetails.separatorLabelText, + ), + yearsAndMonthsErrMsg: localizations.translate( + i18.individualDetails.yearsAndMonthsErrorText, + ), + initialDate: before150Years, + onChangeOfFormControl: (formControl) { + // Handle changes to the control's value here + final value = formControl.value; + if (value == null) { + formControl.setErrors({'': true}); + } else { + DigitDOBAge age = + DigitDateUtils.calculateAge(value); + if ((age.years == 0 && age.months == 0) || + age.months > 11 || + (age.years >= 150 && age.months >= 0)) { formControl.setErrors({'': true}); } else { - DigitDOBAge age = - DigitDateUtils.calculateAge(value); - if ((age.years == 0 && age.months == 0) || - age.months > 11 || - (age.years >= 150 && age.months >= 0)) { - formControl.setErrors({'': true}); - } else { - formControl.removeError(''); - } + formControl.removeError(''); } - }, - cancelText: localizations - .translate(i18.common.coreCommonCancel), - confirmText: localizations - .translate(i18.common.coreCommonOk), - ), - ), - DigitReactiveSearchDropdown( - label: localizations.translate( - i18.individualDetails.genderLabelText, - ), - form: form, - menuItems: RegistrationDeliverySingleton() - .genderOptions! - .map( - (e) => e, - ) - .toList(), - formControlName: _genderKey, - valueMapper: (value) { - return localizations.translate(value); + } }, - isRequired: true, - validationMessage: localizations.translate( - i18.common.corecommonRequired, - ), - emptyText: localizations - .translate(i18.common.noMatchFound), + cancelText: localizations + .translate(i18.common.coreCommonCancel), + confirmText: localizations + .translate(i18.common.coreCommonOk), ), - individualDetailsShowcaseData.mobile.buildWith( - child: DigitTextFormField( - keyboardType: TextInputType.number, - formControlName: _mobileNumberKey, - maxLength: 10, - label: localizations.translate( - i18.individualDetails.mobileNumberLabelText, - ), - validationMessages: { - 'maxLength': (object) => - localizations.translate(i18 - .individualDetails - .mobileNumberLengthValidationMessage), - 'minLength': (object) => - localizations.translate(i18 - .individualDetails - .mobileNumberLengthValidationMessage), - }, - inputFormatters: [ - FilteringTextInputFormatter.digitsOnly, - ], - ), + ), + SelectionBox( + isRequired: true, + title: localizations.translate( + i18.individualDetails.genderLabelText, + ), + allowMultipleSelection: false, + width: 126, + initialSelection: + form.control(_genderKey).value != null + ? [form.control(_genderKey).value] + : [], + options: RegistrationDeliverySingleton() + .genderOptions! + .map( + (e) => e, + ) + .toList(), + onSelectionChanged: (value) { + setState(() { + if (value.isNotEmpty) { + form.control(_genderKey).value = value.first; + } else { + form.control(_genderKey).value = null; + setState(() { + form + .control(_genderKey) + .setErrors({'': true}); + }); + } + }); + }, + valueMapper: (value) { + return localizations.translate(value); + }, + errorMessage: form.control(_genderKey).hasErrors + ? localizations + .translate(i18.common.corecommonRequired) + : null, + ), + ]), + individualDetailsShowcaseData.mobile.buildWith( + child: DigitTextFormField( + keyboardType: TextInputType.number, + formControlName: _mobileNumberKey, + maxLength: 10, + label: localizations.translate( + i18.individualDetails.mobileNumberLabelText, ), - ], + validationMessages: { + 'maxLength': (object) => localizations.translate( + i18.individualDetails + .mobileNumberLengthValidationMessage), + 'minLength': (object) => localizations.translate( + i18.individualDetails + .mobileNumberLengthValidationMessage), + }, + inputFormatters: [ + FilteringTextInputFormatter.digitsOnly, + ], + ), ), const SizedBox(height: 16), if ((RegistrationDeliverySingleton().beneficiaryType == @@ -580,6 +550,9 @@ class _IndividualDetailsPageState (RegistrationDeliverySingleton().beneficiaryType == BeneficiaryType.individual)) BlocBuilder( + buildWhen: (p, c) { + return true; + }, builder: (context, state) => state .qrCodes.isNotEmpty ? Row( @@ -601,7 +574,7 @@ class _IndividualDetailsPageState child: Text( overflow: TextOverflow.ellipsis, localizations - .translate(state.qrCodes.first), + .translate(state.qrCodes.last), ), ), Padding( @@ -744,9 +717,10 @@ class _IndividualDetailsPageState ), ); + String? individualName = form.control(_individualNameKey).value as String?; individual = individual.copyWith( name: name.copyWith( - givenName: form.control(_individualNameKey).value, + givenName: individualName?.trim(), ), gender: form.control(_genderKey).value == null ? null @@ -775,6 +749,12 @@ class _IndividualDetailsPageState return value.individualModel; }, + create: (value) { + return value.individualModel; + }, + summary: (value) { + return value.individualModel; + }, ); final searchQuery = state.mapOrNull( @@ -790,7 +770,7 @@ class _IndividualDetailsPageState CustomValidator.requiredMin, Validators.maxLength(200), ], - value: individual?.name?.givenName ?? searchQuery, + value: individual?.name?.givenName ?? searchQuery?.trim(), ), _idTypeKey: FormControl( value: individual?.identifiers?.firstOrNull?.identifierType, diff --git a/packages/registration_delivery/lib/pages/reason_for_deletion.dart b/packages/registration_delivery/lib/pages/reason_for_deletion.dart index 4834166f6..e001b3627 100644 --- a/packages/registration_delivery/lib/pages/reason_for_deletion.dart +++ b/packages/registration_delivery/lib/pages/reason_for_deletion.dart @@ -22,11 +22,10 @@ class ReasonForDeletionPage extends LocalizedStatefulWidget { }); @override - State createState() => _ReasonForDeletionPageState(); + State createState() => ReasonForDeletionPageState(); } -class _ReasonForDeletionPageState - extends LocalizedState { +class ReasonForDeletionPageState extends LocalizedState { static const _reasonForDeletionKey = 'reasonForDeletion'; @override @@ -57,7 +56,7 @@ class _ReasonForDeletionPageState projectId: RegistrationDeliverySingleton() .projectId!, householdModel: - state.householdMemberWrapper.household, + state.householdMemberWrapper.household!, individualModel: state.selectedIndividual!, projectBeneficiaryType: RegistrationDeliverySingleton() @@ -69,12 +68,12 @@ class _ReasonForDeletionPageState projectId: RegistrationDeliverySingleton() .projectId!, householdModel: - state.householdMemberWrapper.household, + state.householdMemberWrapper.household!, members: - state.householdMemberWrapper.members, + state.householdMemberWrapper.members!, projectBeneficiaryModel: state .householdMemberWrapper - .projectBeneficiaries + .projectBeneficiaries! .first, projectBeneficiaryType: RegistrationDeliverySingleton() @@ -82,12 +81,39 @@ class _ReasonForDeletionPageState ), ); - context.router.maybePop(); + // context.router.maybePop(); + final parent = context.router.parent() as StackRouter; if (widget.isHousholdDelete) { (context.router.parent() as StackRouter).maybePop(); } - context.router.push(BeneficiaryAcknowledgementRoute()); + parent.popUntil((route) => + route.settings.name == + BeneficiaryWrapperRoute.name); + final reloadState = + context.read(); + Future.delayed( + const Duration(milliseconds: 500), + () { + reloadState.add( + HouseholdOverviewReloadEvent( + projectId: + RegistrationDeliverySingleton().projectId!, + projectBeneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType!, + ), + ); + }, + ).then( + (value) => context.router.push( + HouseholdAcknowledgementRoute( + enableViewHousehold: true, + ), + ), + ); + // context.router.push(HouseholdAcknowledgementRoute( + // enableViewHousehold: true)); } else { DigitToast.show(context, options: DigitToastOptions( diff --git a/packages/registration_delivery/lib/pages/registration_delivery_wrapper.dart b/packages/registration_delivery/lib/pages/registration_delivery_wrapper.dart index 7a9e9f82f..45a6b8e05 100644 --- a/packages/registration_delivery/lib/pages/registration_delivery_wrapper.dart +++ b/packages/registration_delivery/lib/pages/registration_delivery_wrapper.dart @@ -2,14 +2,16 @@ import 'package:auto_route/auto_route.dart'; import 'package:digit_data_model/models/entities/individual.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/blocs/search_households/household_global_seach.dart'; +import 'package:registration_delivery/blocs/search_households/individual_global_search.dart'; +import 'package:registration_delivery/data/repositories/local/individual_global_search.dart'; import 'package:registration_delivery/utils/extensions/extensions.dart'; import '../blocs/household_details/household_details.dart'; -import '../blocs/search_households/proximity_search.dart'; import '../blocs/search_households/search_bloc_common_wrapper.dart'; -import '../blocs/search_households/search_by_head.dart'; import '../blocs/search_households/search_households.dart'; import '../blocs/search_households/tag_by_search.dart'; +import '../data/repositories/local/household_global_search.dart'; import '../data/repositories/local/registration_delivery_address.dart'; import '../models/entities/household.dart'; import '../models/entities/household_member.dart'; @@ -31,123 +33,128 @@ class RegistrationDeliveryWrapperPage extends StatelessWidget { BlocProvider( create: (context) { return SearchHouseholdsBloc( - beneficiaryType: - RegistrationDeliverySingleton().beneficiaryType!, - userUid: RegistrationDeliverySingleton().loggedInUserUuid!, - projectId: RegistrationDeliverySingleton().projectId!, - addressRepository: - context.read(), - projectBeneficiary: context.repository(context), - householdMember: context.repository(context), - household: context - .repository(context), - individual: - context.repository( - context), - taskDataRepository: - context.repository(context), - sideEffectDataRepository: - context.repository( - context), - referralDataRepository: context - .repository(context), - ); + beneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!, + userUid: RegistrationDeliverySingleton().loggedInUserUuid!, + projectId: RegistrationDeliverySingleton().projectId!, + addressRepository: + context.read(), + projectBeneficiary: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(context), + householdMember: context.repository(context), + household: + context.repository( + context), + individual: + context.repository( + context), + taskDataRepository: + context.repository(context), + sideEffectDataRepository: context + .repository(context), + referralDataRepository: context.repository(context), + individualGlobalSearchRepository: context.read(), + houseHoldGlobalSearchRepository: context.read()); }, ), BlocProvider( create: (context) { - return SearchByHeadBloc( - beneficiaryType: - RegistrationDeliverySingleton().beneficiaryType!, - userUid: RegistrationDeliverySingleton().loggedInUserUuid!, - projectId: RegistrationDeliverySingleton().projectId!, - addressRepository: - context.read(), - projectBeneficiary: context.repository(context), - householdMember: context.repository(context), - household: context - .repository(context), - individual: - context.repository( - context), - taskDataRepository: - context.repository(context), - sideEffectDataRepository: - context.repository( - context), - referralDataRepository: context - .repository(context), - ); + return TagSearchBloc( + beneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!, + userUid: RegistrationDeliverySingleton().loggedInUserUuid!, + projectId: RegistrationDeliverySingleton().projectId!, + addressRepository: + context.read(), + projectBeneficiary: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(context), + householdMember: context.repository(context), + household: + context.repository( + context), + individual: + context.repository( + context), + taskDataRepository: + context.repository(context), + sideEffectDataRepository: context + .repository(context), + referralDataRepository: context.repository(context), + individualGlobalSearchRepository: context.read(), + houseHoldGlobalSearchRepository: context.read()); }, ), BlocProvider( create: (context) { - return ProximitySearchBloc( - beneficiaryType: - RegistrationDeliverySingleton().beneficiaryType!, - userUid: RegistrationDeliverySingleton().loggedInUserUuid!, - projectId: RegistrationDeliverySingleton().projectId!, - addressRepository: - context.read(), - projectBeneficiary: context.repository(context), - householdMember: context.repository(context), - household: context - .repository(context), - individual: - context.repository( - context), - taskDataRepository: - context.repository(context), - sideEffectDataRepository: - context.repository( - context), - referralDataRepository: context - .repository(context), - ); + return IndividualGlobalSearchBloc( + beneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!, + userUid: RegistrationDeliverySingleton().loggedInUserUuid!, + projectId: RegistrationDeliverySingleton().projectId!, + addressRepository: + context.read(), + projectBeneficiary: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(context), + householdMember: context.repository(context), + household: + context.repository( + context), + individual: + context.repository( + context), + taskDataRepository: + context.repository(context), + sideEffectDataRepository: context + .repository(context), + referralDataRepository: context.repository(context), + individualGlobalSearchRepository: context.read(), + houseHoldGlobalSearchRepository: context.read()); }, ), BlocProvider( create: (context) { - return TagSearchBloc( - beneficiaryType: - RegistrationDeliverySingleton().beneficiaryType!, - userUid: RegistrationDeliverySingleton().loggedInUserUuid!, - projectId: RegistrationDeliverySingleton().projectId!, - addressRepository: - context.read(), - projectBeneficiary: context.repository(context), - householdMember: context.repository(context), - household: context - .repository(context), - individual: - context.repository( - context), - taskDataRepository: - context.repository(context), - sideEffectDataRepository: - context.repository( - context), - referralDataRepository: context - .repository(context), - ); + return HouseHoldGlobalSearchBloc( + beneficiaryType: + RegistrationDeliverySingleton().beneficiaryType!, + userUid: RegistrationDeliverySingleton().loggedInUserUuid!, + projectId: RegistrationDeliverySingleton().projectId!, + addressRepository: + context.read(), + projectBeneficiary: context.repository< + ProjectBeneficiaryModel, + ProjectBeneficiarySearchModel>(context), + householdMember: context.repository(context), + household: + context.repository( + context), + individual: + context.repository( + context), + taskDataRepository: + context.repository(context), + sideEffectDataRepository: context + .repository(context), + referralDataRepository: context.repository(context), + individualGlobalSearchRepository: context.read(), + houseHoldGlobalSearchRepository: context.read()); }, ), BlocProvider( create: (context) { return SearchBlocWrapper( - searchHouseholdsBloc: context.read(), - searchByHeadBloc: context.read(), - proximitySearchBloc: context.read(), - tagSearchBloc: context.read(), - ); + searchHouseholdsBloc: context.read(), + tagSearchBloc: context.read(), + individualGlobalSearchBloc: + context.read(), + houseHoldGlobalSearchBloc: + context.read()); }, ), BlocProvider( diff --git a/packages/registration_delivery/lib/pages/search_beneficiary.dart b/packages/registration_delivery/lib/pages/search_beneficiary.dart index 95e7f3172..0cf5c4650 100644 --- a/packages/registration_delivery/lib/pages/search_beneficiary.dart +++ b/packages/registration_delivery/lib/pages/search_beneficiary.dart @@ -9,11 +9,14 @@ import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:registration_delivery/registration_delivery.dart'; import '../../utils/i18_key_constants.dart' as i18; +import '../models/entities/status.dart'; import '../router/registration_delivery_router.gm.dart'; +import '../utils/global_search_parameters.dart'; import '../utils/utils.dart'; import '../widgets/back_navigation_help_header.dart'; import '../widgets/beneficiary/view_beneficiary_card.dart'; import '../widgets/localized.dart'; +import '../widgets/status_filter/status_filter.dart'; @RoutePage() class SearchBeneficiaryPage extends LocalizedStatefulWidget { @@ -35,6 +38,7 @@ class _SearchBeneficiaryPageState double lat = 0.0; double long = 0.0; + List selectedFilters = []; SearchHouseholdsState searchHouseholdsState = const SearchHouseholdsState( loading: false, @@ -47,7 +51,7 @@ class _SearchBeneficiaryPageState void initState() { // Initialize the BlocWrapper with instances of SearchHouseholdsBloc, SearchMemberBloc, and ProximitySearchBloc blocWrapper = context.read(); - + context.read().add(const LoadLocationEvent()); // Listen to state changes blocWrapper.stateChanges.listen((state) { if (mounted) { @@ -62,7 +66,6 @@ class _SearchBeneficiaryPageState @override void dispose() { - blocWrapper.clearEvent(); super.dispose(); } @@ -76,35 +79,10 @@ class _SearchBeneficiaryPageState onNotification: (scrollNotification) { if (scrollNotification is ScrollUpdateNotification) { final metrics = scrollNotification.metrics; - if (metrics.atEdge && - isProximityEnabled && - searchController.text == '' && - metrics.pixels != 0) { - // [TODO: Handle the null check at Bloc level for Event parameters - blocWrapper.proximitySearchBloc - .add(SearchHouseholdsEvent.searchByProximity( - latitude: lat, - longititude: long, - projectId: RegistrationDeliverySingleton().projectId!, - maxRadius: RegistrationDeliverySingleton().maxRadius!, - offset: blocWrapper.proximitySearchBloc.state.offset, - limit: blocWrapper.proximitySearchBloc.state.limit, - )); - } else if (metrics.atEdge && - searchController.text != '' && - metrics.pixels != 0) { - blocWrapper.searchByHeadBloc - .add(SearchHouseholdsEvent.searchByHouseholdHead( - searchText: searchController.text, - projectId: RegistrationDeliverySingleton().projectId!, - isProximityEnabled: isProximityEnabled, - offset: blocWrapper.searchByHeadBloc.state.offset, - limit: blocWrapper.searchByHeadBloc.state.limit, - )); + if (metrics.atEdge && metrics.pixels != 0) { + triggerGlobalSearchEvent(isPagination: true); } } - // Return true to allow the notification to continue to be dispatched to further ancestors. - return true; }, child: ScrollableContent( @@ -138,63 +116,6 @@ class _SearchBeneficiaryPageState builder: (context, locationState) { return Column( children: [ - DigitSearchBar( - controller: searchController, - hintText: localizations.translate( - i18.searchBeneficiary - .beneficiarySearchHintText, - ), - textCapitalization: TextCapitalization.words, - onChanged: (value) { - if (value.isEmpty) { - blocWrapper.clearEvent(); - } - if (value.trim().length < 2 && - !isProximityEnabled) { - blocWrapper.clearEvent(); - - return; - } else if (isProximityEnabled && - value.trim().length < 2) { - blocWrapper.proximitySearchBloc.add( - SearchHouseholdsEvent.searchByProximity( - latitude: locationState.latitude!, - longititude: locationState.longitude!, - projectId: - RegistrationDeliverySingleton() - .projectId!, - maxRadius: - RegistrationDeliverySingleton() - .maxRadius!, - offset: offset, - limit: limit, - ), - ); - } else { - blocWrapper.searchHouseholdsBloc.add( - const SearchHouseholdsClearEvent(), - ); - blocWrapper.searchByHeadBloc.add( - SearchHouseholdsEvent - .searchByHouseholdHead( - searchText: value, - projectId: - RegistrationDeliverySingleton() - .projectId!, - isProximityEnabled: isProximityEnabled, - latitude: locationState.latitude, - longitude: locationState.longitude, - maxRadius: - RegistrationDeliverySingleton() - .maxRadius, - tag: null, - offset: offset, - limit: limit, - ), - ); - } - }, - ), locationState.latitude != null ? Row( children: [ @@ -218,26 +139,10 @@ class _SearchBeneficiaryPageState .maxRadius != null && isProximityEnabled) { - blocWrapper.proximitySearchBloc - .add( - SearchHouseholdsEvent - .searchByProximity( - latitude: - locationState.latitude!, - longititude: - locationState.longitude!, - projectId: - RegistrationDeliverySingleton() - .projectId!, - maxRadius: - RegistrationDeliverySingleton() - .maxRadius!, - offset: offset, - limit: limit, - ), - ); + triggerGlobalSearchEvent(); } else { blocWrapper.clearEvent(); + triggerGlobalSearchEvent(); } }, ), @@ -250,6 +155,124 @@ class _SearchBeneficiaryPageState ], ) : const Offstage(), + DigitSearchBar( + controller: searchController, + hintText: localizations.translate( + i18.searchBeneficiary + .beneficiarySearchHintText, + ), + textCapitalization: TextCapitalization.words, + onChanged: (value) { + if (value.isEmpty || + value.trim().length > 2) { + triggerGlobalSearchEvent(); + } + }, + ), + RegistrationDeliverySingleton() + .searchHouseHoldFilter != + null && + RegistrationDeliverySingleton() + .searchHouseHoldFilter! + .isNotEmpty + ? Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.only( + left: kPadding), + child: DigitIconButton( + textDirection: TextDirection.rtl, + iconText: + getFilterIconNLabel()['label'], + icon: getFilterIconNLabel()['icon'], + onPressed: () => showFilterDialog(), + ), + ), + ) + : const Offstage(), + selectedFilters.isNotEmpty + ? Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: + MediaQuery.of(context).size.height * + 0.06, + child: ListView.builder( + shrinkWrap: true, + scrollDirection: Axis.horizontal, + itemCount: selectedFilters.length, + itemBuilder: (context, index) { + return Padding( + padding: const EdgeInsets.all( + kPadding / 2), + child: Container( + padding: + const EdgeInsets.all( + kPadding / 2), + decoration: BoxDecoration( + border: Border.all( + color: + const DigitColors() + .cloudGray), + borderRadius: + BorderRadius.circular( + kPadding / 2), + ), + child: Row( + children: [ + Text( + localizations.translate( + getStatus( + selectedFilters[ + index])), + style: TextStyle( + color: const DigitColors() + .davyGray)), + Text( + ' (${searchHouseholdsState.totalResults})', + style: TextStyle( + color: const DigitColors() + .davyGray)), + const SizedBox( + width: kPadding), + GestureDetector( + onTap: () { + setState(() { + selectedFilters.remove( + selectedFilters[ + index]); + }); + blocWrapper + .clearEvent(); + triggerGlobalSearchEvent(); + }, + child: Container( + decoration: + BoxDecoration( + color: + const DigitColors() + .davyGray, + borderRadius: + BorderRadius + .circular( + kPadding / + 2), + ), + child: Icon( + Icons.close, + color: + const DigitColors() + .white, + ), + ), + ) + ], + ), + )); + }), + ), + ) + : const Offstage(), ], ); }, @@ -277,14 +300,17 @@ class _SearchBeneficiaryPageState ), BlocListener( listener: (context, scannerState) { - context.read().tagSearchBloc.add( - SearchHouseholdsEvent.searchByTag( - tag: scannerState.qrCodes.isNotEmpty - ? scannerState.qrCodes.lastOrNull! - : '', - projectId: RegistrationDeliverySingleton().projectId!, - ), - ); + if (scannerState.qrCodes.isNotEmpty) { + context.read().tagSearchBloc.add( + SearchHouseholdsEvent.searchByTag( + tag: scannerState.qrCodes.isNotEmpty + ? scannerState.qrCodes.lastOrNull! + : '', + projectId: + RegistrationDeliverySingleton().projectId!, + ), + ); + } }, child: BlocBuilder( builder: (context, locationState) { @@ -299,8 +325,8 @@ class _SearchBeneficiaryPageState long, ), Coordinate( - i.household.address?.latitude, - i.household.address?.longitude, + i.household?.address?.latitude, + i.household?.address?.longitude, ), ); @@ -317,16 +343,46 @@ class _SearchBeneficiaryPageState const DigitScannerEvent.handleScanner(), ); - await context.router.push( - BeneficiaryWrapperRoute( - wrapper: i, - ), - ); + if ((i.tasks != null && + i.tasks?.last.status == + Status.closeHousehold.toValue() && + (i.tasks ?? []).isNotEmpty) || + (i.projectBeneficiaries ?? []).isEmpty) { + setState(() { + selectedFilters = []; + }); + blocWrapper.clearEvent(); + await context.router.push( + BeneficiaryRegistrationWrapperRoute( + initialState: BeneficiaryRegistrationState + .editHousehold( + householdModel: i.household!, + individualModel: i.members!, + registrationDate: DateTime.now(), + projectBeneficiaryModel: + (i.projectBeneficiaries ?? []) + .isNotEmpty + ? i.projectBeneficiaries + ?.last + : null, + addressModel: i.headOfHousehold! + .address!.last, + headOfHousehold: + i.headOfHousehold), + ), + ); + } else { + await context.router.push( + BeneficiaryWrapperRoute( + wrapper: i, + ), + ); + } setState(() { isProximityEnabled = false; }); searchController.clear(); - + selectedFilters.clear(); blocWrapper.clearEvent(); }, ), @@ -365,6 +421,7 @@ class _SearchBeneficiaryPageState ), )); searchController.clear(); + selectedFilters = []; blocWrapper.clearEvent(); } : null, @@ -382,6 +439,8 @@ class _SearchBeneficiaryPageState ), onPressed: () { blocWrapper.clearEvent(); + selectedFilters = []; + searchController.clear(); Navigator.of(context).push( MaterialPageRoute( builder: (context) => const DigitScannerPage( @@ -406,4 +465,130 @@ class _SearchBeneficiaryPageState ), ); } + + getFilterIconNLabel() { + return { + 'label': localizations.translate( + i18.searchBeneficiary.filterLabel, + ), + 'icon': Icons.filter_alt + }; + } + + showFilterDialog() async { + var filters = await DigitDialog.show(context, + options: DigitDialogOptions( + titlePadding: EdgeInsets.zero, + dialogPadding: EdgeInsets.zero, + contentPadding: EdgeInsets.zero, + barrierDismissible: true, + content: StatusFilter( + selectedFilters: selectedFilters, + titleIcon: Icon(getFilterIconNLabel()['icon'], + color: const DigitColors().burningOrange), + titleText: getFilterIconNLabel()['label'], + isCloseIcon: true, + ), + )); + + if (filters != null && filters.isNotEmpty) { + setState(() { + selectedFilters = []; + }); + setState(() { + selectedFilters.addAll(filters); + }); + triggerGlobalSearchEvent(); + } else { + setState(() { + selectedFilters = []; + }); + blocWrapper.clearEvent(); + triggerGlobalSearchEvent(); + } + } + + void triggerGlobalSearchEvent({bool isPagination = false}) { + if (!isPagination) { + blocWrapper.clearEvent(); + } + if (RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.individual) { + if (isProximityEnabled || + selectedFilters.isNotEmpty || + searchController.text.isNotEmpty) { + blocWrapper.individualGlobalSearchBloc + .add(SearchHouseholdsEvent.individualGlobalSearch( + globalSearchParams: GlobalSearchParameters( + isProximityEnabled: isProximityEnabled, + latitude: lat, + projectId: RegistrationDeliverySingleton().projectId!, + longitude: long, + maxRadius: RegistrationDeliverySingleton().maxRadius, + nameSearch: searchController.text.trim().length > 2 + ? searchController.text.trim() + : blocWrapper.searchHouseholdsBloc.state.searchQuery, + filter: selectedFilters, + offset: isPagination + ? blocWrapper.individualGlobalSearchBloc.state.offset + : offset, + limit: isPagination + ? blocWrapper.individualGlobalSearchBloc.state.limit + : limit, + ))); + } + } else { + if (isProximityEnabled || + selectedFilters.isNotEmpty || + searchController.text.isNotEmpty) { + blocWrapper.houseHoldGlobalSearchBloc + .add(SearchHouseholdsEvent.houseHoldGlobalSearch( + globalSearchParams: GlobalSearchParameters( + isProximityEnabled: isProximityEnabled, + latitude: lat, + longitude: long, + projectId: RegistrationDeliverySingleton().projectId!, + maxRadius: RegistrationDeliverySingleton().maxRadius, + nameSearch: searchController.text.trim().length > 2 + ? searchController.text.trim() + : blocWrapper.searchHouseholdsBloc.state.searchQuery, + filter: selectedFilters, + offset: isPagination + ? blocWrapper.houseHoldGlobalSearchBloc.state.offset + : offset, + limit: isPagination + ? blocWrapper.houseHoldGlobalSearchBloc.state.limit + : limit, + ))); + } + } + } + + String getStatus(String selectedFilter) { + final statusMap = { + Status.delivered.toValue(): Status.delivered, + Status.notAdministered.toValue(): Status.notAdministered, + Status.visited.toValue(): Status.visited, + Status.notVisited.toValue(): Status.notVisited, + Status.beneficiaryRefused.toValue(): Status.beneficiaryRefused, + Status.beneficiaryReferred.toValue(): Status.beneficiaryReferred, + Status.administeredSuccess.toValue(): Status.administeredSuccess, + Status.administeredFailed.toValue(): Status.administeredFailed, + Status.inComplete.toValue(): Status.inComplete, + Status.toAdminister.toValue(): Status.toAdminister, + Status.closeHousehold.toValue(): Status.closeHousehold, + Status.registered.toValue(): Status.registered, + Status.notRegistered.toValue(): Status.notRegistered, + }; + + var mappedStatus = statusMap.entries + .where((element) => element.value.name == selectedFilter) + .first + .key; + if (mappedStatus != null) { + return mappedStatus; + } else { + return selectedFilter; + } + } } diff --git a/packages/registration_delivery/lib/pages/summary_page.dart b/packages/registration_delivery/lib/pages/summary_page.dart new file mode 100644 index 000000000..1e60af607 --- /dev/null +++ b/packages/registration_delivery/lib/pages/summary_page.dart @@ -0,0 +1,404 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/utils/date_utils.dart'; +import 'package:digit_components/widgets/atoms/details_card.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:recase/recase.dart'; +import 'package:registration_delivery/models/entities/additional_fields_type.dart'; +import 'package:registration_delivery/router/registration_delivery_router.gm.dart'; +import 'package:registration_delivery/widgets/back_navigation_help_header.dart'; +import 'package:registration_delivery/widgets/showcase/showcase_button.dart'; + +import '../../../widgets/localized.dart'; +import '../../utils/i18_key_constants.dart' as i18; +import '../blocs/beneficiary_registration/beneficiary_registration.dart'; +import '../blocs/search_households/search_bloc_common_wrapper.dart'; +import '../blocs/search_households/search_households.dart'; +import '../utils/constants.dart'; +import '../utils/utils.dart'; + +@RoutePage() +class SummaryPage extends LocalizedStatefulWidget { + const SummaryPage({ + super.key, + super.appLocalizations, + }); + + @override + State createState() => SummaryPageState(); +} + +class SummaryPageState extends LocalizedState { + final clickedStatus = ValueNotifier(false); + + String getLocalizedMessage(String code) { + return localizations.translate(code); + } + + @override + Widget build(BuildContext context) { + return PopScope( + onPopInvoked: (val) { + context.read().add( + BeneficiaryRegistrationCreateEvent( + projectId: RegistrationDeliverySingleton().projectId!, + userUuid: RegistrationDeliverySingleton().loggedInUserUuid!, + boundary: RegistrationDeliverySingleton().boundary!, + ), + ); + }, + child: Scaffold( + body: BlocConsumer( + listener: (context, householdState) { + final router = context.router; + householdState.mapOrNull( + persisted: (value) { + if (value.navigateToRoot) { + (router.parent() as StackRouter).maybePop(); + } else { + router.popUntil((route) => + route.settings.name == SearchBeneficiaryRoute.name); + context.read().searchHouseholdsBloc.add( + SearchHouseholdsEvent.searchByHousehold( + householdModel: value.householdModel, + projectId: RegistrationDeliverySingleton().projectId!, + isProximityEnabled: false, + ), + ); + router.push(BeneficiaryAcknowledgementRoute( + enableViewHousehold: true, + )); + } + }, + ); + }, + builder: (context, householdState) { + return ScrollableContent( + enableFixedButton: true, + header: Column(children: [ + const BackNavigationHelpHeaderWidget( + showHelp: false, + showcaseButton: ShowcaseButton(), + ), + Padding( + padding: + const EdgeInsets.only(bottom: kPadding, left: kPadding), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + localizations.translate( + i18.common.coreCommonSummaryDetails, + ), + style: DigitTheme + .instance.mobileTheme.textTheme.displayMedium, + ), + ), + ), + ]), + footer: DigitCard( + margin: const EdgeInsets.fromLTRB(0, kPadding, 0, 0), + padding: const EdgeInsets.fromLTRB(kPadding, 0, kPadding, 0), + child: ValueListenableBuilder( + valueListenable: clickedStatus, + builder: (context, bool isClicked, _) { + return DigitElevatedButton( + onPressed: isClicked + ? null + : () async { + final bloc = + context.read(); + final userId = RegistrationDeliverySingleton() + .loggedInUserUuid; + final projectId = + RegistrationDeliverySingleton().projectId; + + householdState.maybeWhen( + orElse: () { + return; + }, + summary: ( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold, + ) async { + final submit = await DigitDialog.show( + context, + options: DigitDialogOptions( + titleText: localizations.translate( + i18.deliverIntervention.dialogTitle, + ), + contentText: localizations.translate( + i18.deliverIntervention.dialogContent, + ), + primaryAction: DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonSubmit, + ), + action: (context) { + clickedStatus.value = true; + Navigator.of( + context, + rootNavigator: true, + ).pop(true); + }, + ), + secondaryAction: DigitDialogActions( + label: localizations.translate( + i18.common.coreCommonCancel, + ), + action: (context) => Navigator.of( + context, + rootNavigator: true, + ).pop(false), + ), + ), + ); + + if (submit ?? false) { + if (context.mounted) { + bloc.add( + BeneficiaryRegistrationCreateEvent( + projectId: projectId!, + userUuid: userId!, + boundary: + RegistrationDeliverySingleton() + .boundary!, + tag: projectBeneficiaryModel?.tag, + navigateToSummary: false), + ); + } + } + }, + ); + }, + child: Center( + child: Text( + householdState.mapOrNull( + editIndividual: (value) => localizations + .translate(i18.common.coreCommonSave), + ) ?? + localizations + .translate(i18.common.coreCommonSubmit), + ), + ), + ); + }, + ), + ), + slivers: [ + SliverToBoxAdapter( + child: Column( + children: [ + DigitCard( + child: LabelValueList( + heading: localizations.translate(i18 + .householdLocation.householdLocationLabelText), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.householdLocation.villageLabel), + value: householdState.householdModel?.address + ?.locality?.code + .split('_') + .last + .toString() + .titleCase ?? + localizations + .translate(i18.common.coreCommonNA), + isInline: true), + LabelValuePair( + label: localizations.translate( + i18.householdLocation.landmarkFormLabel), + value: householdState + .householdModel?.address?.landmark ?? + localizations + .translate(i18.common.coreCommonNA), + isInline: true), + ]), + ), + DigitCard( + child: LabelValueList( + heading: localizations.translate( + i18.householdDetails.householdDetailsLabel), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.beneficiaryDetails.totalMembers), + value: householdState + .householdModel?.memberCount + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate(i18 + .householdDetails + .noOfPregnantWomenCountLabel), + value: householdState.householdModel + ?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.pregnantWomen + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate(i18 + .householdDetails + .noOfChildrenBelow5YearsLabel), + value: householdState.householdModel + ?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.children + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + ]), + ), + DigitCard( + child: LabelValueList( + heading: localizations.translate( + i18.householdDetails.houseDetailsLabel), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.householdDetails.noOfRoomsLabel), + value: householdState.householdModel + ?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType.noOfRooms + .toValue()) + .firstOrNull + ?.value + .toString() ?? + '0', + isInline: true), + LabelValuePair( + label: localizations.translate( + i18.householdDetails.typeOfStructure), + value: (householdState.householdModel + ?.additionalFields?.fields + .where((h) => + h.key == + AdditionalFieldsType + .houseStructureTypes + .toValue()) + .firstOrNull + ?.value ?? + []) + .toString() + .split('|') + .map((item) => getLocalizedMessage(item)) + .toList() + .join(', '), + isInline: true), + ]), + ), + DigitCard( + child: LabelValueList( + heading: localizations.translate(i18 + .individualDetails.individualsDetailsLabelText), + withDivider: true, + items: [ + LabelValuePair( + label: localizations.translate( + i18.individualDetails.nameLabelText), + value: householdState.maybeWhen( + orElse: () => localizations + .translate(i18.common.coreCommonNA), + summary: ( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold, + ) => + individualModel?.name?.givenName ?? + localizations.translate( + i18.common.coreCommonNA)), + ), + LabelValuePair( + label: localizations.translate( + i18.individualDetails.dobLabelText), + value: householdState.maybeWhen( + orElse: () => localizations + .translate(i18.common.coreCommonNA), + summary: ( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold, + ) => + individualModel?.dateOfBirth != null + ? DigitDateUtils.getFilteredDate( + DigitDateUtils + .getFormattedDateToDateTime( + individualModel + ?.dateOfBirth ?? + '') + .toString(), + dateFormat: Constants() + .dateMonthYearFormat) + .toString() + : localizations.translate( + i18.common.coreCommonNA)), + ), + LabelValuePair( + label: localizations.translate( + i18.individualDetails.genderLabelText), + value: householdState.maybeWhen( + orElse: () => localizations + .translate(i18.common.coreCommonNA), + summary: ( + navigateToRoot, + householdModel, + individualModel, + projectBeneficiaryModel, + registrationDate, + addressModel, + loading, + isHeadOfHousehold, + ) => + individualModel?.gender != null + ? localizations.translate( + individualModel?.gender?.name + .toUpperCase() ?? + '') + : localizations.translate( + i18.common.coreCommonNA)), + ), + ]), + ), + ], + ), + ) + ]); + }, + )), + ); + } +} diff --git a/packages/registration_delivery/lib/registration_delivery.dart b/packages/registration_delivery/lib/registration_delivery.dart index 21ced98d1..ff2e0209d 100644 --- a/packages/registration_delivery/lib/registration_delivery.dart +++ b/packages/registration_delivery/lib/registration_delivery.dart @@ -4,19 +4,17 @@ library registration_delivery; import 'package:dart_mappable/dart_mappable.dart'; + export 'blocs/beneficiary_registration/beneficiary_registration.dart'; export 'blocs/delivery_intervention/deliver_intervention.dart'; export 'blocs/household_details/household_details.dart'; export 'blocs/household_location/household_location.dart'; export 'blocs/household_overview/household_overview.dart'; export 'blocs/referral_management/referral_management.dart'; -export 'blocs/search_households/proximity_search.dart'; export 'blocs/search_households/search_bloc_common_wrapper.dart'; -export 'blocs/search_households/search_by_head.dart'; export 'blocs/search_households/search_households.dart'; export 'blocs/search_households/tag_by_search.dart'; export 'blocs/side_effects/side_effects.dart'; -export 'data/repositories/local/registration_delivery_address.dart'; export 'data/repositories/local/base/household_base.dart'; export 'data/repositories/local/base/household_member_base.dart'; export 'data/repositories/local/base/project_beneficiary_base.dart'; @@ -26,6 +24,7 @@ export 'data/repositories/local/household.dart'; export 'data/repositories/local/household_member.dart'; export 'data/repositories/local/project_beneficiary.dart'; export 'data/repositories/local/referral.dart'; +export 'data/repositories/local/registration_delivery_address.dart'; export 'data/repositories/local/side_effect.dart'; export 'data/repositories/local/task.dart'; export 'data/repositories/oplog/oplog.dart'; @@ -39,19 +38,10 @@ export 'models/entities/household.dart'; export 'models/entities/household_member.dart'; export 'models/entities/project_beneficiary.dart'; export 'models/entities/referral.dart'; +export 'models/entities/registration_delivery_enums.dart'; export 'models/entities/side_effect.dart'; export 'models/entities/task.dart'; export 'models/entities/task_resource.dart'; -export 'router/registration_delivery_router.dart'; -export 'utils/typedefs.dart'; -export 'utils/utils.dart' show RegistrationDeliverySingleton; -export 'widgets/beneficiary/beneficiary_card.dart'; -export 'widgets/beneficiary/beneficiary_statistics_card.dart'; -export 'widgets/progress_bar/beneficiary_progress.dart'; -export 'pages/beneficiary/widgets/household_acknowledgement.dart'; -export 'pages/beneficiary/widgets/past_delivery.dart'; -export 'pages/beneficiary/widgets/record_delivery_cycle.dart'; -export 'pages/beneficiary/widgets/splash_acknowledgement.dart'; export 'pages/beneficiary/beneficiary_details.dart'; export 'pages/beneficiary/beneficiary_wrapper.dart'; export 'pages/beneficiary/deliver_intervention.dart'; @@ -61,11 +51,23 @@ export 'pages/beneficiary/household_overview.dart'; export 'pages/beneficiary/record_past_delivery_details.dart'; export 'pages/beneficiary/refer_beneficiary.dart'; export 'pages/beneficiary/side_effects.dart'; +export 'pages/beneficiary/widgets/household_acknowledgement.dart'; +export 'pages/beneficiary/widgets/past_delivery.dart'; +export 'pages/beneficiary/widgets/record_delivery_cycle.dart'; +export 'pages/beneficiary/widgets/splash_acknowledgement.dart'; export 'pages/beneficiary_registration/beneficiary_acknowledgement.dart'; export 'pages/beneficiary_registration/beneficiary_registration_wrapper.dart'; +export 'pages/beneficiary_registration/house_details.dart'; export 'pages/beneficiary_registration/household_details.dart'; export 'pages/beneficiary_registration/household_location.dart'; export 'pages/beneficiary_registration/individual_details.dart'; export 'pages/reason_for_deletion.dart'; export 'pages/registration_delivery_wrapper.dart'; export 'pages/search_beneficiary.dart'; +export 'pages/summary_page.dart'; +export 'router/registration_delivery_router.dart'; +export 'utils/typedefs.dart'; +export 'utils/utils.dart' show RegistrationDeliverySingleton; +export 'widgets/beneficiary/beneficiary_card.dart'; +export 'widgets/beneficiary/beneficiary_statistics_card.dart'; +export 'widgets/progress_bar/beneficiary_progress.dart'; diff --git a/packages/registration_delivery/lib/registration_delivery.init.dart b/packages/registration_delivery/lib/registration_delivery.init.dart index f7b7ae3bc..db23c3ec9 100644 --- a/packages/registration_delivery/lib/registration_delivery.init.dart +++ b/packages/registration_delivery/lib/registration_delivery.init.dart @@ -10,10 +10,11 @@ import 'models/entities/household_member.dart' as p3; import 'models/entities/project_beneficiary.dart' as p4; import 'models/entities/referral.dart' as p5; import 'models/entities/reg_form_validations_type.dart' as p6; -import 'models/entities/side_effect.dart' as p7; -import 'models/entities/status.dart' as p8; -import 'models/entities/task.dart' as p9; -import 'models/entities/task_resource.dart' as p10; +import 'models/entities/registration_delivery_enums.dart' as p7; +import 'models/entities/side_effect.dart' as p8; +import 'models/entities/status.dart' as p9; +import 'models/entities/task.dart' as p10; +import 'models/entities/task_resource.dart' as p11; void initializeMappers() { p0.AdditionalFieldsTypeMapper.ensureInitialized(); @@ -31,14 +32,15 @@ void initializeMappers() { p5.ReferralModelMapper.ensureInitialized(); p5.ReferralAdditionalFieldsMapper.ensureInitialized(); p6.RegFormValidationsMapper.ensureInitialized(); - p7.SideEffectSearchModelMapper.ensureInitialized(); - p7.SideEffectModelMapper.ensureInitialized(); - p7.SideEffectAdditionalFieldsMapper.ensureInitialized(); - p8.StatusMapper.ensureInitialized(); - p9.TaskSearchModelMapper.ensureInitialized(); - p9.TaskModelMapper.ensureInitialized(); - p9.TaskAdditionalFieldsMapper.ensureInitialized(); - p10.TaskResourceSearchModelMapper.ensureInitialized(); - p10.TaskResourceModelMapper.ensureInitialized(); - p10.TaskResourceAdditionalFieldsMapper.ensureInitialized(); + p7.RegistrationDeliveryEnumsMapper.ensureInitialized(); + p8.SideEffectSearchModelMapper.ensureInitialized(); + p8.SideEffectModelMapper.ensureInitialized(); + p8.SideEffectAdditionalFieldsMapper.ensureInitialized(); + p9.StatusMapper.ensureInitialized(); + p10.TaskSearchModelMapper.ensureInitialized(); + p10.TaskModelMapper.ensureInitialized(); + p10.TaskAdditionalFieldsMapper.ensureInitialized(); + p11.TaskResourceSearchModelMapper.ensureInitialized(); + p11.TaskResourceModelMapper.ensureInitialized(); + p11.TaskResourceAdditionalFieldsMapper.ensureInitialized(); } diff --git a/packages/registration_delivery/lib/router/registration_delivery_router.dart b/packages/registration_delivery/lib/router/registration_delivery_router.dart index e7c002b5b..14d14e52f 100644 --- a/packages/registration_delivery/lib/router/registration_delivery_router.dart +++ b/packages/registration_delivery/lib/router/registration_delivery_router.dart @@ -14,7 +14,7 @@ class RegistrationDeliveryRoute extends $RegistrationDeliveryRoute { path: 'registration-delivery-wrapper', children: [ AutoRoute( - initial: true, + initial: true, page: SearchBeneficiaryRoute.page, path: 'search-beneficiary'), @@ -29,6 +29,8 @@ class RegistrationDeliveryRoute extends $RegistrationDeliveryRoute { AutoRoute( page: HouseHoldDetailsRoute.page, path: 'household-details'), + AutoRoute( + page: HouseDetailsRoute.page, path: 'house-details'), AutoRoute( page: HouseholdLocationRoute.page, path: 'household-location', @@ -38,6 +40,10 @@ class RegistrationDeliveryRoute extends $RegistrationDeliveryRoute { page: BeneficiaryAcknowledgementRoute.page, path: 'beneficiary-acknowledgement', ), + AutoRoute( + page: SummaryRoute.page, + path: 'beneficiary-summary', + ), ], ), AutoRoute( @@ -53,10 +59,22 @@ class RegistrationDeliveryRoute extends $RegistrationDeliveryRoute { page: BeneficiaryDetailsRoute.page, path: 'beneficiary-details', ), + AutoRoute( + page: BeneficiaryChecklistRoute.page, + path: 'beneficiary-checklist', + ), + AutoRoute( + page: BeneficiaryChecklistRoute.page, + path: 'beneficiary-checklist', + ), AutoRoute( page: DeliverInterventionRoute.page, path: 'deliver-intervention', ), + AutoRoute( + page: RefusedDeliveryRoute.page, + path: 'refused-delivery', + ), AutoRoute( page: SideEffectsRoute.page, path: 'side-effects', @@ -85,6 +103,10 @@ class RegistrationDeliveryRoute extends $RegistrationDeliveryRoute { page: HouseholdAcknowledgementRoute.page, path: 'household-acknowledgement', ), + AutoRoute( + page: DeliverySummaryRoute.page, + path: 'delivery-summary', + ), ], ), ]), diff --git a/packages/registration_delivery/lib/router/registration_delivery_router.gm.dart b/packages/registration_delivery/lib/router/registration_delivery_router.gm.dart index 9ddbc61e2..9f7594328 100644 --- a/packages/registration_delivery/lib/router/registration_delivery_router.gm.dart +++ b/packages/registration_delivery/lib/router/registration_delivery_router.gm.dart @@ -8,59 +8,67 @@ // coverage:ignore-file // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:auto_route/auto_route.dart' as _i20; -import 'package:digit_data_model/data_model.dart' as _i25; -import 'package:flutter/material.dart' as _i21; -import 'package:registration_delivery/blocs/app_localization.dart' as _i22; -import 'package:registration_delivery/blocs/beneficiary_registration/beneficiary_registration.dart' - as _i23; +import 'package:auto_route/auto_route.dart' as _i25; +import 'package:digit_data_model/data_model.dart' as _i30; +import 'package:flutter/material.dart' as _i26; +import 'package:registration_delivery/blocs/app_localization.dart' as _i27; import 'package:registration_delivery/blocs/search_households/search_households.dart' - as _i24; -import 'package:registration_delivery/models/entities/task.dart' as _i26; -import 'package:registration_delivery/pages/beneficiary/beneficiary_details.dart' + as _i29; +import 'package:registration_delivery/models/entities/task.dart' as _i31; +import 'package:registration_delivery/pages/beneficiary/beneficiary_checklist.dart' as _i2; +import 'package:registration_delivery/pages/beneficiary/beneficiary_details.dart' + as _i3; import 'package:registration_delivery/pages/beneficiary/beneficiary_wrapper.dart' - as _i4; -import 'package:registration_delivery/pages/beneficiary/deliver_intervention.dart' as _i5; -import 'package:registration_delivery/pages/beneficiary/dose_administered.dart' +import 'package:registration_delivery/pages/beneficiary/deliver_intervention.dart' as _i6; -import 'package:registration_delivery/pages/beneficiary/facility_selection.dart' +import 'package:registration_delivery/pages/beneficiary/delivery_summary_page.dart' as _i7; +import 'package:registration_delivery/pages/beneficiary/dose_administered.dart' + as _i8; +import 'package:registration_delivery/pages/beneficiary/facility_selection.dart' + as _i9; import 'package:registration_delivery/pages/beneficiary/household_overview.dart' - as _i11; -import 'package:registration_delivery/pages/beneficiary/record_past_delivery_details.dart' as _i14; +import 'package:registration_delivery/pages/beneficiary/record_past_delivery_details.dart' + as _i17; import 'package:registration_delivery/pages/beneficiary/refer_beneficiary.dart' - as _i15; -import 'package:registration_delivery/pages/beneficiary/side_effects.dart' as _i18; +import 'package:registration_delivery/pages/beneficiary/refused_delivery.dart' + as _i19; +import 'package:registration_delivery/pages/beneficiary/side_effects.dart' + as _i22; import 'package:registration_delivery/pages/beneficiary/widgets/household_acknowledgement.dart' - as _i9; + as _i12; import 'package:registration_delivery/pages/beneficiary/widgets/splash_acknowledgement.dart' - as _i19; + as _i23; import 'package:registration_delivery/pages/beneficiary_registration/beneficiary_acknowledgement.dart' as _i1; import 'package:registration_delivery/pages/beneficiary_registration/beneficiary_registration_wrapper.dart' - as _i3; + as _i4; +import 'package:registration_delivery/pages/beneficiary_registration/house_details.dart' + as _i10; import 'package:registration_delivery/pages/beneficiary_registration/household_details.dart' - as _i8; + as _i11; import 'package:registration_delivery/pages/beneficiary_registration/household_location.dart' - as _i10; + as _i13; import 'package:registration_delivery/pages/beneficiary_registration/individual_details.dart' - as _i12; -import 'package:registration_delivery/pages/reason_for_deletion.dart' as _i13; + as _i15; +import 'package:registration_delivery/pages/reason_for_deletion.dart' as _i16; import 'package:registration_delivery/pages/registration_delivery_wrapper.dart' - as _i16; -import 'package:registration_delivery/pages/search_beneficiary.dart' as _i17; + as _i20; +import 'package:registration_delivery/pages/search_beneficiary.dart' as _i21; +import 'package:registration_delivery/pages/summary_page.dart' as _i24; +import 'package:registration_delivery/registration_delivery.dart' as _i28; -abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { +abstract class $RegistrationDeliveryRoute extends _i25.AutoRouterModule { @override - final Map pagesMap = { + final Map pagesMap = { BeneficiaryAcknowledgementRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const BeneficiaryAcknowledgementRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, child: _i1.BeneficiaryAcknowledgementPage( key: args.key, @@ -69,12 +77,24 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { ), ); }, + BeneficiaryChecklistRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const BeneficiaryChecklistRouteArgs()); + return _i25.AutoRoutePage( + routeData: routeData, + child: _i2.BeneficiaryChecklistPage( + key: args.key, + beneficiaryClientRefId: args.beneficiaryClientRefId, + appLocalizations: args.appLocalizations, + ), + ); + }, BeneficiaryDetailsRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const BeneficiaryDetailsRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i2.BeneficiaryDetailsPage( + child: _i3.BeneficiaryDetailsPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -82,10 +102,10 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { }, BeneficiaryRegistrationWrapperRoute.name: (routeData) { final args = routeData.argsAs(); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i20.WrappedRoute( - child: _i3.BeneficiaryRegistrationWrapperPage( + child: _i25.WrappedRoute( + child: _i4.BeneficiaryRegistrationWrapperPage( key: args.key, initialState: args.initialState, )), @@ -93,9 +113,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { }, BeneficiaryWrapperRoute.name: (routeData) { final args = routeData.argsAs(); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i4.BeneficiaryWrapperPage( + child: _i5.BeneficiaryWrapperPage( key: args.key, wrapper: args.wrapper, isEditing: args.isEditing, @@ -105,21 +125,32 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { DeliverInterventionRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const DeliverInterventionRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i5.DeliverInterventionPage( + child: _i6.DeliverInterventionPage( key: args.key, appLocalizations: args.appLocalizations, isEditing: args.isEditing, ), ); }, + DeliverySummaryRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const DeliverySummaryRouteArgs()); + return _i25.AutoRoutePage( + routeData: routeData, + child: _i7.DeliverySummaryPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, DoseAdministeredRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const DoseAdministeredRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i6.DoseAdministeredPage( + child: _i8.DoseAdministeredPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -127,20 +158,31 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { }, FacilitySelectionRoute.name: (routeData) { final args = routeData.argsAs(); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i7.FacilitySelectionPage( + child: _i9.FacilitySelectionPage( key: args.key, facilities: args.facilities, ), ); }, + HouseDetailsRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const HouseDetailsRouteArgs()); + return _i25.AutoRoutePage( + routeData: routeData, + child: _i10.HouseDetailsPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, HouseHoldDetailsRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const HouseHoldDetailsRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i8.HouseHoldDetailsPage( + child: _i11.HouseHoldDetailsPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -149,9 +191,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { HouseholdAcknowledgementRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const HouseholdAcknowledgementRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i9.HouseholdAcknowledgementPage( + child: _i12.HouseholdAcknowledgementPage( key: args.key, appLocalizations: args.appLocalizations, enableViewHousehold: args.enableViewHousehold, @@ -161,9 +203,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { HouseholdLocationRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const HouseholdLocationRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i10.HouseholdLocationPage( + child: _i13.HouseholdLocationPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -172,9 +214,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { HouseholdOverviewRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const HouseholdOverviewRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i11.HouseholdOverviewPage( + child: _i14.HouseholdOverviewPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -183,9 +225,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { IndividualDetailsRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const IndividualDetailsRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i12.IndividualDetailsPage( + child: _i15.IndividualDetailsPage( key: args.key, appLocalizations: args.appLocalizations, isHeadOfHousehold: args.isHeadOfHousehold, @@ -195,9 +237,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { ReasonForDeletionRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const ReasonForDeletionRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i13.ReasonForDeletionPage( + child: _i16.ReasonForDeletionPage( key: args.key, appLocalizations: args.appLocalizations, isHousholdDelete: args.isHousholdDelete, @@ -207,9 +249,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { RecordPastDeliveryDetailsRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const RecordPastDeliveryDetailsRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i14.RecordPastDeliveryDetailsPage( + child: _i17.RecordPastDeliveryDetailsPage( key: args.key, appLocalizations: args.appLocalizations, tasks: args.tasks, @@ -218,9 +260,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { }, ReferBeneficiaryRoute.name: (routeData) { final args = routeData.argsAs(); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i15.ReferBeneficiaryPage( + child: _i18.ReferBeneficiaryPage( key: args.key, appLocalizations: args.appLocalizations, isEditing: args.isEditing, @@ -228,18 +270,29 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { ), ); }, + RefusedDeliveryRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const RefusedDeliveryRouteArgs()); + return _i25.AutoRoutePage( + routeData: routeData, + child: _i19.RefusedDeliveryPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, RegistrationDeliveryWrapperRoute.name: (routeData) { - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: const _i16.RegistrationDeliveryWrapperPage(), + child: const _i20.RegistrationDeliveryWrapperPage(), ); }, SearchBeneficiaryRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const SearchBeneficiaryRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i17.SearchBeneficiaryPage( + child: _i21.SearchBeneficiaryPage( key: args.key, appLocalizations: args.appLocalizations, ), @@ -247,9 +300,9 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { }, SideEffectsRoute.name: (routeData) { final args = routeData.argsAs(); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i18.SideEffectsPage( + child: _i22.SideEffectsPage( key: args.key, appLocalizations: args.appLocalizations, tasks: args.tasks, @@ -260,27 +313,38 @@ abstract class $RegistrationDeliveryRoute extends _i20.AutoRouterModule { SplashAcknowledgementRoute.name: (routeData) { final args = routeData.argsAs( orElse: () => const SplashAcknowledgementRouteArgs()); - return _i20.AutoRoutePage( + return _i25.AutoRoutePage( routeData: routeData, - child: _i19.SplashAcknowledgementPage( + child: _i23.SplashAcknowledgementPage( key: args.key, appLocalizations: args.appLocalizations, enableBackToSearch: args.enableBackToSearch, ), ); }, + SummaryRoute.name: (routeData) { + final args = routeData.argsAs( + orElse: () => const SummaryRouteArgs()); + return _i25.AutoRoutePage( + routeData: routeData, + child: _i24.SummaryPage( + key: args.key, + appLocalizations: args.appLocalizations, + ), + ); + }, }; } /// generated route for /// [_i1.BeneficiaryAcknowledgementPage] class BeneficiaryAcknowledgementRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { BeneficiaryAcknowledgementRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool? enableViewHousehold, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( BeneficiaryAcknowledgementRoute.name, args: BeneficiaryAcknowledgementRouteArgs( @@ -293,8 +357,8 @@ class BeneficiaryAcknowledgementRoute static const String name = 'BeneficiaryAcknowledgementRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class BeneficiaryAcknowledgementRouteArgs { @@ -304,9 +368,9 @@ class BeneficiaryAcknowledgementRouteArgs { this.enableViewHousehold, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool? enableViewHousehold; @@ -317,13 +381,57 @@ class BeneficiaryAcknowledgementRouteArgs { } /// generated route for -/// [_i2.BeneficiaryDetailsPage] +/// [_i2.BeneficiaryChecklistPage] +class BeneficiaryChecklistRoute + extends _i25.PageRouteInfo { + BeneficiaryChecklistRoute({ + _i26.Key? key, + String? beneficiaryClientRefId, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, + }) : super( + BeneficiaryChecklistRoute.name, + args: BeneficiaryChecklistRouteArgs( + key: key, + beneficiaryClientRefId: beneficiaryClientRefId, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'BeneficiaryChecklistRoute'; + + static const _i25.PageInfo page = + _i25.PageInfo(name); +} + +class BeneficiaryChecklistRouteArgs { + const BeneficiaryChecklistRouteArgs({ + this.key, + this.beneficiaryClientRefId, + this.appLocalizations, + }); + + final _i26.Key? key; + + final String? beneficiaryClientRefId; + + final _i27.RegistrationDeliveryLocalization? appLocalizations; + + @override + String toString() { + return 'BeneficiaryChecklistRouteArgs{key: $key, beneficiaryClientRefId: $beneficiaryClientRefId, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i3.BeneficiaryDetailsPage] class BeneficiaryDetailsRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { BeneficiaryDetailsRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( BeneficiaryDetailsRoute.name, args: BeneficiaryDetailsRouteArgs( @@ -335,8 +443,8 @@ class BeneficiaryDetailsRoute static const String name = 'BeneficiaryDetailsRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class BeneficiaryDetailsRouteArgs { @@ -345,9 +453,9 @@ class BeneficiaryDetailsRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -356,13 +464,13 @@ class BeneficiaryDetailsRouteArgs { } /// generated route for -/// [_i3.BeneficiaryRegistrationWrapperPage] +/// [_i4.BeneficiaryRegistrationWrapperPage] class BeneficiaryRegistrationWrapperRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { BeneficiaryRegistrationWrapperRoute({ - _i21.Key? key, - required _i23.BeneficiaryRegistrationState initialState, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + required _i28.BeneficiaryRegistrationState initialState, + List<_i25.PageRouteInfo>? children, }) : super( BeneficiaryRegistrationWrapperRoute.name, args: BeneficiaryRegistrationWrapperRouteArgs( @@ -374,8 +482,8 @@ class BeneficiaryRegistrationWrapperRoute static const String name = 'BeneficiaryRegistrationWrapperRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class BeneficiaryRegistrationWrapperRouteArgs { @@ -384,9 +492,9 @@ class BeneficiaryRegistrationWrapperRouteArgs { required this.initialState, }); - final _i21.Key? key; + final _i26.Key? key; - final _i23.BeneficiaryRegistrationState initialState; + final _i28.BeneficiaryRegistrationState initialState; @override String toString() { @@ -395,14 +503,14 @@ class BeneficiaryRegistrationWrapperRouteArgs { } /// generated route for -/// [_i4.BeneficiaryWrapperPage] +/// [_i5.BeneficiaryWrapperPage] class BeneficiaryWrapperRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { BeneficiaryWrapperRoute({ - _i21.Key? key, - required _i24.HouseholdMemberWrapper wrapper, + _i26.Key? key, + required _i29.HouseholdMemberWrapper wrapper, bool isEditing = false, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( BeneficiaryWrapperRoute.name, args: BeneficiaryWrapperRouteArgs( @@ -415,8 +523,8 @@ class BeneficiaryWrapperRoute static const String name = 'BeneficiaryWrapperRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class BeneficiaryWrapperRouteArgs { @@ -426,9 +534,9 @@ class BeneficiaryWrapperRouteArgs { this.isEditing = false, }); - final _i21.Key? key; + final _i26.Key? key; - final _i24.HouseholdMemberWrapper wrapper; + final _i29.HouseholdMemberWrapper wrapper; final bool isEditing; @@ -439,14 +547,14 @@ class BeneficiaryWrapperRouteArgs { } /// generated route for -/// [_i5.DeliverInterventionPage] +/// [_i6.DeliverInterventionPage] class DeliverInterventionRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { DeliverInterventionRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool isEditing = false, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( DeliverInterventionRoute.name, args: DeliverInterventionRouteArgs( @@ -459,8 +567,8 @@ class DeliverInterventionRoute static const String name = 'DeliverInterventionRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class DeliverInterventionRouteArgs { @@ -470,9 +578,9 @@ class DeliverInterventionRouteArgs { this.isEditing = false, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool isEditing; @@ -483,13 +591,52 @@ class DeliverInterventionRouteArgs { } /// generated route for -/// [_i6.DoseAdministeredPage] +/// [_i7.DeliverySummaryPage] +class DeliverySummaryRoute + extends _i25.PageRouteInfo { + DeliverySummaryRoute({ + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, + }) : super( + DeliverySummaryRoute.name, + args: DeliverySummaryRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'DeliverySummaryRoute'; + + static const _i25.PageInfo page = + _i25.PageInfo(name); +} + +class DeliverySummaryRouteArgs { + const DeliverySummaryRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i26.Key? key; + + final _i27.RegistrationDeliveryLocalization? appLocalizations; + + @override + String toString() { + return 'DeliverySummaryRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i8.DoseAdministeredPage] class DoseAdministeredRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { DoseAdministeredRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( DoseAdministeredRoute.name, args: DoseAdministeredRouteArgs( @@ -501,8 +648,8 @@ class DoseAdministeredRoute static const String name = 'DoseAdministeredRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class DoseAdministeredRouteArgs { @@ -511,9 +658,9 @@ class DoseAdministeredRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -522,13 +669,13 @@ class DoseAdministeredRouteArgs { } /// generated route for -/// [_i7.FacilitySelectionPage] +/// [_i9.FacilitySelectionPage] class FacilitySelectionRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { FacilitySelectionRoute({ - _i21.Key? key, - required List<_i25.FacilityModel> facilities, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + required List<_i30.FacilityModel> facilities, + List<_i25.PageRouteInfo>? children, }) : super( FacilitySelectionRoute.name, args: FacilitySelectionRouteArgs( @@ -540,8 +687,8 @@ class FacilitySelectionRoute static const String name = 'FacilitySelectionRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class FacilitySelectionRouteArgs { @@ -550,9 +697,9 @@ class FacilitySelectionRouteArgs { required this.facilities, }); - final _i21.Key? key; + final _i26.Key? key; - final List<_i25.FacilityModel> facilities; + final List<_i30.FacilityModel> facilities; @override String toString() { @@ -561,13 +708,51 @@ class FacilitySelectionRouteArgs { } /// generated route for -/// [_i8.HouseHoldDetailsPage] +/// [_i10.HouseDetailsPage] +class HouseDetailsRoute extends _i25.PageRouteInfo { + HouseDetailsRoute({ + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, + }) : super( + HouseDetailsRoute.name, + args: HouseDetailsRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'HouseDetailsRoute'; + + static const _i25.PageInfo page = + _i25.PageInfo(name); +} + +class HouseDetailsRouteArgs { + const HouseDetailsRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i26.Key? key; + + final _i27.RegistrationDeliveryLocalization? appLocalizations; + + @override + String toString() { + return 'HouseDetailsRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i11.HouseHoldDetailsPage] class HouseHoldDetailsRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { HouseHoldDetailsRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( HouseHoldDetailsRoute.name, args: HouseHoldDetailsRouteArgs( @@ -579,8 +764,8 @@ class HouseHoldDetailsRoute static const String name = 'HouseHoldDetailsRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class HouseHoldDetailsRouteArgs { @@ -589,9 +774,9 @@ class HouseHoldDetailsRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -600,14 +785,14 @@ class HouseHoldDetailsRouteArgs { } /// generated route for -/// [_i9.HouseholdAcknowledgementPage] +/// [_i12.HouseholdAcknowledgementPage] class HouseholdAcknowledgementRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { HouseholdAcknowledgementRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool? enableViewHousehold, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( HouseholdAcknowledgementRoute.name, args: HouseholdAcknowledgementRouteArgs( @@ -620,8 +805,8 @@ class HouseholdAcknowledgementRoute static const String name = 'HouseholdAcknowledgementRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class HouseholdAcknowledgementRouteArgs { @@ -631,9 +816,9 @@ class HouseholdAcknowledgementRouteArgs { this.enableViewHousehold, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool? enableViewHousehold; @@ -644,13 +829,13 @@ class HouseholdAcknowledgementRouteArgs { } /// generated route for -/// [_i10.HouseholdLocationPage] +/// [_i13.HouseholdLocationPage] class HouseholdLocationRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { HouseholdLocationRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( HouseholdLocationRoute.name, args: HouseholdLocationRouteArgs( @@ -662,8 +847,8 @@ class HouseholdLocationRoute static const String name = 'HouseholdLocationRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class HouseholdLocationRouteArgs { @@ -672,9 +857,9 @@ class HouseholdLocationRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -683,13 +868,13 @@ class HouseholdLocationRouteArgs { } /// generated route for -/// [_i11.HouseholdOverviewPage] +/// [_i14.HouseholdOverviewPage] class HouseholdOverviewRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { HouseholdOverviewRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( HouseholdOverviewRoute.name, args: HouseholdOverviewRouteArgs( @@ -701,8 +886,8 @@ class HouseholdOverviewRoute static const String name = 'HouseholdOverviewRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class HouseholdOverviewRouteArgs { @@ -711,9 +896,9 @@ class HouseholdOverviewRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -722,14 +907,14 @@ class HouseholdOverviewRouteArgs { } /// generated route for -/// [_i12.IndividualDetailsPage] +/// [_i15.IndividualDetailsPage] class IndividualDetailsRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { IndividualDetailsRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool isHeadOfHousehold = false, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( IndividualDetailsRoute.name, args: IndividualDetailsRouteArgs( @@ -742,8 +927,8 @@ class IndividualDetailsRoute static const String name = 'IndividualDetailsRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class IndividualDetailsRouteArgs { @@ -753,9 +938,9 @@ class IndividualDetailsRouteArgs { this.isHeadOfHousehold = false, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool isHeadOfHousehold; @@ -766,14 +951,14 @@ class IndividualDetailsRouteArgs { } /// generated route for -/// [_i13.ReasonForDeletionPage] +/// [_i16.ReasonForDeletionPage] class ReasonForDeletionRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { ReasonForDeletionRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool isHousholdDelete = false, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( ReasonForDeletionRoute.name, args: ReasonForDeletionRouteArgs( @@ -786,8 +971,8 @@ class ReasonForDeletionRoute static const String name = 'ReasonForDeletionRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class ReasonForDeletionRouteArgs { @@ -797,9 +982,9 @@ class ReasonForDeletionRouteArgs { this.isHousholdDelete = false, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool isHousholdDelete; @@ -810,14 +995,14 @@ class ReasonForDeletionRouteArgs { } /// generated route for -/// [_i14.RecordPastDeliveryDetailsPage] +/// [_i17.RecordPastDeliveryDetailsPage] class RecordPastDeliveryDetailsRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { RecordPastDeliveryDetailsRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i26.TaskModel>? tasks, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i31.TaskModel>? tasks, + List<_i25.PageRouteInfo>? children, }) : super( RecordPastDeliveryDetailsRoute.name, args: RecordPastDeliveryDetailsRouteArgs( @@ -830,8 +1015,8 @@ class RecordPastDeliveryDetailsRoute static const String name = 'RecordPastDeliveryDetailsRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class RecordPastDeliveryDetailsRouteArgs { @@ -841,11 +1026,11 @@ class RecordPastDeliveryDetailsRouteArgs { this.tasks, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; - final List<_i26.TaskModel>? tasks; + final List<_i31.TaskModel>? tasks; @override String toString() { @@ -854,15 +1039,15 @@ class RecordPastDeliveryDetailsRouteArgs { } /// generated route for -/// [_i15.ReferBeneficiaryPage] +/// [_i18.ReferBeneficiaryPage] class ReferBeneficiaryRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { ReferBeneficiaryRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool isEditing = false, required String projectBeneficiaryClientRefId, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( ReferBeneficiaryRoute.name, args: ReferBeneficiaryRouteArgs( @@ -876,8 +1061,8 @@ class ReferBeneficiaryRoute static const String name = 'ReferBeneficiaryRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class ReferBeneficiaryRouteArgs { @@ -888,9 +1073,9 @@ class ReferBeneficiaryRouteArgs { required this.projectBeneficiaryClientRefId, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool isEditing; @@ -903,9 +1088,48 @@ class ReferBeneficiaryRouteArgs { } /// generated route for -/// [_i16.RegistrationDeliveryWrapperPage] -class RegistrationDeliveryWrapperRoute extends _i20.PageRouteInfo { - const RegistrationDeliveryWrapperRoute({List<_i20.PageRouteInfo>? children}) +/// [_i19.RefusedDeliveryPage] +class RefusedDeliveryRoute + extends _i25.PageRouteInfo { + RefusedDeliveryRoute({ + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, + }) : super( + RefusedDeliveryRoute.name, + args: RefusedDeliveryRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'RefusedDeliveryRoute'; + + static const _i25.PageInfo page = + _i25.PageInfo(name); +} + +class RefusedDeliveryRouteArgs { + const RefusedDeliveryRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i26.Key? key; + + final _i27.RegistrationDeliveryLocalization? appLocalizations; + + @override + String toString() { + return 'RefusedDeliveryRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} + +/// generated route for +/// [_i20.RegistrationDeliveryWrapperPage] +class RegistrationDeliveryWrapperRoute extends _i25.PageRouteInfo { + const RegistrationDeliveryWrapperRoute({List<_i25.PageRouteInfo>? children}) : super( RegistrationDeliveryWrapperRoute.name, initialChildren: children, @@ -913,17 +1137,17 @@ class RegistrationDeliveryWrapperRoute extends _i20.PageRouteInfo { static const String name = 'RegistrationDeliveryWrapperRoute'; - static const _i20.PageInfo page = _i20.PageInfo(name); + static const _i25.PageInfo page = _i25.PageInfo(name); } /// generated route for -/// [_i17.SearchBeneficiaryPage] +/// [_i21.SearchBeneficiaryPage] class SearchBeneficiaryRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { SearchBeneficiaryRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - List<_i20.PageRouteInfo>? children, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, }) : super( SearchBeneficiaryRoute.name, args: SearchBeneficiaryRouteArgs( @@ -935,8 +1159,8 @@ class SearchBeneficiaryRoute static const String name = 'SearchBeneficiaryRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class SearchBeneficiaryRouteArgs { @@ -945,9 +1169,9 @@ class SearchBeneficiaryRouteArgs { this.appLocalizations, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; @override String toString() { @@ -956,14 +1180,14 @@ class SearchBeneficiaryRouteArgs { } /// generated route for -/// [_i18.SideEffectsPage] -class SideEffectsRoute extends _i20.PageRouteInfo { +/// [_i22.SideEffectsPage] +class SideEffectsRoute extends _i25.PageRouteInfo { SideEffectsRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, - required List<_i26.TaskModel> tasks, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + required List<_i31.TaskModel> tasks, bool isEditing = false, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( SideEffectsRoute.name, args: SideEffectsRouteArgs( @@ -977,8 +1201,8 @@ class SideEffectsRoute extends _i20.PageRouteInfo { static const String name = 'SideEffectsRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class SideEffectsRouteArgs { @@ -989,11 +1213,11 @@ class SideEffectsRouteArgs { this.isEditing = false, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; - final List<_i26.TaskModel> tasks; + final List<_i31.TaskModel> tasks; final bool isEditing; @@ -1004,14 +1228,14 @@ class SideEffectsRouteArgs { } /// generated route for -/// [_i19.SplashAcknowledgementPage] +/// [_i23.SplashAcknowledgementPage] class SplashAcknowledgementRoute - extends _i20.PageRouteInfo { + extends _i25.PageRouteInfo { SplashAcknowledgementRoute({ - _i21.Key? key, - _i22.RegistrationDeliveryLocalization? appLocalizations, + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, bool? enableBackToSearch, - List<_i20.PageRouteInfo>? children, + List<_i25.PageRouteInfo>? children, }) : super( SplashAcknowledgementRoute.name, args: SplashAcknowledgementRouteArgs( @@ -1024,8 +1248,8 @@ class SplashAcknowledgementRoute static const String name = 'SplashAcknowledgementRoute'; - static const _i20.PageInfo page = - _i20.PageInfo(name); + static const _i25.PageInfo page = + _i25.PageInfo(name); } class SplashAcknowledgementRouteArgs { @@ -1035,9 +1259,9 @@ class SplashAcknowledgementRouteArgs { this.enableBackToSearch, }); - final _i21.Key? key; + final _i26.Key? key; - final _i22.RegistrationDeliveryLocalization? appLocalizations; + final _i27.RegistrationDeliveryLocalization? appLocalizations; final bool? enableBackToSearch; @@ -1046,3 +1270,41 @@ class SplashAcknowledgementRouteArgs { return 'SplashAcknowledgementRouteArgs{key: $key, appLocalizations: $appLocalizations, enableBackToSearch: $enableBackToSearch}'; } } + +/// generated route for +/// [_i24.SummaryPage] +class SummaryRoute extends _i25.PageRouteInfo { + SummaryRoute({ + _i26.Key? key, + _i27.RegistrationDeliveryLocalization? appLocalizations, + List<_i25.PageRouteInfo>? children, + }) : super( + SummaryRoute.name, + args: SummaryRouteArgs( + key: key, + appLocalizations: appLocalizations, + ), + initialChildren: children, + ); + + static const String name = 'SummaryRoute'; + + static const _i25.PageInfo page = + _i25.PageInfo(name); +} + +class SummaryRouteArgs { + const SummaryRouteArgs({ + this.key, + this.appLocalizations, + }); + + final _i26.Key? key; + + final _i27.RegistrationDeliveryLocalization? appLocalizations; + + @override + String toString() { + return 'SummaryRouteArgs{key: $key, appLocalizations: $appLocalizations}'; + } +} diff --git a/packages/registration_delivery/lib/utils/constants.dart b/packages/registration_delivery/lib/utils/constants.dart index 973ddda76..a3f9de2ad 100644 --- a/packages/registration_delivery/lib/utils/constants.dart +++ b/packages/registration_delivery/lib/utils/constants.dart @@ -9,6 +9,8 @@ class Constants { final String deliveryTeam = 'Delivery Team'; final String notAvailable = 'N/A'; final String dateTimeExtFormat = 'dd-MM-yyyy'; + final String dateMonthYearFormat = 'dd MMM yyyy'; + static const String checklistViewDateFormat = 'dd/MM/yyyy hh:mm a'; } class KeyValue { @@ -29,3 +31,13 @@ class StatusKeys { StatusKeys(this.isNotEligible, this.isBeneficiaryRefused, this.isBeneficiaryReferred, this.isStatusReset); } + +class TaskResourceInfo { + String productName; + String quantityDelivered; + + TaskResourceInfo( + this.productName, + this.quantityDelivered, + ); +} diff --git a/packages/registration_delivery/lib/utils/global_search_parameters.dart b/packages/registration_delivery/lib/utils/global_search_parameters.dart new file mode 100644 index 000000000..dfee00637 --- /dev/null +++ b/packages/registration_delivery/lib/utils/global_search_parameters.dart @@ -0,0 +1,25 @@ +class GlobalSearchParameters { + final bool isProximityEnabled; + final double? latitude; + final String? projectId; + final double? longitude; + final double? maxRadius; + final String? nameSearch; + final int? offset; + final int? limit; + final List? filter; + final int? totalCount; + + GlobalSearchParameters({ + required this.isProximityEnabled, + required this.latitude, + required this.longitude, + required this.maxRadius, + required this.nameSearch, + required this.offset, + required this.limit, + required this.filter, + this.totalCount, + this.projectId + }); +} diff --git a/packages/registration_delivery/lib/utils/i18_key_constants.dart b/packages/registration_delivery/lib/utils/i18_key_constants.dart index 5fa02c710..671c89cb8 100644 --- a/packages/registration_delivery/lib/utils/i18_key_constants.dart +++ b/packages/registration_delivery/lib/utils/i18_key_constants.dart @@ -17,6 +17,7 @@ const householdDetailsShowcase = HouseholdDetailsShowcase(); const individualDetailsShowcase = IndividualDetailsShowcase(); const householdOverviewShowcase = HouseholdOverviewShowcase(); const deliverInterventionShowcase = DeliverInterventionShowcase(); +const checklist = Checklist(); class Common { const Common(); @@ -113,6 +114,12 @@ class Common { String get scanBales => 'CORE_COMMON_SCAN_BALES'; String get ageInMonths => 'AGE_IN_MONTHS_LABEL'; + String get locationCapturing => 'CAPTURING_LOCATION'; + String get locationCaptured => 'LOCATION_CAPTURED'; + String get coreCommonSummaryDetails => 'CORE_COMMON_SUMMARY_DETAILS'; + + String get metersNear => 'METERS_NEAR'; + String get coreCommonLoadingText => 'CORE_COMMON_LOADING_TEXT'; } class SearchBeneficiary { @@ -140,6 +147,12 @@ class SearchBeneficiary { String get iconLabel => 'ICON_LABEL'; + String get filterLabel => 'FILTER_LABEL'; + + String get clearFilter => 'CLEAR_FILTER'; + + String get applyFilter => 'APPLY_FILTER'; + String get yearsAbbr => 'YEARS_ABBR'; String get monthsAbbr => 'MONTHS_ABBR'; @@ -227,6 +240,7 @@ class BeneficiaryDetails { String get recordCycle => 'BENEFICIARY_DETAILS_RECORD_CYCLE'; String get householdMemberSingular => 'BENEFICIARY_HOUSEHOLD_MEMBER'; String get householdMemberPlural => 'BENEFICIARY_HOUSEHOLD_MEMBERS'; + String get totalMembers => 'TOTAL_HOUSEHOLD_MEMBERS'; } class IndividualDetails { @@ -283,7 +297,11 @@ class HouseholdLocation { String get householdLocationLabelText => 'HOUSEHOLD_LOCATION_LABEL_TEXT'; + String get householdLocationDescriptionText => + 'HOUSEHOLD_LOCATION_DESCRIPTION_TEXT'; + String get administrationAreaFormLabel => 'ADMINISTRATION_AREA_FORM_LABEL'; + String get gpsAccuracyLabel => 'CLOSE_HOUSEHOLD_GPS_ACCURACY_LABEL'; String get administrationAreaRequiredValidation => 'HOUSEHOLD_LOCATION_ADMINISTRATION_AREA_REQUIRED_VALIDATION'; @@ -293,6 +311,8 @@ class HouseholdLocation { String get landmarkFormLabel => 'LANDMARK_FORM_LABEL'; + String get villageLabel => 'VILLAGE_LABEL'; + String get householdAddressLine2LabelText => 'HOUSEHOLD_ADDRESS_LINE_2_FORM_LABEL'; @@ -316,19 +336,68 @@ class AcknowledgementSuccess { String get dataDownloadedSuccessLabel => 'DATA_DOWNLOADED_SUCCESS_LABEL'; } +class Checklist { + const Checklist(); + + String get checklist => 'CHECKLIST'; + + String get checklistlabel => 'CHECKLIST_LABEL'; + + String get checklistCreateActionLabel => 'CHECKLIST_CREATE_ACTION_LABEL'; + + String get checklistViewActionLabel => 'CHECKLIST_VIEW_ACTION_LABEL'; + + String get checklistDetailLabel => 'CHECKLIST_DETAILS_LABEL'; + + String get checklistDialogLabel => 'CHECKLIST_DIALOG_LABEL'; + + String get checklistDialogDescription => 'CHECKLIST_DIALOG_DESCRITPTION'; + + String get checklistDialogPrimaryAction => 'CHECKLIST_DIALOG_PRIMARY_ACTION'; + + String get checklistDialogSecondaryAction => + 'CHECKLIST_DIALOG_SECONDARY_ACTION'; + + String get checklistdate => 'CHECKLIST_DATE'; + + String get checklistReasonRequiredError => 'CHECKLIST_REASON_REQUIRED_ERROR'; + + String get notSelectedKey => 'NOT_SELECTED'; + + String get checklistBackDialogLabel => 'CHECKLIST_BACK_DIALOG_LABEL'; + + String get checklistBackDialogDescription => + 'CHECKLIST_BACK_DIALOG_DESCRITPTION'; + + String get checklistBackDialogPrimaryAction => + 'CHECKLIST_BACK_DIALOG_PRIMARY_ACTION'; + + String get checklistBackDialogSecondaryAction => + 'CHECKLIST_BACK_DIALOG_SECONDARY_ACTION'; +} + class HouseholdDetails { const HouseholdDetails(); String get householdDetailsLabel => 'HOUSEHOLD_DETAILS_LABEL'; + String get householdDetailsDescription => 'HOUSEHOLD_DETAILS_DESCRIPTION'; + String get actionLabel => 'HOUSEHOLD_ACTION_LABEL'; String get dateOfRegistrationLabel => 'HOUSEHOLD_DETAILS_DATE_OF_REGISTRATION_LABEL'; String get noOfMembersCountLabel => 'NO_OF_MEMBERS_COUNT_LABEL'; + String get noOfPregnantWomenCountLabel => 'NO_OF_PREGNANT_WOMEN_LABEL'; + String get noOfChildrenBelow5YearsLabel => 'NO_OF_CHILDREN_BELOW_5_YR_LABEL'; String get viewHouseHoldDetailsAction => 'VIEW_HOUSEHOLD_DETAILS_ACTION_LABEL'; + String get noOfRoomsLabel => 'NO_OF_ROOMS_LABEL'; + String get houseDetailsLabel => 'HOUSE_DETAILS_LABEL'; + String get selectStructureTypeError => 'PLEASE_SELECT_STRUCTURE_TYPE'; + String get memberCountError => 'MEMBER_COUNT_ERROR'; + String get typeOfStructure => 'TYPE_OF_STRUCTURE'; } class HouseholdOverView { @@ -357,6 +426,12 @@ class HouseholdOverView { String get householdOverViewDeliveredIconLabel => 'HOUSEHOLD_OVER_VIEW_DELIVERED_ICON_LABEL'; + String get householdOverViewRegisteredIconLabel => + 'HOUSEHOLD_OVER_VIEW_REGISTERED_ICON_LABEL'; + + String get householdOverViewNotRegisteredIconLabel => + 'HOUSEHOLD_OVER_VIEW_NOT_REGISTERED_ICON_LABEL'; + String get householdOverViewNotDeliveredIconLabel => 'HOUSEHOLD_OVER_VIEW_NOT_DELIVERED_ICON_LABEL'; @@ -420,6 +495,13 @@ class DeliverIntervention { const DeliverIntervention(); String get deliverInterventionLabel => 'DELIVER_INTERVENTION_LABEL'; + String get beneficiaryChecklistDialogTitle => + 'BENEFICIARY_CHECKLIST_DIALOG_TITLE'; + + String get refusedDeliveryLabel => 'REFUSED_DELIVERY_LABEL'; + String get refusedDeliveryVisitDateLabel => 'REFUSED_DELIVERY_VISIT_DATE'; + String get reasonForRefusalLabel => 'REASON_FOR_REFUSAL_LABEL'; + String get reasonForRefusalCommentLabel => 'REASON_FOR_REFUSAL_COMMENT_LABEL'; String get deliverInterventionResourceLabel => 'DELIVER_INTERVENTION_RESOURCE_LABEL'; @@ -430,6 +512,8 @@ class DeliverIntervention { String get resourceDeliveredLabel => 'DELIVER_INTERVENTION_RESOURCE_DELIVERED_LABEL'; + String get typeOfResourceUsed => 'TYPE_OF_RESOURCE_USED'; + String get resourceDeliveredError => 'DELIVER_INTERVENTION_RESOURCE_DELIVERED_ERROR'; @@ -438,6 +522,11 @@ class DeliverIntervention { String get deliveryCommentLabel => 'DELIVER_INTERVENTION_DELIVERY_COMMENT_LABEL'; + String get deliveryCommentHeading => + 'DELIVER_INTERVENTION_DELIVERY_COMMENT_HEADING'; + + String get deliveryDetailsLabel => + 'DELIVER_INTERVENTION_DELIVERY_DETAILS_LABEL'; String get idTypeText => 'DELIVER_INTERVENTION_ID_TYPE_TEXT'; @@ -647,6 +736,10 @@ class HouseholdLocationShowcase { return 'HOUSEHOLD_LOCATION_SHOWCASE_ADMINISTRATIVE_AREA'; } + String get gpsAccuracy { + return 'HOUSEHOLD_LOCATION_SHOWCASE_GPS_ACCURACY_LABEL'; + } + String get landmark { return 'HOUSEHOLD_LOCATION_SHOWCASE_LANDMARK'; } @@ -670,6 +763,17 @@ class HouseholdDetailsShowcase { String get numberOfMembersLivingInHousehold { return 'HOUSEHOLD_DETAILS_SHOWCASE_NUMBER_OF_MEMBERS_LIVING_IN_HOUSEHOLD'; } + + String get numberOfPregnantWomenInHousehold => + 'HOUSEHOLD_DETAILS_SHOWCASE_NO_OF_PREGNANT_WOMEN_IN_HOUSEHOLD'; + + String get numberOfChildrenBelow5InHousehold => + 'HOUSEHOLD_DETAILS_SHOWCASE_NO_OF_CHILD_BELOW_5_IN_HOUSEHOLD'; + + String get numberOfRoomsInHousehold => + 'HOUSE_DETAILS_SHOWCASE_NO_OF_ROOMS_IN_HOUSEHOLD'; + + String get typeOfStructure => 'HOUSE_DETAILS_SHOWCASE_TYPE_OF_STRUCTURE'; } class IndividualDetailsShowcase { @@ -751,6 +855,18 @@ class HouseholdOverviewShowcase { class DeliverInterventionShowcase { const DeliverInterventionShowcase(); + String get dateOfVisitLabel { + return 'DELIVER_INTERVENTION_SHOWCASE_MEMBER_COUNT'; + } + + String get reasonOfRefusalLabel { + return 'DELIVER_INTERVENTION_SHOWCASE_NUMBER_OF_BEDNETS_TO_DELIVER'; + } + + String get commentLabel { + return 'DELIVER_INTERVENTION_SHOWCASE_NUMBER_OF_BEDNETS_DISTRIBUTED'; + } + String get memberCount { return 'DELIVER_INTERVENTION_SHOWCASE_MEMBER_COUNT'; } diff --git a/packages/registration_delivery/lib/utils/utils.dart b/packages/registration_delivery/lib/utils/utils.dart index d443382e6..1b40a62af 100644 --- a/packages/registration_delivery/lib/utils/utils.dart +++ b/packages/registration_delivery/lib/utils/utils.dart @@ -6,6 +6,7 @@ import 'package:digit_components/utils/date_utils.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:formula_parser/formula_parser.dart'; import 'package:reactive_forms/reactive_forms.dart'; +import 'package:registration_delivery/models/entities/household.dart'; import '../models/entities/additional_fields_type.dart'; import '../models/entities/referral.dart'; @@ -47,16 +48,14 @@ class CustomValidator { ) { if (control.value != null && control.value.toString().isNotEmpty && - control.value.toString().length < 10) { + control.value.toString().length < 9) { return {'minLength': true}; } } } bool checkStatus(List? tasks, ProjectCycle? currentCycle) { - if (currentCycle == null || - currentCycle.startDate == null || - currentCycle.endDate == null) { + if (currentCycle == null) { return false; } @@ -91,7 +90,7 @@ bool checkIfBeneficiaryRefused( ) { final isBeneficiaryRefused = (tasks != null && (tasks ?? []).isNotEmpty && - tasks.last.status == Status.beneficiaryRefused.toValue()); + tasks.last.status == Status.administeredFailed.toValue()); return isBeneficiaryRefused; } @@ -183,19 +182,34 @@ bool checkIfBeneficiaryReferred( } } -DeliveryDoseCriteria? fetchProductVariant( - ProjectCycleDelivery? currentDelivery, - IndividualModel? individualModel, -) { - if (currentDelivery != null && individualModel != null) { - final individualAge = DigitDateUtils.calculateAge( - DigitDateUtils.getFormattedDateToDateTime( - individualModel.dateOfBirth!, - ) ?? - DateTime.now(), - ); - final individualAgeInMonths = - individualAge.years * 12 + individualAge.months; +DeliveryDoseCriteria? fetchProductVariant(ProjectCycleDelivery? currentDelivery, + IndividualModel? individualModel, HouseholdModel? householdModel) { + if (currentDelivery != null) { + var individualAgeInMonths = 0; + var gender; + var roomCount; + var memberCount; + + if (individualModel != null) { + final individualAge = DigitDateUtils.calculateAge( + DigitDateUtils.getFormattedDateToDateTime( + individualModel.dateOfBirth!, + ) ?? + DateTime.now(), + ); + individualAgeInMonths = individualAge.years * 12 + individualAge.months; + + gender = individualModel.gender?.index; + } + if (householdModel != null && householdModel.additionalFields != null) { + memberCount = householdModel.memberCount; + roomCount = int.tryParse(householdModel.additionalFields?.fields + .where((h) => h.key == AdditionalFieldsType.noOfRooms.toValue()) + .firstOrNull + ?.value + .toString() ?? + '1')!; + } final filteredCriteria = currentDelivery.doseCriteria?.where((criteria) { final condition = criteria.condition; @@ -208,8 +222,9 @@ DeliveryDoseCriteria? fetchProductVariant( element, { 'age': individualAgeInMonths, - if (individualModel.gender != null) - 'gender': individualModel.gender?.index, + if (gender != null) 'gender': gender, + if (memberCount != null) 'memberCount': memberCount, + if (roomCount != null) 'roomCount': roomCount }, ); final error = expression.parse; @@ -291,7 +306,7 @@ class RegistrationDeliverySingleton { String? _tenantId; String? _loggedInUserUuid; - + UserModel? _loggedInUser; double? _maxRadius; String? _projectId; BeneficiaryType? _beneficiaryType; @@ -306,7 +321,10 @@ class RegistrationDeliverySingleton { List? _householdMemberDeletionReasonOptions; List? _deliveryCommentOptions; List? _symptomsTypes; + List? _searchHouseHoldFilter; List? _referralReasons; + List? _houseStructureTypes; + List? _refusalReasons; void setBoundary({required BoundaryModel boundary}) { _boundaryModel = boundary; @@ -317,20 +335,25 @@ class RegistrationDeliverySingleton { _persistenceConfiguration = persistenceConfiguration; } - void setInitialData( - {required String loggedInUserUuid, - required double maxRadius, - required String projectId, - required BeneficiaryType selectedBeneficiaryType, - required ProjectTypeModel? projectType, - required ProjectModel selectedProject, - required List? genderOptions, - required List? idTypeOptions, - required List? householdDeletionReasonOptions, - required List? householdMemberDeletionReasonOptions, - required List? deliveryCommentOptions, - required List? symptomsTypes, - required List? referralReasons}) { + void setInitialData({ + required String loggedInUserUuid, + required double maxRadius, + required String projectId, + required BeneficiaryType selectedBeneficiaryType, + required ProjectTypeModel? projectType, + required ProjectModel selectedProject, + required List? genderOptions, + required List? idTypeOptions, + required List? householdDeletionReasonOptions, + required List? householdMemberDeletionReasonOptions, + required List? deliveryCommentOptions, + required List? symptomsTypes, + required List? searchHouseHoldFilter, + required List? referralReasons, + required List? houseStructureTypes, + required List? refusalReasons, + required UserModel? loggedInUser, + }) { _loggedInUserUuid = loggedInUserUuid; _maxRadius = maxRadius; _projectId = projectId; @@ -344,7 +367,11 @@ class RegistrationDeliverySingleton { householdMemberDeletionReasonOptions; _deliveryCommentOptions = deliveryCommentOptions; _symptomsTypes = symptomsTypes; + _searchHouseHoldFilter = searchHouseHoldFilter; _referralReasons = referralReasons; + _houseStructureTypes = houseStructureTypes; + _refusalReasons = refusalReasons; + _loggedInUser = loggedInUser; } void setTenantId(String tenantId) { @@ -369,7 +396,11 @@ class RegistrationDeliverySingleton { _householdMemberDeletionReasonOptions; List? get deliveryCommentOptions => _deliveryCommentOptions; List? get symptomsTypes => _symptomsTypes; + List? get searchHouseHoldFilter => _searchHouseHoldFilter; List? get referralReasons => _referralReasons; + List? get houseStructureTypes => _houseStructureTypes; + List? get refusalReasons => _refusalReasons; + UserModel? get loggedInUser => _loggedInUser; } bool allDosesDelivered( @@ -417,3 +448,30 @@ bool allDosesDelivered( } } } + +Status getTaskStatus(Iterable tasks) { + final statusMap = { + Status.delivered.toValue(): Status.delivered, + Status.notAdministered.toValue(): Status.notAdministered, + Status.visited.toValue(): Status.visited, + Status.notVisited.toValue(): Status.notVisited, + Status.beneficiaryRefused.toValue(): Status.beneficiaryRefused, + Status.beneficiaryReferred.toValue(): Status.beneficiaryReferred, + Status.administeredSuccess.toValue(): Status.administeredSuccess, + Status.administeredFailed.toValue(): Status.administeredFailed, + Status.inComplete.toValue(): Status.inComplete, + Status.toAdminister.toValue(): Status.toAdminister, + Status.closeHousehold.toValue(): Status.closeHousehold, + }; + + if (tasks.isEmpty) { + return Status.registered.toValue(); + } else { + final mappedStatus = statusMap[tasks.last.status ?? Status.registered]; + if (mappedStatus != null) { + return mappedStatus; + } + } + + return Status.registered.toValue(); +} diff --git a/packages/registration_delivery/lib/widgets/beneficiary/beneficiary_card.dart b/packages/registration_delivery/lib/widgets/beneficiary/beneficiary_card.dart index fb191e0c5..753cf2918 100644 --- a/packages/registration_delivery/lib/widgets/beneficiary/beneficiary_card.dart +++ b/packages/registration_delivery/lib/widgets/beneficiary/beneficiary_card.dart @@ -6,16 +6,16 @@ import '../../models/entities/status.dart'; class BeneficiaryCard extends StatelessWidget { final String title; - final String subtitle; - final String description; + final String? subtitle; + final String? description; final String? status; final String? statusType; const BeneficiaryCard({ super.key, required this.title, - required this.subtitle, - required this.description, + this.subtitle, + this.description, this.status, this.statusType, }); @@ -37,7 +37,9 @@ class BeneficiaryCard extends StatelessWidget { ), Offstage( offstage: status == null, - child: status == Status.visited.toValue() + child: status == Status.visited.toValue() || + status == Status.registered.toValue() || + status == Status.administeredSuccess.toValue() ? DigitIconButton( icon: Icons.check_circle, iconText: RegistrationDeliveryLocalization.of(context) @@ -53,20 +55,22 @@ class BeneficiaryCard extends StatelessWidget { iconColor: theme.colorScheme.error, ), ), - Padding( - padding: const EdgeInsets.all(4), - child: Text( - subtitle, - style: theme.textTheme.bodyMedium, + if (subtitle != null) + Padding( + padding: const EdgeInsets.all(4), + child: Text( + subtitle!, + style: theme.textTheme.bodyMedium, + ), ), - ), - Padding( - padding: const EdgeInsets.all(4), - child: Text( - description, - style: theme.textTheme.bodySmall, + if (description != null) + Padding( + padding: const EdgeInsets.all(4), + child: Text( + description!, + style: theme.textTheme.bodySmall, + ), ), - ), ], ); } diff --git a/packages/registration_delivery/lib/widgets/beneficiary/resource_beneficiary_card.dart b/packages/registration_delivery/lib/widgets/beneficiary/resource_beneficiary_card.dart index 24a628d9f..e3b66c660 100644 --- a/packages/registration_delivery/lib/widgets/beneficiary/resource_beneficiary_card.dart +++ b/packages/registration_delivery/lib/widgets/beneficiary/resource_beneficiary_card.dart @@ -1,4 +1,5 @@ import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:reactive_forms/reactive_forms.dart'; @@ -24,10 +25,10 @@ class ResourceBeneficiaryCard extends LocalizedStatefulWidget { @override State createState() => - _ResourceBeneficiaryCardState(); + ResourceBeneficiaryCardState(); } -class _ResourceBeneficiaryCardState +class ResourceBeneficiaryCardState extends LocalizedState { @override Widget build(BuildContext context) { @@ -54,24 +55,28 @@ class _ResourceBeneficiaryCardState return productState.maybeWhen( orElse: () => const Offstage(), fetched: (productVariants) { - return DigitReactiveSearchDropdown( - label: localizations.translate( - i18.individualDetails.idTypeLabelText, - ), - form: widget.form, - menuItems: productVariants, - formControlName: 'resourceDelivered.${widget.cardIndex}', - valueMapper: (value) { - return localizations.translate( - value.sku ?? value.id, - ); - }, - isRequired: true, - validationMessage: localizations.translate( - i18.common.corecommonRequired, - ), - emptyText: localizations.translate(i18.common.noMatchFound), - ); + return + SelectionBox( + width: 116, + options: productVariants, + onSelectionChanged: (selectedOptions) { + if (selectedOptions.isNotEmpty) { + var selectedOption = selectedOptions.first; + widget.form.control('resourceDelivered.${widget.cardIndex}').value = selectedOption; + }else{ + widget.form.control('resourceDelivered.${widget.cardIndex}').value = null; + } + }, + initialSelection: widget.form.control('resourceDelivered.${widget.cardIndex}').value != null ? [ + widget.form.control('resourceDelivered.${widget.cardIndex}').value + ] : [], + valueMapper: (value) { + return localizations.translate( + value.sku ?? value.id, + ); + }, + allowMultipleSelection: false, + ); }, ); }, @@ -84,6 +89,7 @@ class _ResourceBeneficiaryCardState i18.deliverIntervention.quantityDistributedLabel, ), minimum: 1, + ), SizedBox( child: Align( diff --git a/packages/registration_delivery/lib/widgets/beneficiary/view_beneficiary_card.dart b/packages/registration_delivery/lib/widgets/beneficiary/view_beneficiary_card.dart index 683fe5b1f..9f49dbbc4 100644 --- a/packages/registration_delivery/lib/widgets/beneficiary/view_beneficiary_card.dart +++ b/packages/registration_delivery/lib/widgets/beneficiary/view_beneficiary_card.dart @@ -4,6 +4,7 @@ import 'package:digit_components/models/digit_table_model.dart'; import 'package:digit_components/utils/date_utils.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; +import 'package:registration_delivery/models/entities/project_beneficiary.dart'; import '../../blocs/search_households/search_households.dart'; import '../../models/entities/status.dart'; @@ -28,10 +29,10 @@ class ViewBeneficiaryCard extends LocalizedStatefulWidget { }); @override - State createState() => _ViewBeneficiaryCardState(); + State createState() => ViewBeneficiaryCardState(); } -class _ViewBeneficiaryCardState extends LocalizedState { +class ViewBeneficiaryCardState extends LocalizedState { late HouseholdMemberWrapper householdMember; @override @@ -46,7 +47,7 @@ class _ViewBeneficiaryCardState extends LocalizedState { super.didUpdateWidget(oldWidget); } - bool _isCardExpanded = true; + bool _isCardExpanded = false; bool get isCardExpanded => _isCardExpanded; @@ -82,37 +83,37 @@ class _ViewBeneficiaryCardState extends LocalizedState { final currentCycle = RegistrationDeliverySingleton().projectType?.cycles?.firstWhereOrNull( (e) => - (e.startDate!) < DateTime.now().millisecondsSinceEpoch && - (e.endDate!) > DateTime.now().millisecondsSinceEpoch, + (e.startDate) < DateTime.now().millisecondsSinceEpoch && + (e.endDate) > DateTime.now().millisecondsSinceEpoch, // Return null when no matching cycle is found ); - final tableData = householdMember.members.map( + final tableData = householdMember.members?.map( (e) { final projectBeneficiary = - RegistrationDeliverySingleton().beneficiaryType != - BeneficiaryType.individual - ? [householdMember.projectBeneficiaries.first] - : householdMember.projectBeneficiaries - .where( - (element) => - element.beneficiaryClientReferenceId == - e.clientReferenceId, - ) - .toList(); + householdMember.projectBeneficiaries?.where((element) { + if (RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.individual) { + return element.beneficiaryClientReferenceId == e.clientReferenceId; + } else { + return element.beneficiaryClientReferenceId == + householdMember.household!.clientReferenceId; + } + }).toList(); - final taskData = projectBeneficiary.isNotEmpty + final taskData = (projectBeneficiary ?? []).isNotEmpty && + householdMember.tasks != null ? householdMember.tasks ?.where((element) => element.projectBeneficiaryClientReferenceId == - projectBeneficiary.first.clientReferenceId) + projectBeneficiary?.first.clientReferenceId) .toList() : null; - final referralData = projectBeneficiary.isNotEmpty + final referralData = (projectBeneficiary ?? []).isNotEmpty ? householdMember.referrals ?.where((element) => element.projectBeneficiaryClientReferenceId == - projectBeneficiary.first.clientReferenceId) + projectBeneficiary?.first.clientReferenceId) .toList() : null; final sideEffects = taskData != null && taskData.isNotEmpty @@ -160,16 +161,14 @@ class _ViewBeneficiaryCardState extends LocalizedState { currentCycle, ); -// TODO need to pass the current cycle - final isStatusReset = checkStatus(taskData, currentCycle); final rowTableData = [ TableData( [ - e.name?.givenName, - e.name?.familyName, - ].whereNotNull().join('-'), + e.name?.givenName ?? '--', + (e.name?.familyName?.trim().isNotEmpty ?? false) ? e.name?.familyName : null, + ].whereNotNull().join(' '), cellKey: 'beneficiary', ), TableData( @@ -196,7 +195,7 @@ class _ViewBeneficiaryCardState extends LocalizedState { ), TableData( e.dateOfBirth == null - ? '' + ? '--' : '${DigitDateUtils.calculateAge( DigitDateUtils.getFormattedDateToDateTime( e.dateOfBirth!, @@ -211,7 +210,7 @@ class _ViewBeneficiaryCardState extends LocalizedState { cellKey: 'age', ), TableData( - e.gender?.name ?? '--', + e.gender?.name == null ? '--' : localizations.translate('CORE_COMMON_${ e.gender?.name.toUpperCase()}'), cellKey: 'gender', ), ]; @@ -229,17 +228,17 @@ class _ViewBeneficiaryCardState extends LocalizedState { ).toList(); final ageInYears = DigitDateUtils.calculateAge( - householdMember.headOfHousehold.dateOfBirth != null + householdMember.headOfHousehold?.dateOfBirth != null ? DigitDateUtils.getFormattedDateToDateTime( - householdMember.headOfHousehold.dateOfBirth!, + householdMember.headOfHousehold!.dateOfBirth!, ) ?? DateTime.now() : DateTime.now(), ).years; final ageInMonths = DigitDateUtils.calculateAge( - householdMember.headOfHousehold.dateOfBirth != null + householdMember.headOfHousehold?.dateOfBirth != null ? DigitDateUtils.getFormattedDateToDateTime( - householdMember.headOfHousehold.dateOfBirth!, + householdMember.headOfHousehold!.dateOfBirth!, ) ?? DateTime.now() : DateTime.now(), @@ -251,17 +250,27 @@ class _ViewBeneficiaryCardState extends LocalizedState { months: ageInMonths, ), RegistrationDeliverySingleton().projectType, - householdMember.tasks?.last, - householdMember.sideEffects, + (householdMember.tasks ?? []).isNotEmpty + ? householdMember.tasks?.last + : null, + (householdMember.sideEffects ?? []).isNotEmpty + ? householdMember.sideEffects + : null, ); final isBeneficiaryRefused = checkIfBeneficiaryRefused(householdMember.tasks); - final projectBeneficiary = householdMember.projectBeneficiaries - .where((p) => - p.beneficiaryClientReferenceId == - householdMember.headOfHousehold.clientReferenceId) - .firstOrNull; + final projectBeneficiary = householdMember.projectBeneficiaries?.where((p) { + if (RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.individual) { + return p.beneficiaryClientReferenceId == + householdMember.headOfHousehold?.clientReferenceId; + } else { + return p.beneficiaryClientReferenceId == + householdMember.household?.clientReferenceId; + } + }).firstOrNull; + final tasks = householdMember.tasks?.where((t) => t.projectBeneficiaryClientReferenceId == projectBeneficiary?.clientReferenceId); @@ -277,29 +286,28 @@ class _ViewBeneficiaryCardState extends LocalizedState { width: MediaQuery.of(context).size.width / 1.8, child: BeneficiaryCard( description: [ - householdMember.household.address?.doorNo, - householdMember.household.address?.addressLine1, - householdMember.household.address?.addressLine2, - householdMember.household.address?.landmark, - householdMember.household.address?.city, - householdMember.household.address?.pincode, + householdMember.household?.address?.doorNo, + householdMember.household?.address?.addressLine1, + householdMember.household?.address?.addressLine2, + householdMember.household?.address?.landmark, + householdMember.household?.address?.city, + householdMember.household?.address?.pincode, ].whereNotNull().take(2).join(' '), subtitle: widget.distance != null - ? '${householdMember.members.length ?? 1} ${householdMember.members.length == 1 ? localizations.translate(i18.beneficiaryDetails.householdMemberSingular) : localizations.translate(i18.beneficiaryDetails.householdMemberPlural)}\n${((widget.distance!) * 1000).round() > 999 ? '(${((widget.distance!).round())} km)' : '(${((widget.distance!) * 1000).round()} mts) ${localizations.translate(i18.beneficiaryDetails.fromCurrentLocation)}'}' - : '${householdMember.members.length ?? 1} ${householdMember.members.length == 1 ? localizations.translate(i18.beneficiaryDetails.householdMemberSingular) : localizations.translate(i18.beneficiaryDetails.householdMemberPlural)}', - status: RegistrationDeliverySingleton().beneficiaryType == - BeneficiaryType.individual - ? (tasks ?? []).isNotEmpty && - !isNotEligible && - !isBeneficiaryRefused - ? Status.visited.toValue() - : Status.notVisited.toValue() - : (tasks ?? []).isNotEmpty - ? Status.visited.toValue() - : Status.notVisited.toValue(), + ? '${householdMember.members?.length ?? 1} ${householdMember.members?.length == 1 ? localizations.translate(i18.beneficiaryDetails.householdMemberSingular) : localizations.translate(i18.beneficiaryDetails.householdMemberPlural)}\n${((widget.distance!) * 1000).round() > 999 ? '(${((widget.distance!).round())} km)' : '(${((widget.distance!) * 1000).round()} mts) ${localizations.translate(i18.beneficiaryDetails.fromCurrentLocation)}'}' + : '${householdMember.members?.length ?? 1} ${householdMember.members?.length == 1 ? localizations.translate(i18.beneficiaryDetails.householdMemberSingular) : localizations.translate(i18.beneficiaryDetails.householdMemberPlural)}', + status: getStatus( + tasks ?? [], + householdMember.projectBeneficiaries ?? [], + RegistrationDeliverySingleton().beneficiaryType == + BeneficiaryType.individual + ? isNotEligible + : false, + isBeneficiaryRefused), title: [ - householdMember.headOfHousehold.name?.givenName, - householdMember.headOfHousehold.name?.familyName, + householdMember.headOfHousehold?.name?.givenName ?? + localizations.translate(i18.common.coreCommonNA), + householdMember.headOfHousehold?.name?.familyName, ].whereNotNull().join(''), ), ), @@ -321,15 +329,15 @@ class _ViewBeneficiaryCardState extends LocalizedState { offstage: !isCardExpanded, child: DigitTable( headerList: filteredHeaderList, - tableData: tableData, + tableData: tableData ?? [], columnWidth: 130, columnRowFixedHeight: 65, - height: householdMember.members.length == 1 + height: householdMember.members?.length == 1 ? 65 * 2 - : householdMember.members.length <= 4 - ? (householdMember.members.length + 1) * 65 + : (householdMember.members?.length ?? 0) <= 4 + ? ((householdMember.members?.length ?? 0) + 1) * 65 : 5 * 68, - scrollPhysics: householdMember.members.length <= 4 + scrollPhysics: (householdMember.members?.length ?? 0) <= 4 ? const NeverScrollableScrollPhysics() : const ClampingScrollPhysics(), ), @@ -393,4 +401,20 @@ class _ViewBeneficiaryCardState extends LocalizedState { ? theme.colorScheme.onSurfaceVariant : theme.colorScheme.error; } + + getStatus( + Iterable tasks, + List projectBeneficiaries, + bool isNotEligible, + bool isBeneficiaryRefused) { + if (projectBeneficiaries.isNotEmpty) { + if (tasks.isEmpty) { + return Status.registered.toValue(); + } else { + return getTaskStatus(tasks).toValue(); + } + } else { + return Status.notRegistered.toValue(); + } + } } diff --git a/packages/registration_delivery/lib/widgets/member_card/member_card.dart b/packages/registration_delivery/lib/widgets/member_card/member_card.dart index fa0973dbb..014dab8dc 100644 --- a/packages/registration_delivery/lib/widgets/member_card/member_card.dart +++ b/packages/registration_delivery/lib/widgets/member_card/member_card.dart @@ -3,6 +3,7 @@ import 'package:digit_components/digit_components.dart'; import 'package:digit_data_model/data_model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:registration_delivery/models/entities/project_beneficiary.dart'; import 'package:registration_delivery/utils/extensions/extensions.dart'; import '../../blocs/app_localization.dart'; @@ -19,10 +20,11 @@ import '../action_card/action_card.dart'; class MemberCard extends StatelessWidget { final String name; final String? gender; - final int years; - final int months; + final int? years; + final int? months; final bool isHead; final IndividualModel individual; + final List? projectBeneficiaries; final bool isDelivered; final VoidCallback setAsHeadAction; @@ -41,14 +43,15 @@ class MemberCard extends StatelessWidget { required this.individual, required this.name, this.gender, - required this.years, + this.years, this.isHead = false, - this.months = 0, + this.months, required this.localizations, required this.isDelivered, required this.setAsHeadAction, required this.editMemberAction, required this.deleteMemberAction, + this.projectBeneficiaries, this.tasks, this.isNotEligible = false, this.projectBeneficiaryClientReferenceId, @@ -102,34 +105,37 @@ class MemberCard extends StatelessWidget { child: Align( alignment: Alignment.topRight, child: DigitIconButton( - onPressed: () => DigitActionDialog.show( - context, - widget: ActionCard( - items: [ - ActionCardModel( - icon: Icons.person, - label: localizations.translate( - i18.memberCard.assignAsHouseholdhead, - ), - action: isHead ? null : setAsHeadAction, - ), - ActionCardModel( - icon: Icons.edit, - label: localizations.translate( - i18.memberCard.editIndividualDetails, - ), - action: editMemberAction, - ), - ActionCardModel( - icon: Icons.delete, - label: localizations.translate( - i18.memberCard.deleteIndividualActionText, + buttonDisabled: (projectBeneficiaries ?? []).isEmpty, + onPressed: (projectBeneficiaries ?? []).isEmpty + ? null + : () => DigitActionDialog.show( + context, + widget: ActionCard( + items: [ + ActionCardModel( + icon: Icons.person, + label: localizations.translate( + i18.memberCard.assignAsHouseholdhead, + ), + action: isHead ? null : setAsHeadAction, + ), + ActionCardModel( + icon: Icons.edit, + label: localizations.translate( + i18.memberCard.editIndividualDetails, + ), + action: editMemberAction, + ), + ActionCardModel( + icon: Icons.delete, + label: localizations.translate( + i18.memberCard.deleteIndividualActionText, + ), + action: isHead ? null : deleteMemberAction, + ), + ], + ), ), - action: isHead ? null : deleteMemberAction, - ), - ], - ), - ), iconText: localizations.translate( i18.memberCard.editDetails, ), @@ -150,13 +156,15 @@ class MemberCard extends StatelessWidget { gender != null ? localizations .translate('CORE_COMMON_${gender?.toUpperCase()}') - : ' - ', + : ' -- ', style: theme.textTheme.bodyMedium, ), ), Expanded( child: Text( - " | $years ${localizations.translate(i18.memberCard.deliverDetailsYearText)} $months ${localizations.translate(i18.memberCard.deliverDetailsMonthsText)}", + years != null && months != null + ? " | $years ${localizations.translate(i18.memberCard.deliverDetailsYearText)} $months ${localizations.translate(i18.memberCard.deliverDetailsMonthsText)}" + : "| --", style: theme.textTheme.bodyMedium, ), ), @@ -187,7 +195,6 @@ class MemberCard extends StatelessWidget { .householdOverViewBeneficiaryReferredLabel : isBeneficiaryRefused ? Status.beneficiaryRefused.toValue() - // [TODO Need to update the localization] : i18.householdOverView .householdOverViewNotDeliveredIconLabel, ), @@ -225,45 +232,45 @@ class MemberCard extends StatelessWidget { ? const Offstage() : !isNotEligible ? DigitElevatedButton( - // padding: const EdgeInsets.only( - // left: kPadding / 2, - // right: kPadding / 2, - // ), - onPressed: () { - final bloc = - context.read(); + onPressed: (projectBeneficiaries ?? []).isEmpty + ? null + : () { + final bloc = + context.read(); - bloc.add( - HouseholdOverviewEvent.selectedIndividual( - individualModel: individual, - ), - ); - bloc.add(HouseholdOverviewReloadEvent( - projectId: RegistrationDeliverySingleton() - .projectId!, - projectBeneficiaryType: - RegistrationDeliverySingleton() - .beneficiaryType ?? - BeneficiaryType.individual, - )); + bloc.add( + HouseholdOverviewEvent + .selectedIndividual( + individualModel: individual, + ), + ); + bloc.add(HouseholdOverviewReloadEvent( + projectId: + RegistrationDeliverySingleton() + .projectId!, + projectBeneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType ?? + BeneficiaryType.individual, + )); - final futureTaskList = tasks - ?.where((task) => - task.status == - Status.delivered.toValue()) - .toList(); + final futureTaskList = tasks + ?.where((task) => + task.status == + Status.delivered.toValue()) + .toList(); - if ((futureTaskList ?? []).isNotEmpty) { - context.router.push( - RecordPastDeliveryDetailsRoute( - tasks: tasks, - ), - ); - } else { - context.router - .push(BeneficiaryDetailsRoute()); - } - }, + if ((futureTaskList ?? []).isNotEmpty) { + context.router.push( + RecordPastDeliveryDetailsRoute( + tasks: tasks, + ), + ); + } else { + context.router + .push(BeneficiaryDetailsRoute()); + } + }, child: Center( child: Text( allDosesDelivered( @@ -320,197 +327,213 @@ class MemberCard extends StatelessWidget { 50, ), ), - onPressed: () async { - await DigitActionDialog.show( - context, - widget: Column( - children: [ - DigitOutLineButton( - label: localizations.translate( - i18.memberCard.beneficiaryRefusedLabel, - ), - buttonStyle: OutlinedButton.styleFrom( - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.zero, - ), - backgroundColor: Colors.white, - side: BorderSide( - width: 1.0, - color: theme.colorScheme.secondary, - ), - minimumSize: Size( - MediaQuery.of(context).size.width / - 1.25, - 50, - ), - ), - onPressed: () { - Navigator.of(context, rootNavigator: true) - .pop(); - context - .read() - .add( - DeliverInterventionSubmitEvent( - task: TaskModel( - projectBeneficiaryClientReferenceId: - projectBeneficiaryClientReferenceId, - clientReferenceId: - IdGen.i.identifier, - tenantId: - RegistrationDeliverySingleton() - .tenantId, - rowVersion: 1, - auditDetails: AuditDetails( - createdBy: - RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context - .millisecondsSinceEpoch(), - ), - projectId: - RegistrationDeliverySingleton() - .projectId, - status: Status - .beneficiaryRefused - .toValue(), - clientAuditDetails: - ClientAuditDetails( - createdBy: - RegistrationDeliverySingleton() - .loggedInUserUuid!, - createdTime: context - .millisecondsSinceEpoch(), - lastModifiedBy: - RegistrationDeliverySingleton() - .loggedInUserUuid, - lastModifiedTime: context - .millisecondsSinceEpoch(), - ), - additionalFields: - TaskAdditionalFields( - version: 1, - fields: [ - AdditionalField( - 'taskStatus', - Status.beneficiaryRefused + onPressed: (projectBeneficiaries ?? []).isEmpty + ? null + : () async { + await DigitActionDialog.show( + context, + widget: Column( + children: [ + DigitOutLineButton( + label: localizations.translate( + i18.memberCard + .beneficiaryRefusedLabel, + ), + buttonStyle: OutlinedButton.styleFrom( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.zero, + ), + backgroundColor: Colors.white, + side: BorderSide( + width: 1.0, + color: + theme.colorScheme.secondary, + ), + minimumSize: Size( + MediaQuery.of(context) + .size + .width / + 1.25, + 50, + ), + ), + onPressed: () { + Navigator.of(context, + rootNavigator: true) + .pop(); + context + .read() + .add( + DeliverInterventionSubmitEvent( + task: TaskModel( + projectBeneficiaryClientReferenceId: + projectBeneficiaryClientReferenceId, + clientReferenceId: + IdGen.i.identifier, + tenantId: + RegistrationDeliverySingleton() + .tenantId, + rowVersion: 1, + auditDetails: + AuditDetails( + createdBy: + RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context + .millisecondsSinceEpoch(), + ), + projectId: + RegistrationDeliverySingleton() + .projectId, + status: Status + .beneficiaryRefused .toValue(), + clientAuditDetails: + ClientAuditDetails( + createdBy: + RegistrationDeliverySingleton() + .loggedInUserUuid!, + createdTime: context + .millisecondsSinceEpoch(), + lastModifiedBy: + RegistrationDeliverySingleton() + .loggedInUserUuid, + lastModifiedTime: context + .millisecondsSinceEpoch(), + ), + additionalFields: + TaskAdditionalFields( + version: 1, + fields: [ + AdditionalField( + 'taskStatus', + Status + .beneficiaryRefused + .toValue(), + ), + ], + ), + address: individual + .address?.first, ), - ], + isEditing: false, + boundaryModel: + RegistrationDeliverySingleton() + .boundary!, + ), + ); + final reloadState = context + .read(); + Future.delayed( + const Duration(milliseconds: 500), + () { + reloadState.add( + HouseholdOverviewReloadEvent( + projectId: + RegistrationDeliverySingleton() + .projectId!, + projectBeneficiaryType: + RegistrationDeliverySingleton() + .beneficiaryType!, + ), + ); + }, + ).then( + (value) => context.router.push( + HouseholdAcknowledgementRoute( + enableViewHousehold: true, ), - address: - individual.address?.first, ), - isEditing: false, - boundaryModel: - RegistrationDeliverySingleton() - .boundary!, + ); + }, + ), + const SizedBox( + height: kPadding * 2, + ), + DigitOutLineButton( + label: localizations.translate( + i18.memberCard + .referBeneficiaryLabel, + ), + buttonStyle: OutlinedButton.styleFrom( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.zero, ), - ); - final reloadState = - context.read(); - Future.delayed( - const Duration(milliseconds: 500), - () { - reloadState.add( - HouseholdOverviewReloadEvent( - projectId: - RegistrationDeliverySingleton() - .projectId!, - projectBeneficiaryType: - RegistrationDeliverySingleton() - .beneficiaryType!, + backgroundColor: Colors.white, + side: BorderSide( + width: 1.0, + color: + theme.colorScheme.secondary, + ), + minimumSize: Size( + MediaQuery.of(context) + .size + .width / + 1.25, + 50, ), - ); - }, - ).then( - (value) => context.router.push( - HouseholdAcknowledgementRoute( - enableViewHousehold: true, ), - ), - ); - }, - ), - const SizedBox( - height: kPadding * 2, - ), - DigitOutLineButton( - label: localizations.translate( - i18.memberCard.referBeneficiaryLabel, - ), - buttonStyle: OutlinedButton.styleFrom( - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.zero, - ), - backgroundColor: Colors.white, - side: BorderSide( - width: 1.0, - color: theme.colorScheme.secondary, - ), - minimumSize: Size( - MediaQuery.of(context).size.width / - 1.25, - 50, - ), - ), - onPressed: () async { - Navigator.of( - context, - rootNavigator: true, - ).pop(); - await context.router.push( - ReferBeneficiaryRoute( - projectBeneficiaryClientRefId: - projectBeneficiaryClientReferenceId ?? - '', - ), - ); - }, - ), - const SizedBox( - height: kPadding * 2, - ), - DigitOutLineButton( - label: localizations.translate( - i18.memberCard.recordAdverseEventsLabel, - ), - buttonStyle: OutlinedButton.styleFrom( - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.zero, - ), - backgroundColor: Colors.white, - side: BorderSide( - width: 1.0, - color: tasks != null && - (tasks ?? []).isNotEmpty - ? theme.colorScheme.secondary - : theme.colorScheme.outline, - ), - minimumSize: Size( - MediaQuery.of(context).size.width / - 1.25, - 50, - ), - ), - onPressed: tasks != null && - (tasks ?? []).isNotEmpty - ? () async { + onPressed: () async { Navigator.of( context, rootNavigator: true, ).pop(); await context.router.push( - SideEffectsRoute( - tasks: tasks!, + ReferBeneficiaryRoute( + projectBeneficiaryClientRefId: + projectBeneficiaryClientReferenceId ?? + '', ), ); - } - : null, - ), - ], - ), - ); - }, + }, + ), + const SizedBox( + height: kPadding * 2, + ), + DigitOutLineButton( + label: localizations.translate( + i18.memberCard + .recordAdverseEventsLabel, + ), + buttonStyle: OutlinedButton.styleFrom( + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.zero, + ), + backgroundColor: Colors.white, + side: BorderSide( + width: 1.0, + color: tasks != null && + (tasks ?? []).isNotEmpty + ? theme.colorScheme.secondary + : theme.colorScheme.outline, + ), + minimumSize: Size( + MediaQuery.of(context) + .size + .width / + 1.25, + 50, + ), + ), + onPressed: tasks != null && + (tasks ?? []).isNotEmpty + ? () async { + Navigator.of( + context, + rootNavigator: true, + ).pop(); + await context.router.push( + SideEffectsRoute( + tasks: tasks!, + ), + ); + } + : null, + ), + ], + ), + ); + }, ), ], ), diff --git a/packages/registration_delivery/lib/widgets/progress_bar/beneficiary_progress.dart b/packages/registration_delivery/lib/widgets/progress_bar/beneficiary_progress.dart index 3c39fa856..5ae9047bd 100644 --- a/packages/registration_delivery/lib/widgets/progress_bar/beneficiary_progress.dart +++ b/packages/registration_delivery/lib/widgets/progress_bar/beneficiary_progress.dart @@ -22,10 +22,10 @@ class BeneficiaryProgressBar extends StatefulWidget { }); @override - State createState() => _BeneficiaryProgressBarState(); + State createState() => BeneficiaryProgressBarState(); } -class _BeneficiaryProgressBarState extends State { +class BeneficiaryProgressBarState extends State { int current = 0; @override diff --git a/packages/registration_delivery/lib/widgets/showcase/config/house_details.dart b/packages/registration_delivery/lib/widgets/showcase/config/house_details.dart new file mode 100644 index 000000000..b94af375b --- /dev/null +++ b/packages/registration_delivery/lib/widgets/showcase/config/house_details.dart @@ -0,0 +1,23 @@ +part of 'showcase_constants.dart'; + +class _HouseholdShowcaseData { + static final _HouseholdShowcaseData _instance = _HouseholdShowcaseData._(); + + _HouseholdShowcaseData._(); + + factory _HouseholdShowcaseData() => _instance; + + List get showcaseData => [ + typeOfStructure, + noOfRooms, + ]; + + final typeOfStructure = ShowcaseItemBuilder( + messageLocalizationKey: i18.householdDetailsShowcase.typeOfStructure, + ); + + final noOfRooms = ShowcaseItemBuilder( + messageLocalizationKey: + i18.householdDetailsShowcase.numberOfRoomsInHousehold, + ); +} diff --git a/packages/registration_delivery/lib/widgets/showcase/config/household_details.dart b/packages/registration_delivery/lib/widgets/showcase/config/household_details.dart index 74e12a496..92541d23b 100644 --- a/packages/registration_delivery/lib/widgets/showcase/config/household_details.dart +++ b/packages/registration_delivery/lib/widgets/showcase/config/household_details.dart @@ -11,6 +11,8 @@ class _HouseholdDetailsShowcaseData { List get showcaseData => [ dateOfRegistration, numberOfMembersLivingInHousehold, + numberOfPregnantWomenInHousehold, + numberOfChildrenBelow5InHousehold, ]; final dateOfRegistration = ShowcaseItemBuilder( @@ -21,4 +23,13 @@ class _HouseholdDetailsShowcaseData { messageLocalizationKey: i18.householdDetailsShowcase.numberOfMembersLivingInHousehold, ); + + final numberOfPregnantWomenInHousehold = ShowcaseItemBuilder( + messageLocalizationKey: + i18.householdDetailsShowcase.numberOfPregnantWomenInHousehold, + ); + final numberOfChildrenBelow5InHousehold = ShowcaseItemBuilder( + messageLocalizationKey: + i18.householdDetailsShowcase.numberOfChildrenBelow5InHousehold, + ); } diff --git a/packages/registration_delivery/lib/widgets/showcase/config/household_location.dart b/packages/registration_delivery/lib/widgets/showcase/config/household_location.dart index c0f57b187..5a164ce5a 100644 --- a/packages/registration_delivery/lib/widgets/showcase/config/household_location.dart +++ b/packages/registration_delivery/lib/widgets/showcase/config/household_location.dart @@ -10,6 +10,7 @@ class _HouseholdLocationShowcaseData { List get showcaseData => [ administrativeArea, + gpsAccuracy, addressLine1, addressLine2, landmark, @@ -20,6 +21,10 @@ class _HouseholdLocationShowcaseData { messageLocalizationKey: i18.householdLocationShowcase.administrativeArea, ); + final gpsAccuracy = ShowcaseItemBuilder( + messageLocalizationKey: i18.householdLocationShowcase.gpsAccuracy, + ); + final landmark = ShowcaseItemBuilder( messageLocalizationKey: i18.householdLocationShowcase.landmark, ); diff --git a/packages/registration_delivery/lib/widgets/showcase/config/refused_delivery.dart b/packages/registration_delivery/lib/widgets/showcase/config/refused_delivery.dart new file mode 100644 index 000000000..40329e2b3 --- /dev/null +++ b/packages/registration_delivery/lib/widgets/showcase/config/refused_delivery.dart @@ -0,0 +1,28 @@ +part of 'showcase_constants.dart'; + +class _RefusedDeliveryShowcaseData { + static final _RefusedDeliveryShowcaseData _instance = _RefusedDeliveryShowcaseData._(); + + _RefusedDeliveryShowcaseData._(); + + factory _RefusedDeliveryShowcaseData() => _instance; + + List get showcaseData => [ + dateOfVisit, + reasonOfRefusal, + comments, + ]; + + final dateOfVisit = ShowcaseItemBuilder( + messageLocalizationKey: i18.deliverInterventionShowcase.dateOfVisitLabel, + ); + + final reasonOfRefusal = ShowcaseItemBuilder( + messageLocalizationKey: + i18.deliverInterventionShowcase.reasonOfRefusalLabel, + ); + final comments = ShowcaseItemBuilder( + messageLocalizationKey: + i18.deliverInterventionShowcase.commentLabel, + ); +} diff --git a/packages/registration_delivery/lib/widgets/showcase/config/showcase_constants.dart b/packages/registration_delivery/lib/widgets/showcase/config/showcase_constants.dart index 1540b0b61..d19528cff 100644 --- a/packages/registration_delivery/lib/widgets/showcase/config/showcase_constants.dart +++ b/packages/registration_delivery/lib/widgets/showcase/config/showcase_constants.dart @@ -2,11 +2,13 @@ import '../../../utils/i18_key_constants.dart' as i18; import '../showcase_wrappers.dart'; part 'deliver_intervention.dart'; +part 'house_details.dart'; part 'household_details.dart'; part 'household_location.dart'; part 'household_overview.dart'; part 'individual_details.dart'; part 'search_beneficiaries_showcase.dart'; +part 'refused_delivery.dart'; final searchBeneficiariesShowcaseData = _SearchBeneficiariesShowcaseData(); final householdLocationShowcaseData = _HouseholdLocationShowcaseData(); @@ -14,3 +16,5 @@ final householdDetailsShowcaseData = _HouseholdDetailsShowcaseData(); final individualDetailsShowcaseData = _IndividualDetailsShowcaseData(); final householdOverviewShowcaseData = _HouseholdOverviewShowcaseData(); final deliverInterventionShowcaseData = _DeliverInterventionShowcaseData(); +final houseShowcaseData = _HouseholdShowcaseData(); +final refusedDeliveryShowcaseData = _RefusedDeliveryShowcaseData(); diff --git a/packages/registration_delivery/lib/widgets/showcase/showcase_button.dart b/packages/registration_delivery/lib/widgets/showcase/showcase_button.dart index c6d093e26..32f0e5f1b 100644 --- a/packages/registration_delivery/lib/widgets/showcase/showcase_button.dart +++ b/packages/registration_delivery/lib/widgets/showcase/showcase_button.dart @@ -15,10 +15,10 @@ class ShowcaseButton extends LocalizedStatefulWidget { const ShowcaseButton({super.key, this.showcaseFor}); @override - LocalizedState createState() => _ShowcaseButtonState(); + LocalizedState createState() => ShowcaseButtonState(); } -class _ShowcaseButtonState extends LocalizedState { +class ShowcaseButtonState extends LocalizedState { @override Widget build(BuildContext context) { return TextButton( diff --git a/packages/registration_delivery/lib/widgets/showcase/showcase_wrappers.dart b/packages/registration_delivery/lib/widgets/showcase/showcase_wrappers.dart index a2ac9e398..e18064225 100644 --- a/packages/registration_delivery/lib/widgets/showcase/showcase_wrappers.dart +++ b/packages/registration_delivery/lib/widgets/showcase/showcase_wrappers.dart @@ -33,10 +33,10 @@ class ShowcaseItemWrapperWidget extends LocalizedStatefulWidget { @override LocalizedState createState() => - _ShowcaseItemWrapperWidgetState(); + ShowcaseItemWrapperWidgetState(); } -class _ShowcaseItemWrapperWidgetState +class ShowcaseItemWrapperWidgetState extends LocalizedState { @override Widget build(BuildContext context) { diff --git a/packages/registration_delivery/lib/widgets/status_filter/status_filter.dart b/packages/registration_delivery/lib/widgets/status_filter/status_filter.dart new file mode 100644 index 000000000..90b0b2c44 --- /dev/null +++ b/packages/registration_delivery/lib/widgets/status_filter/status_filter.dart @@ -0,0 +1,196 @@ +import 'package:digit_components/digit_components.dart'; +import 'package:digit_components/widgets/atoms/selection_card.dart'; +import 'package:digit_scanner/widgets/localized.dart'; +import 'package:flutter/material.dart'; +import 'package:registration_delivery/registration_delivery.dart'; +import '../../utils/i18_key_constants.dart' as i18; + +import '../../models/entities/status.dart'; +import '../../utils/i18_key_constants.dart' as i18; + +class StatusFilter extends LocalizedStatefulWidget { + final List? selectedFilters; + final bool isCloseIcon; + final Icon? titleIcon; + final String? titleText; + + const StatusFilter({ + super.key, + super.appLocalizations, + this.isCloseIcon = false, + this.titleIcon, + this.titleText, + this.selectedFilters, + }); + + @override + State createState() => StatusFilterState(); +} + +class StatusFilterState extends LocalizedState { + List selectedButtons = []; + bool isLoading = false; + + @override + void initState() { + assignSelectedButtons(); + super.initState(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: isLoading + ? [ + Padding( + padding: const EdgeInsets.only(top: kPadding * 2), + child: Icon( + Icons.autorenew, + color: const DigitColors().burningOrange, + size: kPadding * 4, + ), + ), + const SizedBox(height: kPadding * 2), + Center( + child: Text( + localizations.translate(i18.common.coreCommonLoadingText), + style: theme.textTheme.headlineSmall + ?.copyWith(color: const DigitColors().burningOrange), + ), + ) + ] + : [ + Row( + children: [ + if (widget.titleIcon != null) ...[ + Padding( + padding: const EdgeInsets.all(kPadding), + child: widget.titleIcon!, + ), + ], + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(vertical: kPadding), + child: Text( + widget.titleText!, + textAlign: TextAlign.left, + style: DigitTheme + .instance.mobileTheme.textTheme.headlineMedium, + ), + ), + ), + if (widget.isCloseIcon) + InkWell( + onTap: () => Navigator.of(context).pop(), + child: const Icon(Icons.close), + ), + ], + ), + Padding( + padding: const EdgeInsets.all(kPadding), + child: SelectionBox( + options: getFilters() ?? [], + allowMultipleSelection: false, + equalWidthOptions: true, + initialSelection: [...selectedButtons], + onSelectionChanged: (selected) { + setState(() { + selectedButtons = selected; + }); + }, + valueMapper: (value) { + return localizations + .translate(value.toValue().toString()); + }, + ), + ), + const SizedBox( + height: kPadding, + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: kPadding), + child: Row( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, // Adjust button spacing + children: [ + Expanded( + child: DigitOutLineButton( + label: localizations.translate( + i18.searchBeneficiary.clearFilter, + ), + onPressed: selectedButtons.isEmpty + ? null + : () { + setState(() { + selectedButtons.clear(); + }); + }), + ), + const SizedBox( + width: kPadding, + ), + Expanded( + child: DigitElevatedButton( + onPressed: selectedButtons.isEmpty + ? null + : () { + setState(() { + isLoading = true; + }); + var selected = selectedButtons + .map((e) => e.name) + .toList(); + + Future.delayed(const Duration(seconds: 1), + () { + Navigator.pop(context, selected); + }); + }, + child: Text( + localizations.translate( + i18.searchBeneficiary.applyFilter, + ), + )), + ), + ], + ), + ) + ], + ), + ); + } + + void selectButton(Status button) { + setState(() { + if (selectedButtons.contains(button)) { + selectedButtons.remove(button); + } else { + selectedButtons.add(button); + } + }); + } + + getFilters() { + var finalStatues = []; + finalStatues.addAll((RegistrationDeliverySingleton() + .searchHouseHoldFilter ?? + []) + .map((e) => Status.values.where((element) => element.toValue() == e)) + .expand((element) => element) + .toList()); + + return finalStatues; + } + + void assignSelectedButtons() { + setState(() { + selectedButtons = widget.selectedFilters! + .map((e) => Status.values.where((element) => element.name == e)) + .expand((element) => element) + .toList(); + }); + } +} diff --git a/packages/registration_delivery/pubspec.lock b/packages/registration_delivery/pubspec.lock index 2a0ac87b2..aba4e9cae 100644 --- a/packages/registration_delivery/pubspec.lock +++ b/packages/registration_delivery/pubspec.lock @@ -37,10 +37,10 @@ packages: dependency: transitive description: name: archive - sha256: "6bd38d335f0954f5fad9c79e614604fbf03a0e5b975923dd001b6ea965ef5b4b" + sha256: cb6a278ef2dbb298455e1a713bda08524a175630ec643a242c399c932a0a1f7d url: "https://pub.dev" source: hosted - version: "3.6.0" + version: "3.6.1" args: dependency: transitive description: @@ -245,18 +245,18 @@ packages: dependency: transitive description: name: camera_platform_interface - sha256: a250314a48ea337b35909a4c9d5416a208d736dcb01d0b02c6af122be66660b0 + sha256: b3ede1f171532e0d83111fe0980b46d17f1aa9788a07a2fbed07366bbdbb9061 url: "https://pub.dev" source: hosted - version: "2.7.4" + version: "2.8.0" camera_web: dependency: transitive description: name: camera_web - sha256: "9e9aba2fbab77ce2472924196ff8ac4dd8f9126c4f9a3096171cd1d870d6b26c" + sha256: b9235ec0a2ce949daec546f1f3d86f05c3921ed31c7d9ab6b7c03214d152fc2d url: "https://pub.dev" source: hosted - version: "0.3.3" + version: "0.3.4" characters: dependency: transitive description: @@ -420,26 +420,26 @@ packages: dependency: "direct main" description: name: digit_components - sha256: "53ee8c0a7c992c0e8d1c9c867b6cf1d52e1728200f4b4436943a5d6c5e4984c3" + sha256: "90e12017934343a197a0c25bec00e5fc28e19cfbf11e522798cc39719609612c" url: "https://pub.dev" source: hosted - version: "1.0.0+2" + version: "1.0.0+9" digit_data_model: dependency: "direct main" description: name: digit_data_model - sha256: "0e1ec8e4d2776fcc4a8118ac85043b8876466ec7399c14880f3d585ad3586ef6" + sha256: e1ea907e9cb7d521341325ac1b1b98fad8bd5e5ca1bab7f7c18ed02ccd2f2c2b url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" digit_scanner: dependency: "direct main" description: name: digit_scanner - sha256: a040c9c413436aeb953fdea3bc99ef618641189b06e8f155d84ac83ba8d40fd1 + sha256: "1f1fe3ca8f038a3c93cd52491cf72c0b0e45c88b14580243d47eac59672e67ea" url: "https://pub.dev" source: hosted - version: "1.0.2" + version: "1.0.3" digit_showcase: dependency: "direct main" description: @@ -452,10 +452,18 @@ packages: dependency: transitive description: name: dio - sha256: "11e40df547d418cc0c4900a9318b26304e665da6fa4755399a9ff9efd09034b5" + sha256: e17f6b3097b8c51b72c74c9f071a605c47bcc8893839bd66732457a5ebe73714 url: "https://pub.dev" source: hosted - version: "5.4.3+1" + version: "5.5.0+1" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "36c5b2d79eb17cdae41e974b7a8284fec631651d2a6f39a8a2ff22327e90aeac" + url: "https://pub.dev" + source: hosted + version: "1.0.1" drift: dependency: "direct main" description: @@ -529,10 +537,10 @@ packages: dependency: "direct main" description: name: flutter_bloc - sha256: f0ecf6e6eb955193ca60af2d5ca39565a86b8a142452c5b24d96fb477428f4d2 + sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a url: "https://pub.dev" source: hosted - version: "8.1.5" + version: "8.1.6" flutter_focus_watcher: dependency: transitive description: @@ -667,10 +675,10 @@ packages: dependency: "direct main" description: name: freezed_annotation - sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d + sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2 url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.4" frontend_server_client: dependency: transitive description: @@ -723,10 +731,10 @@ packages: dependency: "direct main" description: name: gs1_barcode_parser - sha256: "9aaff47bdab7177deaf9248cc861ef41cf611d3f828498cb40b64bedcbf53391" + sha256: fbbabda525e35dc1e998f22584178174a39cfc86ea691e3ac8dfb29e767cf7c1 url: "https://pub.dev" source: hosted - version: "1.0.5" + version: "1.0.6" horizontal_data_table: dependency: transitive description: @@ -907,10 +915,10 @@ packages: dependency: "direct dev" description: name: mocktail - sha256: c4b5007d91ca4f67256e720cb1b6d704e79a510183a12fa551021f652577dce6 + sha256: "890df3f9688106f25755f26b1c60589a92b3ab91a22b8b224947ad041bf172d8" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "1.0.4" nested: dependency: transitive description: @@ -1019,10 +1027,10 @@ packages: dependency: transitive description: name: path_provider_windows - sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170" + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.3.0" petitparser: dependency: transitive description: @@ -1035,10 +1043,10 @@ packages: dependency: transitive description: name: platform - sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.5" plugin_platform_interface: dependency: transitive description: @@ -1107,10 +1115,10 @@ packages: dependency: transitive description: name: pubspec_parse - sha256: c63b2876e58e194e4b0828fcb080ad0e06d051cb607a6be51a9e084f47cb9367 + sha256: c799b721d79eb6ee6fa56f00c04b472dcd44a30d258fac2174a6ec57302678f8 url: "https://pub.dev" source: hosted - version: "1.2.3" + version: "1.3.0" reactive_flutter_typeahead: dependency: transitive description: @@ -1240,10 +1248,10 @@ packages: dependency: "direct main" description: name: sqlite3_flutter_libs - sha256: fb2a106a2ea6042fe57de2c47074cc31539a941819c91e105b864744605da3f5 + sha256: "62bbb4073edbcdf53f40c80775f33eea01d301b7b81417e5b3fb7395416258c1" url: "https://pub.dev" source: hosted - version: "0.5.21" + version: "0.5.24" sqlparser: dependency: transitive description: diff --git a/packages/registration_delivery/pubspec.yaml b/packages/registration_delivery/pubspec.yaml index 03f360778..163e31601 100644 --- a/packages/registration_delivery/pubspec.yaml +++ b/packages/registration_delivery/pubspec.yaml @@ -1,6 +1,6 @@ name: registration_delivery description: This package enables health facility workers to register a household and individual members and deliver the resources. -version: 1.0.2 +version: 1.0.3 homepage: https://github.com/egovernments/health-campaign-field-worker-app/tree/master/packages/registration_delivery repository: https://github.com/egovernments/health-campaign-field-worker-app @@ -11,7 +11,7 @@ environment: dependencies: flutter: sdk: flutter - digit_components: ^1.0.0+2 + digit_components: ^1.0.0+9 flutter_bloc: ^8.1.1 freezed_annotation: ^2.1.0 build_runner: ^2.2.1 @@ -29,10 +29,10 @@ dependencies: uuid: ^3.0.6 recase: ^4.1.0 pluto_grid: ^7.0.1 - digit_scanner: ^1.0.2 + digit_scanner: ^1.0.3 gs1_barcode_parser: ^1.0.5 auto_route: ^7.8.4 - digit_data_model: ^1.0.2 + digit_data_model: ^1.0.3 package_info_plus: ^5.0.1 digit_showcase: ^1.0.0 collection: ^1.16.0 @@ -41,7 +41,6 @@ dependencies: async: ^2.11.0 formula_parser: ^2.0.1 - dev_dependencies: flutter_test: sdk: flutter diff --git a/packages/registration_delivery/test/beneficiary_registration_test.dart b/packages/registration_delivery/test/beneficiary_registration_test.dart index dbb95127a..b022e8481 100644 --- a/packages/registration_delivery/test/beneficiary_registration_test.dart +++ b/packages/registration_delivery/test/beneficiary_registration_test.dart @@ -23,12 +23,15 @@ class MockHouseholdMemberDataRepository extends Mock class MockProjectBeneficiaryDataRepository extends Mock implements ProjectBeneficiaryDataRepository {} +class MockTaskDataRepository extends Mock implements TaskDataRepository {} + void main() { late MockIndividualDataRepository mockIndividualDataRepository; late MockHouseholdDataRepository mockHouseholdDataRepository; late MockHouseholdMemberDataRepository mockHouseholdMemberDataRepository; late MockProjectBeneficiaryDataRepository mockProjectBeneficiaryDataRepository; + late MockTaskDataRepository mockTaskDataRepository; late BeneficiaryRegistrationBloc beneficiaryRegistrationBloc; setUpAll(() { @@ -48,6 +51,7 @@ void main() { mockHouseholdMemberDataRepository = MockHouseholdMemberDataRepository(); mockProjectBeneficiaryDataRepository = MockProjectBeneficiaryDataRepository(); + mockTaskDataRepository = MockTaskDataRepository(); beneficiaryRegistrationBloc = BeneficiaryRegistrationBloc( const BeneficiaryRegistrationState.create(), individualRepository: mockIndividualDataRepository, @@ -55,6 +59,7 @@ void main() { householdMemberRepository: mockHouseholdMemberDataRepository, projectBeneficiaryRepository: mockProjectBeneficiaryDataRepository, beneficiaryType: BeneficiaryType.individual, + taskDataRepository: mockTaskDataRepository, ); }); diff --git a/tools/closed_household_package_imports.dart b/tools/closed_household_package_imports.dart new file mode 100644 index 000000000..0e24b43b3 --- /dev/null +++ b/tools/closed_household_package_imports.dart @@ -0,0 +1,356 @@ +import 'dart:io'; + +void main() { + var appDir = Directory.current.path; + + // Define the paths + var appRoot = '$appDir/apps/health_campaign_field_worker_app/lib'; + var localizationDelegatesFilePath = + '$appRoot/utils/localization_delegates.dart'; + var networkManagerProviderWrapperFilePath = + appRoot + '/widgets/network_manager_provider_wrapper.dart'; + var constantsFilePath = appRoot + '/utils/constants.dart'; + var utilsFilePath = appRoot + '/utils/utils.dart'; + var routerFilePath = appRoot + '/router/app_router.dart'; + var entityMapperFilePath = + appRoot + '/data/local_store/no_sql/schema/entity_mapper.dart'; + var syncDownFilePath = appRoot + '/data/repositories/sync/sync_down.dart'; + var homeFilePath = appRoot + '/pages/home.dart'; + + // Add closed household to home file + _updateHome(homeFilePath); + + // Add closed household routes and import to the router file + _addClosedHouseholdRoutesAndImportToRouterFile(routerFilePath); + + _createLocalizationDelegatesFile(localizationDelegatesFilePath); + + // Add the inventory constants to the constants file + _addClosedHouseholdConstantsToConstantsFile( + constantsFilePath: constantsFilePath); + + // Run dart format on the file + _formatFiles([ + homeFilePath, + syncDownFilePath, + entityMapperFilePath, + routerFilePath, + constantsFilePath, + utilsFilePath, + networkManagerProviderWrapperFilePath, + localizationDelegatesFilePath + ]); +} + +void _formatFiles(List filePaths) { + for (var filePath in filePaths) { + Process.runSync('dart', ['format', filePath]); + print('Formatted $filePath'); + } +} + +void _updateHome(String homeFilePath) { + var importStatement = ''' + import 'package:closed_household/closed_household.dart'; + import 'package:closed_household/router/closed_household_router.gm.dart'; + '''; + + var homeItemsData = ''' + i18.home.closedHouseHoldLabel: + homeShowcaseData.closedHouseHold.buildWith( + child: HomeItemCard( + icon: Icons.home, + enableCustomIcon: true, + customIconSize: 48, + customIcon: Constants.closedHouseholdSvg, + label: i18.home.closedHouseHoldLabel, + onPressed: () { + context.router.push(const ClosedHouseholdWrapperRoute()); + }, + ), + ), + '''; + + var showCaseData = ''' + i18.home.closedHouseHoldLabel: + homeShowcaseData.closedHouseHold.showcaseKey, + '''; + + var itemsLabel = ''' + i18.home.closedHouseHoldLabel, + '''; + + // Define the data to be added + var singletonData = ''' + ClosedHouseholdSingleton().setInitialData( + loggedInUserUuid: context.loggedInUserUuid, + projectId: context.projectId, + beneficiaryType: context.beneficiaryType, + ); + '''; + + // Check if the home.dart file exists + var homeFile = File(homeFilePath); + if (!homeFile.existsSync()) { + print('Error: Home file does not exist at path: $homeFilePath'); + return; + } + + // Read the home.dart file + var homeFileContent = homeFile.readAsStringSync(); + + // Check if the import statement already exists and add it if not + if (!homeFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + homeFileContent = importStatement + '\n' + homeFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + + // Insert the data to be added + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add singleton of package Here', singletonData); + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add home items of package Here', homeItemsData); + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add showcase keys of package Here', showCaseData); + homeFileContent = insertData(homeFileContent, + '// INFO: Need to add items label of package Here', itemsLabel); + + // Write the updated content back to the home.dart file + homeFile.writeAsStringSync(homeFileContent); +} + +String insertData(String fileContent, String marker, String data) { + var markerIndex = fileContent.indexOf(marker); + if (markerIndex != -1) { + var endOfMarker = markerIndex + marker.length; + if (!fileContent.substring(endOfMarker).contains(data.trim())) { + fileContent = fileContent.substring(0, endOfMarker) + + '\n' + + data + + fileContent.substring(endOfMarker); + print('Data was added after marker: $marker'); + } else { + print('Data already exists after marker: $marker'); + } + } else { + print('Error: Could not find the marker: $marker'); + } + return fileContent; +} + +void _addClosedHouseholdRoutesAndImportToRouterFile(String routerFilePath) { + // Define the closed household route lines + var closedHouseholdRoutes = ''' + AutoRoute( + page: ClosedHouseholdWrapperRoute.page, + path: 'closed-household-wrapper', + children: [ + AutoRoute( + page: ClosedHouseholdDetailsRoute.page, + path: 'closed-household-details', + initial: true, + ), + AutoRoute( + page: ClosedHouseholdSummaryRoute.page, + path: 'closed-household-summary'), + AutoRoute( + page: ClosedHouseholdAcknowledgementRoute.page, + path: 'closed-household-acknowledgement'), + ]), + '''; + + // Define the import statement + var importStatement1 = + "import 'package:closed_household/router/closed_household_router.gm.dart';"; + // Define the import statement + var importStatement2 = + "import 'package:closed_household/router/closed_household_router.dart';"; + + // Check if the router file exists + var routerFile = File(routerFilePath); + + if (!routerFile.existsSync()) { + print('Error: Router file does not exist at path: $routerFilePath'); + return; + } + + // Read the router file + var routerFileContent = routerFile.readAsStringSync(); + + // Normalize the whitespace in the file content + var normalizedFileContent = routerFileContent.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statement already exists + if (!normalizedFileContent + .contains(importStatement1.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the beginning of the file + routerFileContent = importStatement1 + '\n' + routerFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + + // Check if the import statement already exists + if (!normalizedFileContent + .contains(importStatement2.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the beginning of the file + routerFileContent = importStatement2 + '\n' + routerFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + // Check if the ClosedHousehold Route module already exists + if (!routerFileContent.contains('ClosedHouseholdWrapperRoute')) { + // Find the position to insert the module + var moduleInsertionIndex = routerFileContent.indexOf('@AutoRouterConfig('); + if (moduleInsertionIndex != -1) { + var endOfModulesIndex = + routerFileContent.indexOf(']', moduleInsertionIndex); + if (endOfModulesIndex != -1) { + var modulesEndIndex = + routerFileContent.lastIndexOf(']', endOfModulesIndex); + routerFileContent = routerFileContent.substring(0, modulesEndIndex) + + ' ClosedHouseholdWrapperRoute,' + + routerFileContent.substring(modulesEndIndex); + print('The ClosedHousehold Route module was added.'); + } else { + print('Error: Could not find the end of the modules list.'); + return; + } + } else { + print('Error: Could not find @AutoRouterConfig annotation.'); + return; + } + } else { + print('The ClosedHousehold module already exists.'); + } + + // Check if the closedHousehold routes already exist in the file + if (!normalizedFileContent + .contains(closedHouseholdRoutes.replaceAll(RegExp(r'\s'), ''))) { + // Find the position to insert the routes + var insertionIndex = routerFileContent + .indexOf('// INFO : Need to add Router of package Here'); + if (insertionIndex != -1) { + routerFileContent = routerFileContent.substring(0, insertionIndex) + + '// INFO : Need to add Router of package Here\n' + + closedHouseholdRoutes + + routerFileContent.substring(insertionIndex + + '// INFO : Need to add Router of package Here'.length); + print('The closedHousehold routes were added.'); + + // Write the updated content back to the file + routerFile.writeAsStringSync(routerFileContent); + } else { + print('Error: Could not find the insertion point.'); + return; + } + } else { + print('The closedHousehold routes already exist.'); + } +} + +void _addClosedHouseholdConstantsToConstantsFile( + {required String constantsFilePath}) { + // Define the import statements + var importStatements = [ + "import 'package:closed_household/utils/utils.dart';", + ]; + + // Define the attendance configuration + var attendanceConfiguration = ''' +ClosedHouseholdSingleton().setTenantId(envConfig.variables.tenantId); + '''; + + // Check if the constants.dart file exists + var constantsFile = File(constantsFilePath); + if (!constantsFile.existsSync()) { + print('Error: The constants.dart file does not exist.'); + return; + } + + // Read the constants.dart file + var constantsFileContent = constantsFile.readAsStringSync(); + + // Normalize the whitespace in the file content and the closedHousehold configuration + var normalizedFileContent = + constantsFileContent.replaceAll(RegExp(r'\s'), ''); + var normalizedAttendanceConfiguration = + attendanceConfiguration.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statements already exist in the file + for (var importStatement in importStatements) { + if (!normalizedFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the top of the file + constantsFileContent = importStatement + '\n' + constantsFileContent; + print('The import statement was added: $importStatement'); + } + } + + // Check if the closedHousehold configuration already exists in the file + // If not, add it to the file + if (!normalizedFileContent.contains(normalizedAttendanceConfiguration)) { + // Find the setInitialDataOfPackages method and add the closedHousehold configuration inside it + var setInitialDataOfPackagesIndex = + constantsFileContent.indexOf('void setInitialDataOfPackages() {'); + if (setInitialDataOfPackagesIndex != -1) { + var endOfSetInitialDataOfPackages = setInitialDataOfPackagesIndex + + constantsFileContent + .substring(setInitialDataOfPackagesIndex) + .indexOf('}') + + 1; + constantsFileContent = + constantsFileContent.substring(0, endOfSetInitialDataOfPackages - 1) + + '\n $attendanceConfiguration' + + constantsFileContent.substring(endOfSetInitialDataOfPackages - 1); + print('The closedHousehold configuration was added.'); + } + } + + // Write the updated content back to the constants.dart file + constantsFile.writeAsStringSync(constantsFileContent); +} + +void _createLocalizationDelegatesFile(String localizationDelegatesFilePath) { + // Define the import statement and delegate for localization + var importStatement = + "import 'package:closed_household/blocs/app_localization.dart'\n as closed_household_localization;"; + var delegate = + "closed_household_localization.ClosedHouseholdLocalization.getDelegate(\n getLocalizationString(\n isar,\n selectedLocale,\n ),\n appConfig.languages!,\n ),"; + + // Read the localization delegates file + var localizationDelegatesFile = File(localizationDelegatesFilePath); + var localizationDelegatesFileContent = + localizationDelegatesFile.readAsStringSync(); + + var normalizedFileContent = + localizationDelegatesFileContent.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statement and delegate already exist in the file + // If not, add them to the file + if (!normalizedFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + localizationDelegatesFileContent = + '$importStatement\n$localizationDelegatesFileContent'; + print('The import statement was added.'); + } + + if (!normalizedFileContent.contains(delegate.replaceAll(RegExp(r'\s'), ''))) { + var lastDelegateIndex = + localizationDelegatesFileContent.lastIndexOf(RegExp(r',')); + if (lastDelegateIndex != -1) { + localizationDelegatesFileContent = + localizationDelegatesFileContent.substring(0, lastDelegateIndex + 1) + + '\n $delegate' + + localizationDelegatesFileContent.substring(lastDelegateIndex + 1); + print('The delegate was added.'); + } + } + + // Write the updated content back to the file + localizationDelegatesFile.writeAsStringSync(localizationDelegatesFileContent); +} diff --git a/tools/digit_dss_imports.dart b/tools/digit_dss_imports.dart new file mode 100644 index 000000000..52fd61fbb --- /dev/null +++ b/tools/digit_dss_imports.dart @@ -0,0 +1,473 @@ +// Import the required Dart I/O package +import 'dart:io'; + +// Define the main function +void main() { + // Get the current directory path + var appDir = Directory.current.path; + + // Define the paths for the application root and the files to be modified + var appRoot = appDir + '/apps/health_campaign_field_worker_app/lib'; + var appFile = appRoot + '/app.dart'; + var localizationDelegatesFilePath = + appRoot + '/utils/localization_delegates.dart'; + var constantsFilePath = appRoot + '/utils/constants.dart'; + var utilsFilePath = appRoot + '/utils/utils.dart'; + var routerFilePath = appRoot + '/router/app_router.dart'; + var entityMapperFilePath = + appRoot + '/data/local_store/no_sql/schema/entity_mapper.dart'; + var syncDownFilePath = appRoot + '/data/repositories/sync/sync_down.dart'; + var homeFilePath = appRoot + '/pages/home.dart'; + var extensionsFilePath = appRoot + '/utils/extensions/extensions.dart'; + + // Add the scanner bloc to the app file + _addDSSDashboardBlocToAppFile(appFile); + + // Create the localization delegates file + _createLocalizationDelegatesFile(localizationDelegatesFilePath); + + // Add dss to home file + _updateHome(homeFilePath); + + // Add dss routes and import to the router file + _addDigitDSSRoutesAndImportToRouterFile(routerFilePath); + + // Add the dss related constants to the constants file + _addRegNDeliveryConstantsToConstantsFile( + constantsFilePath: constantsFilePath); + + // Add the dss related mappers to the utils file + _addDSSMapperToUtilsFile(utilsFilePath: utilsFilePath); + + _formatFiles([ + appFile, + localizationDelegatesFilePath, + constantsFilePath, + utilsFilePath, + routerFilePath, + entityMapperFilePath, + syncDownFilePath, + homeFilePath, + extensionsFilePath, + ]); +} + +void _formatFiles(List filePaths) { + for (var filePath in filePaths) { + Process.runSync('dart', ['format', filePath]); + print('Formatted $filePath'); + } +} + +void _addDSSDashboardBlocToAppFile(String appFilePath) { + var importStatement = "import 'package:digit_dss/digit_dss.dart';"; + + var dssBlocData = ''' + BlocProvider( + create: (ctx) => DashboardBloc( + const DashboardState.initialState(), + isar: widget.isar, + dashboardRemoteRepo: DashboardRemoteRepository(widget.client), + )), + '''; + + // Check if the app.dart file exists + var appFile = File(appFilePath); + if (!appFile.existsSync()) { + print('Error: App file does not exist at path: $appFile'); + return; + } + + // Read the app.dart file + var appFileContent = appFile.readAsStringSync(); + + // Check if the import statement already exists and add it if not + if (!appFileContent.contains(importStatement)) { + appFileContent = importStatement + '\n' + appFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + + if (!appFileContent.contains('DashboardBloc(')) { + // Insert the data to be added + appFileContent = insertData(appFileContent, + '// INFO : Need to add bloc of package Here', dssBlocData); + } + + // Write the updated content back to the app.dart file + appFile.writeAsStringSync(appFileContent); +} + +void _updateHome(String homeFilePath) { + var importStatement = ''' + import 'package:digit_dss/router/dashboard_router.gm.dart'; + '''; + + var homeItemsData = ''' + i18.home.dashboard: homeShowcaseData.dashBoard.buildWith( + child: HomeItemCard( + icon: Icons.bar_chart_sharp, + label: i18.home.dashboard, + onPressed: () { + context.router.push(const UserDashboardRoute()); + }, + ), + ), + '''; + + var showCaseData = ''' + i18.home.dashboard: homeShowcaseData.dashBoard.showcaseKey, + '''; + + var itemsLabel = ''' + i18.home.dashboard, + '''; + + // Define the data to be added + var singletonData = ''' + DashboardSingleton().setInitialData( + projectId: context.projectId, + tenantId: envConfig.variables.tenantId, + dashboardConfig: appConfiguration.dashboardConfig, + appVersion: Constants().version, + selectedProject: context.selectedProject, + actionPath: Constants.getEndPoint( + serviceRegistry: serviceRegistry, + service: DashboardResponseModel.schemaName.toUpperCase(), + action: ApiOperation.search.toValue(), + entityName: DashboardResponseModel.schemaName, + )); + '''; + + // Check if the home.dart file exists + var homeFile = File(homeFilePath); + if (!homeFile.existsSync()) { + print('Error: Home file does not exist at path: $homeFilePath'); + return; + } + + // Read the home.dart file + var homeFileContent = homeFile.readAsStringSync(); + + // Check if the import statement already exists and add it if not + if (!homeFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + homeFileContent = importStatement + '\n' + homeFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + + // Insert the data to be added + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add singleton of package Here', singletonData); + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add home items of package Here', homeItemsData); + homeFileContent = insertData(homeFileContent, + '// INFO : Need to add showcase keys of package Here', showCaseData); + homeFileContent = insertData(homeFileContent, + '// INFO: Need to add items label of package Here', itemsLabel); + + // Write the updated content back to the home.dart file + homeFile.writeAsStringSync(homeFileContent); +} + +String insertData(String fileContent, String marker, String data) { + var markerIndex = fileContent.indexOf(marker); + if (markerIndex != -1) { + var endOfMarker = markerIndex + marker.length; + if (!fileContent.substring(endOfMarker).contains(data.trim())) { + fileContent = fileContent.substring(0, endOfMarker) + + '\n' + + data + + fileContent.substring(endOfMarker); + print('Data was added after marker: $marker'); + } else { + print('Data already exists after marker: $marker'); + } + } else { + print('Error: Could not find the marker: $marker'); + } + return fileContent; +} + +void _createLocalizationDelegatesFile(String localizationDelegatesFilePath) { + // Define the import statement and delegate for localization + var importStatement = + "import 'package:digit_dss/blocs/app_localization.dart' as digit_dss_localization;"; + var delegate = ''' + digit_dss_localization.DashboardLocalization.getDelegate( + getLocalizationString( + isar, + selectedLocale, + ), + appConfig.languages!, + ), + '''; + + // Read the localization delegates file + var localizationDelegatesFile = File(localizationDelegatesFilePath); + var localizationDelegatesFileContent = + localizationDelegatesFile.readAsStringSync(); + + var normalizedFileContent = + localizationDelegatesFileContent.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statement and delegate already exist in the file + // If not, add them to the file + if (!normalizedFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + localizationDelegatesFileContent = + '$importStatement\n$localizationDelegatesFileContent'; + print('The import statement was added.'); + } + + if (!normalizedFileContent.contains(delegate.replaceAll(RegExp(r'\s'), ''))) { + var lastDelegateIndex = + localizationDelegatesFileContent.lastIndexOf(RegExp(r',')); + if (lastDelegateIndex != -1) { + localizationDelegatesFileContent = + localizationDelegatesFileContent.substring(0, lastDelegateIndex + 1) + + '\n $delegate' + + localizationDelegatesFileContent.substring(lastDelegateIndex + 1); + print('The delegate was added.'); + } + } + + // Write the updated content back to the file + localizationDelegatesFile.writeAsStringSync(localizationDelegatesFileContent); +} + +void _addDigitDSSRoutesAndImportToRouterFile(String routerFilePath) { + // Define the dss route lines + var dssRoutes = ''' + // DSS Dashboard Routes + AutoRoute( + page: UserDashboardRoute.page, + path: 'dashboard', + ), + '''; + + // Define the import statement + var importStatement1 = + "import 'package:digit_dss/router/dashboard_router.dart';"; + // Define the import statement + var importStatement2 = + "import 'package:digit_dss/router/dashboard_router.gm.dart';"; + + // Check if the router file exists + var routerFile = File(routerFilePath); + + if (!routerFile.existsSync()) { + print('Error: Router file does not exist at path: $routerFilePath'); + return; + } + + // Read the router file + var routerFileContent = routerFile.readAsStringSync(); + + // Normalize the whitespace in the file content + var normalizedFileContent = routerFileContent.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statement already exists + if (!normalizedFileContent + .contains(importStatement1.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the beginning of the file + routerFileContent = importStatement1 + '\n' + routerFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + + // Check if the import statement already exists + if (!normalizedFileContent + .contains(importStatement2.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the beginning of the file + routerFileContent = importStatement2 + '\n' + routerFileContent; + print('The import statement was added.'); + } else { + print('The import statement already exists.'); + } + // Check if the DSSRoute module already exists + if (!routerFileContent.contains('DashboardRoute')) { + // Find the position to insert the module + var moduleInsertionIndex = routerFileContent.indexOf('@AutoRouterConfig('); + if (moduleInsertionIndex != -1) { + var endOfModulesIndex = + routerFileContent.indexOf(']', moduleInsertionIndex); + if (endOfModulesIndex != -1) { + var modulesEndIndex = + routerFileContent.lastIndexOf(']', endOfModulesIndex); + routerFileContent = routerFileContent.substring(0, modulesEndIndex) + + ' DashboardRoute,' + + routerFileContent.substring(modulesEndIndex); + print('The DashboardRoute module was added.'); + } else { + print('Error: Could not find the end of the modules list.'); + return; + } + } else { + print('Error: Could not find @AutoRouterConfig annotation.'); + return; + } + } else { + print('The DashboardRoute module already exists.'); + } + + // Check if the dss routes already exist in the file + if (!normalizedFileContent + .contains(dssRoutes.replaceAll(RegExp(r'\s'), ''))) { + // Find the position to insert the routes + var insertionIndex = routerFileContent + .indexOf('// INFO : Need to add Router of package Here'); + if (insertionIndex != -1) { + routerFileContent = routerFileContent.substring(0, insertionIndex) + + '// INFO : Need to add Router of package Here\n' + + dssRoutes + + routerFileContent.substring(insertionIndex + + '// INFO : Need to add Router of package Here'.length); + print('The dss routes were added.'); + + // Write the updated content back to the file + routerFile.writeAsStringSync(routerFileContent); + } else { + print('Error: Could not find the insertion point.'); + return; + } + } else { + print('The dss routes already exist.'); + } +} + +void _addDSSMapperToUtilsFile({required String utilsFilePath}) { + // Define the dss related lines + var dataModelImportStatement = [ + "import 'package:digit_dss/digit_dss.dart' as dss_mappers;" + ]; + var dataModelInitializationStatement = + "Future(() => dss_mappers.initializeMappers()),"; + + // Check if the utils.dart file exists + var utilsFile = File(utilsFilePath); + + // Read the utils.dart file + var utilsFileContent = utilsFile.readAsStringSync(); + + // Normalize the whitespace in the file content + var normalizedFileContent = utilsFileContent.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statement and delegate already exist in the file + // If not, add them to the file + if (!normalizedFileContent + .contains(dataModelImportStatement[0].replaceAll(RegExp(r'\s'), ''))) { + var libraryIndex = utilsFileContent.indexOf('library app_utils;'); + if (libraryIndex != -1) { + var endOfLibrary = libraryIndex + + utilsFileContent.substring(libraryIndex).indexOf(';') + + 1; + utilsFileContent = utilsFileContent.substring(0, endOfLibrary + 1) + + '\n' + + dataModelImportStatement[0] + + utilsFileContent.substring(endOfLibrary + 1); + print('The import statement was added.'); + } + } else { + print('The import statement already exists.'); + } + + if (!utilsFileContent.contains(dataModelInitializationStatement)) { + // Add the dss related initialization statement to the file + var initializeAllMappersIndex = + utilsFileContent.indexOf('initializeAllMappers() async {'); + if (initializeAllMappersIndex == -1) { + print( + 'Error: Could not find a place to insert the DigitDSS initialization statement.'); + return; + } + var endOfInitializeAllMappers = initializeAllMappersIndex + + utilsFileContent.substring(initializeAllMappersIndex).indexOf(']') + + 1; + utilsFileContent = + utilsFileContent.substring(0, endOfInitializeAllMappers - 1) + + '\n ' + + dataModelInitializationStatement + + utilsFileContent.substring(endOfInitializeAllMappers - 1); + print('DigitDSS initialization statement added to utils.dart'); + } + + // Write the updated content back to the utils.dart file + utilsFile.writeAsStringSync(utilsFileContent); +} + +void _addRegNDeliveryConstantsToConstantsFile( + {required String constantsFilePath}) { + // Define the import statements + var importStatements = [ + "import 'package:digit_dss/digit_dss.dart';", + ]; + + // Define the additional line to be added + var dashboardResponseSchema = ''' + DashboardResponseSchema + '''; + // Check if the constants.dart file exists + var constantsFile = File(constantsFilePath); + if (!constantsFile.existsSync()) { + print('Error: The constants.dart file does not exist.'); + return; + } + + // Read the constants.dart file + var constantsFileContent = constantsFile.readAsStringSync(); + + // Normalize the whitespace in the file content and the dss configuration + var normalizedFileContent = + constantsFileContent.replaceAll(RegExp(r'\s'), ''); + var normalizedDashboardSchemaConfiguration = + dashboardResponseSchema.replaceAll(RegExp(r'\s'), ''); + + // Check if the import statements already exist in the file + for (var importStatement in importStatements) { + if (!normalizedFileContent + .contains(importStatement.replaceAll(RegExp(r'\s'), ''))) { + // Add the import statement at the top of the file + constantsFileContent = importStatement + '\n' + constantsFileContent; + print('The import statement was added: $importStatement'); + } + } + + // Check if the dss configuration already exists in the file + // If not, add it to the file + if (!normalizedFileContent.contains(normalizedDashboardSchemaConfiguration)) { + // Find the setInitialDataOfPackages method and add the dss configuration inside it + var openIsarFunctionIndex = + constantsFileContent.indexOf('await Isar.open('); + + if (openIsarFunctionIndex != -1) { + int schemaListStartIndex = + constantsFileContent.indexOf('[', openIsarFunctionIndex); + int schemaListEndIndex = + constantsFileContent.indexOf(']', schemaListStartIndex); + + if (schemaListStartIndex != -1 && schemaListEndIndex != -1) { + String schemaList = constantsFileContent + .substring(schemaListStartIndex + 1, schemaListEndIndex) + .trim(); + + // Ensure no extra comma is added + if (schemaList.isNotEmpty && !schemaList.endsWith(',')) { + schemaList += ','; + } + schemaList += ' $dashboardResponseSchema,'; + + constantsFileContent = constantsFileContent.replaceRange( + schemaListStartIndex + 1, schemaListEndIndex, schemaList); + print('The DashboardSchema was added.'); + } + } + } + + // Write the updated content back to the constants.dart file + constantsFile.writeAsStringSync(constantsFileContent); +} diff --git a/tools/registration_delivery_imports.dart b/tools/registration_delivery_imports.dart index 01b55034a..5e058d11c 100644 --- a/tools/registration_delivery_imports.dart +++ b/tools/registration_delivery_imports.dart @@ -806,6 +806,9 @@ void _addRegistrationRoutesAndImportToRouterFile(String routerFilePath) { AutoRoute( page: HouseHoldDetailsRoute.page, path: 'household-details'), + AutoRoute( + page: HouseDetailsRoute.page, + path: 'house-details'), AutoRoute( page: HouseholdLocationRoute.page, path: 'household-location', @@ -815,6 +818,10 @@ void _addRegistrationRoutesAndImportToRouterFile(String routerFilePath) { page: BeneficiaryAcknowledgementRoute.page, path: 'beneficiary-acknowledgement', ), + AutoRoute( + page: SummaryRoute.page, + path: 'beneficiary-summary', + ), ], ), AutoRoute( @@ -862,6 +869,10 @@ void _addRegistrationRoutesAndImportToRouterFile(String routerFilePath) { page: HouseholdAcknowledgementRoute.page, path: 'household-acknowledgement', ), + AutoRoute( + page: DeliverySummaryRoute.page, + path: 'delivery-summary', + ), ], ), ]),