From b56b998125b82fb4aa797c572363b9d24c2c3e27 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 5 Aug 2026 15:36:26 +0300 Subject: [PATCH 01/47] spare part ui implemented --- lib/controllers/api_routes/urls.dart | 8 +- .../components/activities_list_view.dart | 5 +- .../service_request_bottomsheet.dart | 19 +- .../service_request_detail_view.dart | 21 +- .../forms/cost/cost_detail_form_screen.dart | 389 +++++++----------- .../forms/spare_part/spare_part_request.dart | 64 +-- .../activities/pm_activities_list_view.dart | 207 ++++++++++ .../activities/pm_cost_detail_page.dart | 127 ++++++ .../pm_module/ppm_wo/ppm_details_page.dart | 51 ++- 9 files changed, 603 insertions(+), 288 deletions(-) create mode 100644 lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart create mode 100644 lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 2028d9d7..f9374337 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -3,12 +3,12 @@ class URLs { static const String appReleaseBuildNumber = "50"; - static const host1 = "https://atomsm.hmg.com"; // production url + // static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + static const host1 = "https://atomsmuat.hmg.com"; // local UAT url - static final String _baseUrl = "$_host/mobile"; // host local UAT - // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis + // static final String _baseUrl = "$_host/mobile"; // host local UAT + static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index a543651f..d0294f6d 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -364,7 +364,10 @@ class _ActivitiesListViewState extends State { requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel); Navigator.of(context).push(MaterialPageRoute( - builder: (_) => const SparePartRequest(), + builder: (_) => SparePartRequest( + model: requestDetailProvider.sparePartHelperModel, + provider: requestDetailProvider, + ), )); } } diff --git a/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart b/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart index 04fdd0ce..72e0b6f9 100644 --- a/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart +++ b/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart @@ -668,16 +668,20 @@ class ServiceRequestBottomSheet { } void onItemTap({required int index, required BuildContext context}) { + CMDetailProvider requestDetailProvider = Provider.of(context, listen: false); switch (index) { case 0: - Provider.of(context, listen: false).sparePartHelperModel = SparePartHelperModel(); + requestDetailProvider.sparePartHelperModel = SparePartHelperModel(); Navigator.pushReplacement( context, - MaterialPageRoute(builder: (context) => const SparePartRequest()), + MaterialPageRoute( + builder: (context) => SparePartRequest( + model: requestDetailProvider.sparePartHelperModel, + provider: requestDetailProvider, + )), ); break; case 1: - CMDetailProvider requestDetailProvider = Provider.of(context, listen: false); requestDetailProvider.activityMaintenanceHelperModel = ActivityMaintenanceHelperModel( workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId, id: 0, @@ -804,11 +808,16 @@ class ServiceRequestBottomSheet { buttonColor: AppColor.primary10, loading: false, onPressed: () { + CMDetailProvider provider = Provider.of(context, listen: false); Navigator.pop(context); - Provider.of(context, listen: false).sparePartHelperModel = SparePartHelperModel(); + provider.sparePartHelperModel = SparePartHelperModel(); Navigator.pushReplacement( context, - MaterialPageRoute(builder: (context) => const SparePartRequest()), + MaterialPageRoute( + builder: (context) => SparePartRequest( + model: provider.sparePartHelperModel, + provider: provider, + )), ); }, ).expanded, diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index 73a7f9ea..766c5586 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -338,8 +338,27 @@ class _ServiceRequestDetailViewState extends State { const Spacer(), if (!provider.isReadOnlyRequest) "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async { + WorkOrderData currentWorkOrderData = provider.currentWorkOrder!.data!; + provider.workOrderCostModel = WorkOrderCostModel( + workOrderId: currentWorkOrderData.requestId, + labourCost: currentWorkOrderData.labourCost, + sparePartCost: currentWorkOrderData.sparePartCost, + travelCost: currentWorkOrderData.travelCost, + qAmount: currentWorkOrderData.qAmount, + prNo: currentWorkOrderData.prNo, + poNo: currentWorkOrderData.poNo, + mrNo: currentWorkOrderData.mrNo, + exchangeCost: currentWorkOrderData.exchangeCost, + ); provider.refreshTimer = false; - await Navigator.push(context, MaterialPageRoute(builder: (context) => CostDetailFormScreen(isEdit: true))); + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CostDetailFormScreen( + isEdit: true, + model: provider.workOrderCostModel, + provider: provider, + ))); provider.refreshTimer = true; }), ], diff --git a/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart b/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart index f7be5cab..1c21e035 100644 --- a/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart +++ b/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart @@ -1,11 +1,8 @@ import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; -import 'package:test_sa/models/new_models/work_order_detail_model.dart'; import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; @@ -13,261 +10,189 @@ import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; -import 'package:test_sa/providers/service_request_providers/equipment_status_provider.dart'; class CostDetailFormScreen extends StatefulWidget { static const String id = "/cost-detail-form-screen"; - bool isEdit = false; + final bool isEdit; + final WorkOrderCostModel? model; + final CMDetailProvider provider; - CostDetailFormScreen({Key? key, required this.isEdit}) : super(key: key); + const CostDetailFormScreen({ + Key? key, + required this.isEdit, + required this.model, + required this.provider, + }) : super(key: key); @override _CostDetailFormScreenState createState() => _CostDetailFormScreenState(); } class _CostDetailFormScreenState extends State with TickerProviderStateMixin { - CMDetailProvider? _requestDetailProvider; - final GlobalKey _scaffoldKey = GlobalKey(); - @override - void initState() { - super.initState(); - } - - void assignValues() { - // ServiceRequestDetailProvider requestDetailProvider = Provider.of(context, listen: false); - // _requestDetailProvider = Provider.of(context, listen: false); - WorkOrderData currentWorkOrderData = _requestDetailProvider!.currentWorkOrder!.data!; - _requestDetailProvider!.workOrderCostModel = WorkOrderCostModel( - workOrderId: currentWorkOrderData.requestId, - labourCost: currentWorkOrderData.labourCost, - sparePartCost: currentWorkOrderData.sparePartCost, - travelCost: currentWorkOrderData.travelCost, - qAmount: currentWorkOrderData.qAmount, - prNo: currentWorkOrderData.prNo, - poNo: currentWorkOrderData.poNo, - mrNo: currentWorkOrderData.mrNo, - exchangeCost: currentWorkOrderData.exchangeCost, - ); - } - @override Widget build(BuildContext context) { - if (_requestDetailProvider == null) { - _requestDetailProvider = Provider.of(context, listen: false); - assignValues(); - } - return Scaffold( key: _scaffoldKey, appBar: const DefaultAppBar(title: "Cost Details"), - body: Consumer(builder: (context, CMDetailProvider requestDetailProvider, child) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - AppTextFormField( - labelText: "Spare Part Cost", - backgroundColor: AppColor.neutral100, - initialValue: requestDetailProvider.workOrderCostModel?.sparePartCost?.toString(), - textAlign: TextAlign.center, - enable: false, - labelStyle: AppTextStyles.textFieldLabelStyle, - textInputType: TextInputType.number, - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.sparePartCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - initialValue: requestDetailProvider.workOrderCostModel?.labourCost?.toString(), - textAlign: TextAlign.center, - labelText: "Labor Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.labourCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Travel Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.travelCost?.toString(), - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.travelCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Quot Amount", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.qAmount?.toString(), - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.qAmount = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "PR No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.prNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.prNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "PO No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.poNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.poNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "MR No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.mrNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.mrNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Exchange Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: requestDetailProvider.workOrderCostModel?.exchangeCost != null ? requestDetailProvider.workOrderCostModel?.exchangeCost.toString() : '', - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - requestDetailProvider.workOrderCostModel?.exchangeCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - ], - ).toShadowContainer(context).paddingAll(16), - ).expanded, - FooterActionButton.footerContainer( - context: context, - child: AppFilledButton( - label: "Update Cost Details", - buttonColor: AppColor.primary10, - onPressed: () async { - if (validateForm(requestDetailProvider: requestDetailProvider)) { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); - await requestDetailProvider.engineerUpdateCost().then((success) { - Navigator.pop(context); - if (success) { + body: ListenableBuilder( + listenable: widget.provider, + builder: (context, child) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppTextFormField( + labelText: "Spare Part Cost", + backgroundColor: AppColor.neutral100, + initialValue: widget.model?.sparePartCost?.toString(), + textAlign: TextAlign.center, + enable: false, + labelStyle: AppTextStyles.textFieldLabelStyle, + textInputType: TextInputType.number, + showShadow: false, + onChange: (value) { + widget.model?.sparePartCost = num.parse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + initialValue: widget.model?.labourCost?.toString(), + textAlign: TextAlign.center, + labelText: "Labor Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.labourCost = num.parse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Travel Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.travelCost?.toString(), + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.travelCost = num.parse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Quot Amount", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.qAmount?.toString(), + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.qAmount = num.parse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "PR No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.prNo, + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.prNo = value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "PO No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.poNo, + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.poNo = value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "MR No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.mrNo, + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.mrNo = value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Exchange Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: widget.model?.exchangeCost != null ? widget.model?.exchangeCost.toString() : '', + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + widget.model?.exchangeCost = num.parse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + ], + ).toShadowContainer(context).paddingAll(16), + ).expanded, + FooterActionButton.footerContainer( + context: context, + child: AppFilledButton( + label: "Update Cost Details", + buttonColor: AppColor.primary10, + onPressed: () async { + if (validateForm()) { + showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + await widget.provider.engineerUpdateCost().then((success) { Navigator.pop(context); - } - }); - } - }, + if (success) { + Navigator.pop(context); + } + }); + } + }, + ), ), - ), - ], - ); - }), + ], + ); + }, + ), ); } - bool validateForm({required CMDetailProvider requestDetailProvider}) { + bool validateForm() { bool isValid = true; if (!widget.isEdit) { return true; } - // if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus != null) { - // if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 1 || requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 2) { - // if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.returnToService == null) { - // Fluttertoast.showToast(msg: "Return to service is required ", toastLength: Toast.LENGTH_LONG); - // return false; - // } - // } - // } return isValid; } - - Widget assetStatusWidget({required BuildContext context, required EngineerUpdateWorkOrderHelperModel workOrderData}) { - return Consumer(builder: (cxt, snapshot, _) { - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - context.translation.assetStatus.bodyText(context).custom(color: AppColor.black20), - 8.height, - Wrap( - runSpacing: 8, - spacing: 8, - children: [ - for (var element in snapshot.items) - Row( - mainAxisSize: MainAxisSize.min, - children: [ - SizedBox( - width: 24, - height: 24, - child: Radio( - value: element, - activeColor: Colors.red, - fillColor: WidgetStateColor.resolveWith((states) { - if (states.contains(WidgetState.selected)) return AppColor.primary10; - return AppColor.neutral130; - }), - groupValue: workOrderData.equipmentStatus, - onChanged: (state) { - setState(() { - workOrderData.equipmentStatus = element; - }); - }), - ), - 8.width, - Text(element.name ?? '', style: AppTextStyles.tinyFont.copyWith(color: AppColor.neutral120)), - ], - ) - ], - ).toShimmer(isShow: snapshot.loading, context: context), - ], - ); - }); - } } diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 75140eb4..46a51f77 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -33,15 +33,20 @@ import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; class SparePartRequest extends StatefulWidget { static const String id = "/spare-part-request"; + final SparePartHelperModel ?model; + final CMDetailProvider provider; - const SparePartRequest({Key? key}) : super(key: key); + const SparePartRequest({ + Key? key, + required this.model, + required this.provider, + }) : super(key: key); @override _SparePartRequestState createState() => _SparePartRequestState(); } class _SparePartRequestState extends State with TickerProviderStateMixin { - CMDetailProvider? _requestDetailProvider; PartsProvider? _partsProvider; bool _isLoading = false; List _spareParts = []; @@ -62,37 +67,40 @@ class _SparePartRequestState extends State with TickerProvider void initState() { super.initState(); _partsProvider = Provider.of(context, listen: false); - _requestDetailProvider = Provider.of(context, listen: false); - _requestDetailProvider?.sparePartHelperModel = SparePartHelperModel( - id: _requestDetailProvider?.sparePartHelperModel?.id ?? 0, - workOrderId: _requestDetailProvider?.sparePartHelperModel?.workOrderId ?? _requestDetailProvider?.currentWorkOrder?.data?.requestId, - sparePartAttachments: _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments ?? [], - sparePart: _requestDetailProvider?.sparePartHelperModel?.sparePart ?? SparePart(), - quantity: _requestDetailProvider?.sparePartHelperModel?.quantity, - installQty: _requestDetailProvider?.sparePartHelperModel?.installQty, - returnQty: _requestDetailProvider?.sparePartHelperModel?.returnQty, - activityStatusId: _requestDetailProvider?.sparePartHelperModel?.activityStatusId ?? statusLookup.id, - activityStatus: _requestDetailProvider?.sparePartHelperModel?.activityStatus ?? statusLookup, - comment: _requestDetailProvider?.sparePartHelperModel?.comment ?? '', + + // Initialize model with existing values or defaults + widget.provider.sparePartHelperModel = SparePartHelperModel( + id: widget.model?.id ?? 0, + workOrderId: widget.model?.workOrderId ?? widget.provider.currentWorkOrder?.data?.requestId, + sparePartAttachments: widget.model?.sparePartAttachments ?? [], + sparePart: widget.model?.sparePart ?? SparePart(), + quantity: widget.model?.quantity, + installQty: widget.model?.installQty, + returnQty: widget.model?.returnQty, + activityStatusId: widget.model?.activityStatusId ?? statusLookup.id, + activityStatus: widget.model?.activityStatus ?? statusLookup, + comment: widget.model?.comment ?? '', ); - _partQtyController.text = _requestDetailProvider?.sparePartHelperModel?.quantity != null ? _requestDetailProvider!.sparePartHelperModel!.quantity!.round().toString() : ''; - _installQtyController.text = _requestDetailProvider?.sparePartHelperModel?.installQty != null ? _requestDetailProvider!.sparePartHelperModel!.installQty!.round().toString() : ''; - _returnQtyController.text = _requestDetailProvider?.sparePartHelperModel?.returnQty != null ? _requestDetailProvider!.sparePartHelperModel!.returnQty!.round().toString() : ''; - _oracleNoController.text = _requestDetailProvider?.sparePartHelperModel?.sparePart?.oracleCode != null ? _requestDetailProvider!.sparePartHelperModel!.sparePart!.oracleCode! : ''; - _descriptionController.text = _requestDetailProvider?.sparePartHelperModel?.comment != null ? _requestDetailProvider!.sparePartHelperModel!.comment! : ''; - activityStatus = _requestDetailProvider?.sparePartHelperModel?.activityStatus?.value; + + _partQtyController.text = widget.provider.sparePartHelperModel?.quantity != null ? widget.provider.sparePartHelperModel!.quantity!.round().toString() : ''; + _installQtyController.text = widget.provider.sparePartHelperModel?.installQty != null ? widget.provider.sparePartHelperModel!.installQty!.round().toString() : ''; + _returnQtyController.text = widget.provider.sparePartHelperModel?.returnQty != null ? widget.provider.sparePartHelperModel!.returnQty!.round().toString() : ''; + _oracleNoController.text = widget.provider.sparePartHelperModel?.sparePart?.oracleCode != null ? widget.provider.sparePartHelperModel!.sparePart!.oracleCode! : ''; + _descriptionController.text = widget.provider.sparePartHelperModel?.comment != null ? widget.provider.sparePartHelperModel!.comment! : ''; + activityStatus = widget.provider.sparePartHelperModel?.activityStatus?.value; + scheduleMicrotask(() async { _isLoading = true; - attachments = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.map((e) => GenericAttachmentModel(id: e.id!, name: e.name ?? '')).toList() ?? []; + attachments = widget.provider.sparePartHelperModel?.sparePartAttachments?.map((e) => GenericAttachmentModel(id: e.id!, name: e.name ?? '')).toList() ?? []; setState(() {}); - _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: _requestDetailProvider?.currentWorkOrder?.data?.asset?.id); + _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: widget.provider.currentWorkOrder?.data?.asset?.id); _isLoading = false; setState(() {}); }); } void restValues({required CMDetailProvider requestDetailProvider}) { - requestDetailProvider.sparePartHelperModel = SparePartHelperModel(id: 0, workOrderId: _requestDetailProvider?.currentWorkOrder?.data?.requestId, sparePartAttachments: []); + requestDetailProvider.sparePartHelperModel = SparePartHelperModel(id: 0, workOrderId: widget.provider.currentWorkOrder?.data?.requestId, sparePartAttachments: []); _partQtyController.clear(); _installQtyController.clear(); _returnQtyController.clear(); @@ -130,7 +138,7 @@ class _SparePartRequestState extends State with TickerProvider SingleChildScrollView( padding: const EdgeInsets.all(16), child: IgnorePointer( - ignoring: _requestDetailProvider!.isReadOnlyRequest, + ignoring: widget.provider.isReadOnlyRequest, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -164,7 +172,7 @@ class _SparePartRequestState extends State with TickerProvider if (part != null) { requestDetailProvider.sparePartHelperModel?.sparePart = part; _oracleNoController.text = part.oracleCode ?? ''; - requestDetailProvider.updateSparePartHelperModel(_requestDetailProvider?.sparePartHelperModel); + requestDetailProvider.updateSparePartHelperModel(widget.provider.sparePartHelperModel); } }, ), @@ -307,7 +315,7 @@ class _SparePartRequestState extends State with TickerProvider FooterActionButton.footerContainer( context: context, child: AppFilledButton( - label: _requestDetailProvider?.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity, + label: widget.provider.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity, buttonColor: AppColor.green70, onPressed: () { _onSubmit(requestDetailProvider: requestDetailProvider); @@ -345,7 +353,7 @@ class _SparePartRequestState extends State with TickerProvider builder: (context) => const AppLazyLoading(), ); bool success = false; - if (_requestDetailProvider?.sparePartHelperModel?.id == 0) { + if (widget.provider.sparePartHelperModel?.id == 0) { success = await requestDetailProvider.createActivitySparePart(); } else { success = await requestDetailProvider.updateActivitySparePart(); @@ -356,7 +364,7 @@ class _SparePartRequestState extends State with TickerProvider id: requestDetailProvider.currentWorkOrder!.data!.requestId!, ); if (mounted) Navigator.pop(context); - if (_requestDetailProvider?.sparePartHelperModel?.id == 0) { + if (widget.provider.sparePartHelperModel?.id == 0) { ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context); const SizedBox().flushBar( context: context, diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart new file mode 100644 index 00000000..4d61b068 --- /dev/null +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -0,0 +1,207 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/controllers/providers/api/user_provider.dart'; +import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/extensions/int_extensions.dart'; +import 'package:test_sa/extensions/text_extensions.dart'; +import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/user_types.dart'; +import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart'; +import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; +import 'package:test_sa/models/new_models/work_order_detail_model.dart'; +import 'package:test_sa/models/service_request/spare_parts.dart'; +import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; +import 'package:test_sa/models/service_request/supplier_details.dart'; +import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; +import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; +import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/maintenance_request_main.dart'; +import 'package:test_sa/modules/cm_module/views/forms/spare_part/spare_part_request.dart'; +import 'package:test_sa/new_views/app_style/app_color.dart'; +import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; +import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; +import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; +import 'package:test_sa/views/widgets/images/files_list.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; +import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; +import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; +import 'package:test_sa/views/widgets/requests/request_status.dart'; + +class PmActivitiesListView extends StatefulWidget { + static const String id = "/activities-list"; + + const PmActivitiesListView({Key? key}) : super(key: key); + + @override + _PmActivitiesListViewState createState() { + return _PmActivitiesListViewState(); + } +} + +class _PmActivitiesListViewState extends State { + @override + void initState() { + super.initState(); + } + + @override + void dispose() { + super.dispose(); + } + + List reOrderActivities = []; + + List activities = []; + + bool disableNewActivity = false; + + @override + Widget build(BuildContext context) { + UserProvider userProvider = Provider.of(context); + return Scaffold( + appBar: const DefaultAppBar( + title: 'PM Activities', + // actions: [if (!showReorderView) IconButton(onPressed: () => activities.isEmpty ? null : setState(() => showReorderView = true), icon: const Icon(Icons.reorder_rounded))], + ), + + ///TODO replace with pm provider and data from pm provider + body: Consumer(builder: (context, CMDetailProvider requestDetailProvider, child) { + activities = requestDetailProvider.currentWorkOrder!.data!.activities; + requestDetailProvider.lastVisitedRequestActivityId = (activities.isNotEmpty ? activities.last.id : -1)!; + if (activities.isNotEmpty && (activities.last.activityStatus!.value == 14 || activities.last.activityStatus!.value == 19)) { + disableNewActivity = true; + } else { + disableNewActivity = false; + } + + return Column( + children: [ + (activities.isEmpty && reOrderActivities.isEmpty) + ? NoDataFound(message: context.translation.noDataFound).center.expanded + : ListView.separated( + padding: const EdgeInsets.all(16), + itemCount: activities.length, + separatorBuilder: (czt, index) => 16.height, + itemBuilder: (context, index) { + return sparePartActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: activities[index]); + }, + ).expanded, + if (userProvider.user!.type == UsersTypes.engineer && + (requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && requestDetailProvider.currentWorkOrder?.data?.status?.value != 3)) + FooterActionButton.footerContainer( + context: context, + child: AppFilledButton( + label: 'Create New Spare Part', + maxWidth: true, + buttonColor: AppColor.primary10, + loading: requestDetailProvider.isLoading, + disableButton: disableNewActivity, + onPressed: () async { + // ServiceRequestBottomSheet.activityTypeBottomSheet(context: context); + }, + )) + ], + ); + }), + ); + } + + Widget sparePartActivityCard({required CMDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) { + bool showActionButtons = userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId && + userProvider.user!.type == UsersTypes.engineer && + requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && + requestDetailProvider.currentWorkOrder?.data?.status?.value != 3; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + StatusLabel( + label: activity.activityStatus?.name, + textColor: AppColor.white10, + backgroundColor: AppColor.primary10, + ), + if (showActionButtons) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() { + editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); + }), + 12.width, + "delete_icon".toSvgAsset(height: 24, width: 24).onPress(() async { + showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + int status = await requestDetailProvider.deleteActivitySparePart(id: activity.id!, workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!); + if (status == 200) { + await requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!); + Navigator.pop(context); + } else { + Navigator.pop(context); + } + }), + ], + ) + ], + ), + 6.height, + InfoHeaderWidget(activity.activityType?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'), + InfoTextWidget( + label: context.translation.partName, + value: activity.activitySparePart?.partCatalogItem?.partName, + ), + InfoTextWidget( + label: context.translation.partNo, + value: activity.activitySparePart?.partCatalogItem?.partNumber, + showArrow: true, + ), + if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[ + 6.height, + const Divider().defaultStyle(context), + FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), + ], + ], + ).toShadowContainer(context, showShadow: false).onPress(() { + ///Move to cost page .. + // if (showActionButtons) return; + // if (requestDetailProvider.isReadOnlyRequest) { + // editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); + // } else if (userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId) { + // requestDetailProvider.isReadOnlyRequest = true; + // editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); + // } + }); + } + + void editSparePartRequest({required BuildContext context, required CMDetailProvider requestDetailProvider, required Activities activity}) async { + requestDetailProvider.sparePartHelperModel = SparePartHelperModel( + id: activity.id, + workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId, + comment: activity.activitySparePart?.comment, + sparePartAttachments: activity.activitySparePart?.acitiySparePartAttachments ?? [], + activityStatus: activity.activityStatus, + sparePart: SparePart( + id: activity.activitySparePart?.partCatalogItem?.id, + partName: activity.activitySparePart?.partCatalogItem?.partName, + partNo: activity.activitySparePart?.partCatalogItem?.partNumber, + oracleCode: activity.activitySparePart?.partCatalogItem?.oracleCode), + quantity: activity.activitySparePart?.quantity, + installQty: activity.activitySparePart?.installQty, + returnQty: activity.activitySparePart?.returnQty, + activityStatusId: activity.activityStatus?.id, + ); + + requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel); + + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => SparePartRequest( + model: requestDetailProvider.sparePartHelperModel, + provider: requestDetailProvider, + ), + )); + } +} diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart b/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart new file mode 100644 index 00000000..24cd885b --- /dev/null +++ b/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart @@ -0,0 +1,127 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/controllers/providers/api/user_provider.dart'; +import 'package:test_sa/controllers/providers/settings/setting_provider.dart'; +import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/extensions/int_extensions.dart'; +import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:test_sa/extensions/text_extensions.dart'; +import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/user_types.dart'; +import 'package:test_sa/models/enums/work_order_next_step.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; +import 'package:test_sa/models/new_models/work_order_detail_model.dart'; +import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; +import 'package:test_sa/modules/cm_module/views/forms/asset_retired/asset_retired.dart'; +import 'package:test_sa/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart'; +import 'package:test_sa/new_views/app_style/app_color.dart'; +import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; +import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart'; +import 'package:test_sa/views/widgets/images/files_list.dart'; +import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; +import 'package:test_sa/views/widgets/item_views/info_date_widget.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; +import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; +import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; +import 'package:test_sa/views/widgets/requests/request_status.dart'; +import 'package:test_sa/views/widgets/sound/sound_player.dart'; + +class PmCostDetailsView extends StatefulWidget { + PmCostDetailsView({Key? key}) : super(key: key); + + @override + State createState() => _PmCostDetailsViewState(); +} + +class _PmCostDetailsViewState extends State { + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + UserProvider userProvider = Provider.of(context, listen: false); + + ///TODO: replace with pm provider and data from provider and remove the extra widgets as well. + return Consumer(builder: (pContext, requestProvider, _) { + bool showCostCard = context.userProvider.user!.type == UsersTypes.engineer && + !requestProvider.isReadOnlyRequest && + requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity; + + return requestProvider.isLoading + ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center + : requestProvider.currentWorkOrder == null + ? const NoDataFound() + : Column( + children: [ + SingleChildScrollView( + padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (showCostCard) ...[ + 16.height, + costCard(context, requestProvider), + ], + ], + ), + ).expanded, + ], + ); + }); + } + + Widget costCard(BuildContext context, CMDetailProvider provider) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + InfoHeader16Widget("Cost"), + const Spacer(), + if (!provider.isReadOnlyRequest) + + ///TODO replace with exact provider and data from provider and remove the extra widgets as well. + "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async { + WorkOrderData currentWorkOrderData = provider.currentWorkOrder!.data!; + provider.workOrderCostModel = WorkOrderCostModel( + workOrderId: currentWorkOrderData.requestId, + labourCost: currentWorkOrderData.labourCost, + sparePartCost: currentWorkOrderData.sparePartCost, + travelCost: currentWorkOrderData.travelCost, + qAmount: currentWorkOrderData.qAmount, + prNo: currentWorkOrderData.prNo, + poNo: currentWorkOrderData.poNo, + mrNo: currentWorkOrderData.mrNo, + exchangeCost: currentWorkOrderData.exchangeCost, + ); + provider.refreshTimer = false; + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CostDetailFormScreen( + isEdit: true, + model: provider.workOrderCostModel, + provider: provider, + ))); + provider.refreshTimer = true; + }), + ], + ), + InfoTextWidget(label: 'Spare Part Cost'.addTranslation, value: provider.currentWorkOrder?.data?.sparePartCost?.toString() ?? '-'), + InfoTextWidget(label: 'Labor Cost'.addTranslation, value: provider.currentWorkOrder?.data?.labourCost?.toString() ?? '-'), + InfoTextWidget(label: 'Travel Cost'.addTranslation, value: provider.currentWorkOrder?.data?.travelCost?.toString() ?? '-'), + InfoTextWidget(label: 'Quot Amount'.addTranslation, value: provider.currentWorkOrder?.data?.qAmount?.toString() ?? '-'), + InfoTextWidget(label: 'PR No'.addTranslation, value: provider.currentWorkOrder?.data?.prNo?.toString() ?? '-'), + InfoTextWidget(label: 'PO No'.addTranslation, value: provider.currentWorkOrder?.data?.poNo?.toString() ?? '-'), + InfoTextWidget(label: 'MR No'.addTranslation, value: provider.currentWorkOrder?.data?.mrNo?.toString() ?? '-'), + InfoTextWidget(label: 'Exchange Cost'.addTranslation, value: provider.currentWorkOrder?.data?.exchangeCost?.toString() ?? '-'), + ], + ).toShadowContainer(context); + } +} diff --git a/lib/modules/pm_module/ppm_wo/ppm_details_page.dart b/lib/modules/pm_module/ppm_wo/ppm_details_page.dart index bf64bf9a..84bac35f 100644 --- a/lib/modules/pm_module/ppm_wo/ppm_details_page.dart +++ b/lib/modules/pm_module/ppm_wo/ppm_details_page.dart @@ -8,6 +8,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; @@ -82,6 +83,20 @@ class _PpmDetailsPageState extends State { textColor: AppColor.getRequestStatusTextColorByName(context, planPreventiveVisit.visitStatus!.name!), backgroundColor: AppColor.getRequestStatusColorByName(context, planPreventiveVisit.visitStatus!.name!), ), + // "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() { + // if(userProvider!.user!.type == UsersTypes.engineer && (!ppmProvider.isReadOnly)){ + // FooterActionButton.footerContainer( + // child: AppFilledButton( + // onPressed: () async { + // await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdatePpm(ppm: null, planPreventiveVisit: planPreventiveVisit))); + // getVisitData(); + // }, + // label: context.translation.updateWorkOrder, + // ), + // context: context, + // ); + // } + // }) ], ), InfoHeader16Widget(planPreventiveVisit.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? ''), @@ -104,26 +119,28 @@ class _PpmDetailsPageState extends State { ).expanded, if (userProvider!.user!.type == UsersTypes.engineer && (!ppmProvider.isReadOnly)) ...[ FooterActionButton.footerContainer( - child: AppFilledButton( - onPressed: () async { - await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdatePpm(ppm: null, planPreventiveVisit: planPreventiveVisit))); - getVisitData(); - }, - label: context.translation.updateWorkOrder, + child: Column( + children: [ + AppFilledButton( + onPressed: () async { + await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdatePpm(ppm: null, planPreventiveVisit: planPreventiveVisit))); + getVisitData(); + }, + label: context.translation.updateWorkOrder, + ), + 12.height, + AppFilledButton( + onPressed: () async { + await Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); + getVisitData(); + }, + buttonColor: AppColor.neutral50, + label: context.translation.activities, + ), + ], ), context: context, ) - ] else ...[ - // FooterActionButton.footerContainer( - // context: context, - // child: AppFilledButton( - // onPressed: () async { - // await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdatePpm(ppm: null, planPreventiveVisit: planPreventiveVisit))); - // getVisitData(); - // }, - // label: context.translation.viewDetails, - // ), - // ) ] ]) : const Center(child: NoDataFound()); From 7f4a06b0db8693a668a2f3e8e514bbba126d4e84 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Tue, 11 Aug 2026 11:38:36 +0300 Subject: [PATCH 02/47] PM activity and cost flow implemented --- lib/controllers/api_routes/urls.dart | 13 +- .../providers/api/parts_provider.dart | 17 +- .../providers/api/ppm_provider.dart | 159 +++++ .../spare_part/activity_spare_part_model.dart | 50 +- .../workorder/work_order_helper_models.dart | 3 + .../plan_preventive_visit_model.dart | 644 +++-------------- .../components/activities_list_view.dart | 18 +- .../service_request_bottomsheet.dart | 38 +- .../service_request_detail_view.dart | 1 - .../forms/cost/cost_detail_form_screen.dart | 304 ++++---- .../forms/spare_part/spare_part_request.dart | 658 ++++++++++-------- .../activities/pm_activities_list_view.dart | 137 ++-- .../activities/pm_cost_detail_page.dart | 127 ---- .../pm_module/ppm_wo/ppm_details_page.dart | 16 +- .../ppm_wo/update_ppm/update_ppm.dart | 168 +++-- .../ppm_wo/update_ppm/wo_info_form.dart | 77 ++ 16 files changed, 1150 insertions(+), 1280 deletions(-) delete mode 100644 lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index f9374337..b03cec52 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -254,8 +254,13 @@ class URLs { static get getRegularVisits => "$_baseUrl/Visit/GetVisits"; // get static get updateRegularVisits => "$_baseUrl/Visit/UpdateVisits"; // get - static get getPlanPreventiveVisitById => "$_baseUrl/PlanPreventiveVisit/GetPlanPreventiveVisitById"; // get - static get updateVisitByEngineer => "$_baseUrl/PlanPreventiveVisit/UpdateVisitByEngineer"; // get + static get getPlanPreventiveVisitById => "$_baseUrl/PlanPreventiveVisit/GetPlanPreventiveVisitById"; + static get updateVisitByEngineer => "$_baseUrl/PlanPreventiveVisit/UpdateVisitByEngineer"; + static get createPmActivitySparePart => "$_baseUrl/PlanPreventiveVisit/CreateActivitySparePart"; + static get updatePmActivitySparePart => "$_baseUrl/PlanPreventiveVisit/UpdateActivitySparePart"; + static get deletePmActivitySparePart => "$_baseUrl/PlanPreventiveVisit/DeleteActivitySparePart"; + static get updatePmActivityCost => "$_baseUrl/PlanPreventiveVisit/EngineerUpdateCost"; + static get getSingleServiceRequest => "$_baseUrl/return/call/information"; // get static get getSuppliersAutoComplete => "$_baseUrl/Supplier/GetSuppliersAutoComplete"; @@ -604,4 +609,8 @@ class URLs { static get submitApplicationDemoRequest => "$_baseUrl/DemoUser/CreateDemoUser"; // post submit application demo request// get application demo request history static get sendDemoUserOtp => "$_baseUrl/DemoUser/EmailVerification"; // post send OTP to user static get verifyDemoUserOtp => "$_baseUrl/DemoUser/VerifyOtp"; // post verify OTP + +// spare part request endpoint. + + } diff --git a/lib/controllers/providers/api/parts_provider.dart b/lib/controllers/providers/api/parts_provider.dart index fc2829b8..e50b7a7b 100644 --- a/lib/controllers/providers/api/parts_provider.dart +++ b/lib/controllers/providers/api/parts_provider.dart @@ -88,32 +88,39 @@ class PartsProvider extends ChangeNotifier { late Response response; try { if (partNo != null) { - response = await ApiManager.instance.post(URLs.getPartNumber, body: {"partNo": partNo, }); + response = await ApiManager.instance.post(URLs.getPartNumber, body: { + "partNo": partNo, + }); } else { - response = await ApiManager.instance.post(URLs.getPartNumber, body: {"partName": partName, }); + response = await ApiManager.instance.post(URLs.getPartNumber, body: { + "partName": partName, + }); } List page = []; if (response.statusCode >= 200 && response.statusCode < 300) { // client's request was successfully received List categoriesListJson = json.decode(response.body)["data"]; - page = categoriesListJson.map((part) => SparePart.fromJson(part,false)).toList(); + page = categoriesListJson.map((part) => SparePart.fromJson(part, false)).toList(); } return page; } catch (error) { return []; } } + // Implement this only for spare part request for now show and search on display name .... Future> getPartsListByDisplayName({num? assetId, String? displayName}) async { late Response response; try { - response = await ApiManager.instance.post(URLs.getPartNumber, body: {"displayName": displayName, }); + response = await ApiManager.instance.post(URLs.getPartNumber, body: { + "displayName": displayName, + }); List page = []; if (response.statusCode >= 200 && response.statusCode < 300) { // client's request was successfully received List categoriesListJson = json.decode(response.body)["data"]; - page = categoriesListJson.map((part) => SparePart.fromJson(part,true)).toList(); + page = categoriesListJson.map((part) => SparePart.fromJson(part, true)).toList(); } return page; } catch (error) { diff --git a/lib/controllers/providers/api/ppm_provider.dart b/lib/controllers/providers/api/ppm_provider.dart index 81a7e066..19d222cc 100644 --- a/lib/controllers/providers/api/ppm_provider.dart +++ b/lib/controllers/providers/api/ppm_provider.dart @@ -9,9 +9,12 @@ import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; +import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/models/ppm/ppm.dart'; import 'package:test_sa/models/ppm/ppm_search.dart'; +import 'package:test_sa/models/service_request/spare_parts.dart'; import 'package:test_sa/models/user.dart'; import '../../../new_views/common_widgets/app_lazy_loading.dart'; @@ -20,6 +23,15 @@ class PpmProvider extends ChangeNotifier { // number of items call in each request final pageItemNumber = 12; + bool _isReadOnlyRequest = false; + + bool get isReadOnlyRequest => _isReadOnlyRequest; + + set isReadOnlyRequest(bool value) { + _isReadOnlyRequest = value; + notifyListeners(); + } + PlanPreventiveVisit? _planPreventiveVisit; late int _totalTabs = 4; TabController? tabController; @@ -60,6 +72,14 @@ class PpmProvider extends ChangeNotifier { nextPage = true; stateCode = null; } + List _storeAvailability = []; + + List get storeAvailability => _storeAvailability; + + set storeAvailability(List value) { + _storeAvailability = value; + notifyListeners(); + } // state code of current request to defied error message // like 400 customer request failed @@ -78,6 +98,13 @@ class PpmProvider extends ChangeNotifier { bool isLoading = false; PpmSearch visitsSearch = PpmSearch(); + WorkOrderCostModel? workOrderCostModel; + SparePartHelperModel? sparePartHelperModel; + + void updateSparePartHelperModel(SparePartHelperModel? value) { + sparePartHelperModel = value; + notifyListeners(); + } /// return -2 if request in progress /// return -1 if error happen when sending request @@ -164,11 +191,24 @@ class PpmProvider extends ChangeNotifier { if (response.statusCode >= 200 && response.statusCode < 300) { ppmPlanAttachments = []; planPreventiveVisit = PlanPreventiveVisit.fromJson(json.decode(response.body)["data"]); + + // Set isReadOnly based on visit status (1 or 3 means closed/completed) if (planPreventiveVisit?.visitStatus?.value! == 1 || planPreventiveVisit?.visitStatus?.value == 3) { isReadOnly = true; } else { isReadOnly = false; } + + // Set isReadOnlyRequest based on visit status - same logic as CMDetailProvider + //Need to confirm this with backend Status values: 3 = Closed, 5 = Completed, 6 = Cancelled (adjust based on your PM status values) + if (planPreventiveVisit?.visitStatus?.value == 3 || + planPreventiveVisit?.visitStatus?.value == 5 || + planPreventiveVisit?.visitStatus?.value == 6) { + isReadOnlyRequest = true; + } else { + isReadOnlyRequest = false; + } + isLoading = false; notifyListeners(); return planPreventiveVisit; @@ -364,4 +404,123 @@ class PpmProvider extends ChangeNotifier { return true; } + + Future createActivitySparePart() async { + isLoading = true; + Response response; + try { + response = await ApiManager.instance.post( + URLs.createPmActivitySparePart, + body: sparePartHelperModel!.toPMJson(), + ); + stateCode = response.statusCode; + isLoading = false; + notifyListeners(); + if (stateCode == 200) { + return true; + } + return false; + } catch (error) { + isLoading = false; + stateCode = -1; + notifyListeners(); + return false; + } + } + + Future updateActivitySparePart() async { + isLoading = true; + Response response; + try { + response = await ApiManager.instance.post(URLs.updatePmActivitySparePart, body: sparePartHelperModel!.toPMJson()); + stateCode = response.statusCode; + isLoading = false; + notifyListeners(); + if (stateCode == 200) { + return true; + } + return false; + } catch (error) { + isLoading = false; + stateCode = -1; + notifyListeners(); + return false; + } + } + + Future deleteActivitySparePart({required int id}) async { + isLoading = true; + notifyListeners(); + try { + final response = await ApiManager.instance.delete('${URLs.deletePmActivitySparePart}?activitySparePartPPMId=$id', body: {}); + stateCode = response.statusCode; + if (response.statusCode >= 200 && response.statusCode < 300) { + } + isLoading = false; + notifyListeners(); + return response.statusCode; + } catch (error) { + isLoading = false; + notifyListeners(); + return -1; + } + } + + Future engineerUpdateCost() async { + isLoading = true; + Response response; + try { + response = await ApiManager.instance.post(URLs.updatePmActivityCost, body: workOrderCostModel!.toPMCostJson()); + stateCode = response.statusCode; + isLoading = false; + notifyListeners(); + if (stateCode == 200) { + planPreventiveVisit = PlanPreventiveVisit.fromJson(json.decode(response.body)["data"]); + + // Update isReadOnlyRequest after fetching updated data + if (planPreventiveVisit?.visitStatus?.value == 3 || + planPreventiveVisit?.visitStatus?.value == 5 || + planPreventiveVisit?.visitStatus?.value == 6) { + isReadOnlyRequest = true; + } else { + isReadOnlyRequest = false; + } + + notifyListeners(); + return true; + } + return false; + } catch (error) { + isLoading = false; + stateCode = -1; + notifyListeners(); + return false; + } + } + + Future getStoreAvailabilityById({required num? partId}) async { + try { + isLoading = true; + notifyListeners(); + + final response = await ApiManager.instance.post( + URLs.getSparePartAvailableQuantity + "?PartId=$partId", + body: {}, + ); + + stateCode = response.statusCode; + + if (response.statusCode >= 200 && response.statusCode < 300) { + final List data = json.decode(response.body)["data"]; + storeAvailability = data.map((item) => StoreAvailability.fromJson(item)).toList(); + } + + isLoading = false; + notifyListeners(); + } catch (e) { + log("getStoreAvalivility [error] : $e"); + isLoading = false; + notifyListeners(); + } + } } diff --git a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart index 1c51821f..548d47bb 100644 --- a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart +++ b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart @@ -4,6 +4,7 @@ import 'package:test_sa/models/service_request/spare_parts.dart'; class SparePartHelperModel { int? id; int? workOrderId; + String? pmVisitId; int? partCatalogItemId; int? activityStatusId; SparePart? sparePart; @@ -12,11 +13,13 @@ class SparePartHelperModel { num? installQty; num? returnQty; String? comment; - List? sparePartAttachments; + + List sparePartAttachments; SparePartHelperModel({ this.id, this.workOrderId, + this.pmVisitId, this.partCatalogItemId, this.quantity, this.installQty, @@ -24,9 +27,9 @@ class SparePartHelperModel { this.sparePart, this.activityStatusId, this.activityStatus, - this.comment,this.sparePartAttachments, - }); - + this.comment, + List? sparePartAttachments, + }) : sparePartAttachments = sparePartAttachments ?? []; Map toJson() { final Map data = {}; @@ -36,13 +39,42 @@ class SparePartHelperModel { data['quantity'] = quantity; data['installQty'] = installQty; data['returnQty'] = returnQty; - if(activityStatus!=null){ + if (activityStatus != null) { data['activityStatusId'] = activityStatus?.id; } data['comment'] = comment; - if (sparePartAttachments != null) { - data['acitiySparePartAttachments'] = - sparePartAttachments!.map((v) => v.toJson()).toList(); + if (sparePartAttachments.isNotEmpty) { + data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toJson()).toList(); + } + return data; + } + + //{ + // "id": 0, + // "planPreventiveVisitId": 0, + // "partCatalogItemId": 0, + // "quantity": 0, + // "comment": "string", + // "acitiySparePartAttachments": [ + // { + // "id": 0, + // "name": "string", + // "originalName": "string", + // "attachmentTypeId": 0, + // "attachmentName": "string", + // "attachmentURL": "string" + // } + // ] + // } + Map toPMJson() { + final Map data = {}; + data['id'] = id; + data['planPreventiveVisitId'] = pmVisitId; + data['partCatalogItemId'] = sparePart?.id; + data['quantity'] = quantity; + data['comment'] = comment; + if (sparePartAttachments.isNotEmpty) { + data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toJson()).toList(); } return data; } @@ -65,4 +97,4 @@ class SparePartAttachments { data['name'] = name; return data; } -} \ No newline at end of file +} diff --git a/lib/models/helper_data_models/workorder/work_order_helper_models.dart b/lib/models/helper_data_models/workorder/work_order_helper_models.dart index b15924d6..5515c27d 100644 --- a/lib/models/helper_data_models/workorder/work_order_helper_models.dart +++ b/lib/models/helper_data_models/workorder/work_order_helper_models.dart @@ -178,4 +178,7 @@ class WorkOrderCostModel { Map toJson() { return {'workOrderId': workOrderId, 'sparePartCost': sparePartCost, 'laborCost': labourCost, 'travelCost': travelCost, 'qAmount': qAmount, 'prNo': prNo, 'poNo': poNo,'mrNo':mrNo,'exchangeCost':exchangeCost}; } + Map toPMCostJson() { + return {'planPreventiveVisitId': workOrderId, 'sparePartCost': sparePartCost, 'laborCost': labourCost, 'travelCost': travelCost, 'qAmount': qAmount, 'prNo': prNo, 'poNo': poNo,'mrNo':mrNo,'exchangeCost':exchangeCost}; + } } diff --git a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart index b8f5fd94..87087c3b 100644 --- a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart +++ b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart @@ -1,9 +1,11 @@ +import 'dart:developer'; import 'dart:io'; import 'package:flutter/widgets.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/supplier_details.dart'; import 'package:test_sa/models/timer_model.dart'; @@ -49,10 +51,20 @@ class PlanPreventiveVisit { List? preventiveVisitKits; List? preventiveVisitTimers; List? preventiveVisitSuppliers; + List? activities; + num? sparePartCost; + num? labourCost; + num? travelCost; + num? qAmount; + String? prNo; + String? poNo; + String? mrNo; + num? exchangeCost; TimerModel? tbsTimer = TimerModel(); List? timerModelList = []; TimerModel? ppMTimePicker; + PlanPreventiveVisit( {this.id, this.visitNo, @@ -95,6 +107,15 @@ class PlanPreventiveVisit { this.preventiveVisitTimers, this.timerModelList, this.ppMTimePicker, + this.activities, + this.labourCost, + this.sparePartCost, + this.travelCost, + this.qAmount, + this.prNo, + this.poNo, + this.mrNo, + this.exchangeCost, this.preventiveVisitSuppliers}); PlanPreventiveVisit.fromJson(Map json) { @@ -131,6 +152,14 @@ class PlanPreventiveVisit { safety = json['safety'] != null ? Lookup.fromJson(json['safety']) : null; engSignature = json['engSignature']; nurseSignature = json['nurseSignature']; + travelCost= json['travelCost']; + sparePartCost= json['sparePartCost']; + labourCost =json['laborCost']; + qAmount= json['qAmount']; + prNo= json['prNo']; + poNo= json['poNo']; + mrNo= json['mrNo']; + exchangeCost= json['exchangeCost']; if (json['preventiveVisitAttachments'] != null) { preventiveVisitAttachments = []; json['preventiveVisitAttachments'].forEach((v) { @@ -167,6 +196,13 @@ class PlanPreventiveVisit { preventiveVisitSuppliers!.add(PreventiveVisitSuppliers.fromJson(v)); }); } + if (json['activitySparePartsPPM'] != null) { + log("activitySparePartsPPM: ${json['activitySparePartsPPM']}"); + activities = []; + json['activitySparePartsPPM'].forEach((v) { + activities!.add(PMSparePartActivityModel.fromJson(v)); + }); + } } Map toJson({required int status}) { @@ -183,50 +219,6 @@ class PlanPreventiveVisit { data['safetyId'] = safety?.id; data['engSignature'] = engSignature; data['nurseSignature'] = nurseSignature; - // - // if (asset != null) { - // data['asset'] = asset!.toJson(); - // } - // data['visitNo'] = visitNo; - // data['planNo'] = planNo; - // data['planName'] = planName; - // data['nextPMDate'] = nextPMDate; - // data['assetName'] = assetName; - // data['model'] = model; - // data['manufacturer'] = manufacturer; - // data['supplierName'] = supplierName; - // data['siteName'] = siteName; - // data['buildingName'] = buildingName; - // data['floorName'] = floorName; - // data['departmentName'] = departmentName; - // data['roomName'] = roomName; - // data['fromDate'] = fromDate; - // data['toDate'] = toDate; - // if (assignedEmployee != null) { - // data['assignedEmployee'] = assignedEmployee!.toJson(); - // } - // data['acutalDateOfVisit'] = acutalDateOfVisit; - // if (typeOfService != null) { - // data['typeOfService'] = typeOfService!.toJson(); - // } - // if (visitStatus != null) { - // data['visitStatus'] = visitStatus!.toJson(); - // } - // data['travelingHours'] = travelingHours; - // data['comments'] = comments; - // data['executionTimeFrame'] = executionTimeFrame; - // if (taskStatus != null) { - // data['taskStatus'] = taskStatus!.toJson(); - // } - // if (deviceStatus != null) { - // data['deviceStatus'] = deviceStatus!.toJson(); - // } - // data['assetAvailability'] = assetAvailability; - // if (safety != null) { - // data['safety'] = safety!.toJson(); - // } - // data['engSignature'] = engSignature; - // data['nurseSignature'] = nurseSignature; if (preventiveVisitAttachments != null) { data['preventiveVisitAttachments'] = preventiveVisitAttachments!.map((v) => v.toJson()).toList(); @@ -246,14 +238,12 @@ class PlanPreventiveVisit { if (preventiveVisitSuppliers != null) { data['preventiveVisitSuppliers'] = preventiveVisitSuppliers!.map((v) => v.toJson()).toList(); } + if (activities != null) { + data['activitySparePartsPPM'] = activities!.map((v) => v.toJson()).toList(); + } return data; } - bool _isLocalUrl(String url) { - if (url.isEmpty != false) return false; - return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); - } - Future validate(BuildContext context) async { if (visitStatus?.id == null) { await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.status}"); @@ -290,276 +280,6 @@ class PlanPreventiveVisit { } } -// class PlanPreventiveVisit { -// String? id; -// String? visitNo; -// Asset? asset; -// String? planNo; -// String? planName; -// String? nextPMDate; -// String? assetName; -// String? model; -// String? manufacturer; -// String? supplierName; -// String? siteName; -// String? buildingName; -// String? floorName; -// String? departmentName; -// String? roomName; -// String? fromDate; -// String? toDate; -// AssignedEmployee? assignedEmployee; -// String? acutalDateOfVisit; -// TypeOfService? typeOfService; -// VisitStatus? visitStatus; -// String? travelingHours; -// String? comments; -// int? executionTimeFrame; -// Lookup? taskStatus; -// String? deviceStatus; -// Lookup? assetAvailability; -// Lookup? safety; -// String? engSignature; -// String? nurseSignature; -// List? preventiveVisitAttachments; -// List? preventiveVisitCalibrations; -// List? preventiveVisitChecklists; -// List? preventiveVisitKits; -// List? preventiveVisitTimers; -// List? preventiveVisitSuppliers; -// TimerModel? tbsTimer = TimerModel(); -// -// PlanPreventiveVisit( -// {this.id, -// this.visitNo, -// this.asset, -// this.planNo, -// this.planName, -// this.nextPMDate, -// this.assetName, -// this.model, -// this.manufacturer, -// this.supplierName, -// this.siteName, -// this.buildingName, -// this.floorName, -// this.departmentName, -// this.roomName, -// this.fromDate, -// this.toDate, -// this.assignedEmployee, -// this.acutalDateOfVisit, -// this.typeOfService, -// this.visitStatus, -// this.travelingHours, -// this.comments, -// this.executionTimeFrame, -// this.taskStatus, -// this.deviceStatus, -// this.assetAvailability, -// this.safety, -// this.engSignature, -// this.nurseSignature, -// this.preventiveVisitAttachments, -// this.preventiveVisitCalibrations, -// this.preventiveVisitChecklists, -// this.preventiveVisitKits, -// this.preventiveVisitTimers, -// this.preventiveVisitSuppliers}); -// -// PlanPreventiveVisit.fromJson(Map json) { -// id = json['id']; -// visitNo = json['visitNo']; -// asset = json['asset'] != null ? Asset.fromJson(json['asset']) : null; -// planNo = json['planNo']; -// planName = json['planName']; -// nextPMDate = json['nextPMDate']; -// assetName = json['assetName']; -// model = json['model']; -// manufacturer = json['manufacturer']; -// supplierName = json['supplierName']; -// siteName = json['siteName']; -// buildingName = json['buildingName']; -// floorName = json['floorName']; -// departmentName = json['departmentName']; -// roomName = json['roomName']; -// fromDate = json['fromDate']; -// toDate = json['toDate']; -// assignedEmployee = json['assignedEmployee'] != null ? AssignedEmployee.fromJson(json['assignedEmployee']) : null; -// acutalDateOfVisit = json['acutalDateOfVisit']; -// typeOfService = json['typeOfService'] != null ? TypeOfService.fromJson(json['typeOfService']) : null; -// visitStatus = json['visitStatus'] != null ? VisitStatus.fromJson(json['visitStatus']) : null; -// travelingHours = json['travelingHours']; -// comments = json['comments']; -// executionTimeFrame = json['executionTimeFrame']; -// taskStatus = json['taskStatus']; -// deviceStatus = json['deviceStatus']; -// assetAvailability = json['assetAvailability']; -// safety = json['safety']; -// engSignature = json['engSignature']; -// nurseSignature = json['nurseSignature']; -// if (json['preventiveVisitAttachments'] != null) { -// preventiveVisitAttachments = []; -// json['preventiveVisitAttachments'].forEach((v) { -// preventiveVisitAttachments!.add(PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitCalibrations'] != null) { -// preventiveVisitCalibrations = []; -// json['preventiveVisitCalibrations'].forEach((v) { -// preventiveVisitCalibrations!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitChecklists'] != null) { -// preventiveVisitChecklists = []; -// json['preventiveVisitChecklists'].forEach((v) { -// preventiveVisitChecklists!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitKits'] != null) { -// preventiveVisitKits = []; -// json['preventiveVisitKits'].forEach((v) { -// preventiveVisitKits!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitTimers'] != null) { -// preventiveVisitTimers = []; -// json['preventiveVisitTimers'].forEach((v) { -// preventiveVisitTimers!.add( PreventiveVisitTimers.fromJson(v)); -// }); -// } -// if (json['preventiveVisitSuppliers'] != null) { -// preventiveVisitSuppliers = []; -// json['preventiveVisitSuppliers'].forEach((v) { -// preventiveVisitSuppliers!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['visitNo'] = this.visitNo; -// if (this.asset != null) { -// data['asset'] = this.asset!.toJson(); -// } -// data['planNo'] = this.planNo; -// data['planName'] = this.planName; -// data['nextPMDate'] = this.nextPMDate; -// data['assetName'] = this.assetName; -// data['model'] = this.model; -// data['manufacturer'] = this.manufacturer; -// data['supplierName'] = this.supplierName; -// data['siteName'] = this.siteName; -// data['buildingName'] = this.buildingName; -// data['floorName'] = this.floorName; -// data['departmentName'] = this.departmentName; -// data['roomName'] = this.roomName; -// data['fromDate'] = this.fromDate; -// data['toDate'] = this.toDate; -// if (this.assignedEmployee != null) { -// data['assignedEmployee'] = this.assignedEmployee!.toJson(); -// } -// data['acutalDateOfVisit'] = this.acutalDateOfVisit; -// if (this.typeOfService != null) { -// data['typeOfService'] = this.typeOfService!.toJson(); -// } -// if (this.visitStatus != null) { -// data['visitStatus'] = this.visitStatus!.toJson(); -// } -// data['travelingHours'] = this.travelingHours; -// data['comments'] = this.comments; -// data['executionTimeFrame'] = this.executionTimeFrame; -// data['taskStatus'] = this.taskStatus; -// data['deviceStatus'] = this.deviceStatus; -// data['assetAvailability'] = this.assetAvailability; -// data['safety'] = this.safety; -// data['engSignature'] = this.engSignature; -// data['nurseSignature'] = this.nurseSignature; -// if (this.preventiveVisitAttachments != null) { -// data['preventiveVisitAttachments'] = this.preventiveVisitAttachments!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitCalibrations != null) { -// data['preventiveVisitCalibrations'] = this.preventiveVisitCalibrations!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitChecklists != null) { -// data['preventiveVisitChecklists'] = this.preventiveVisitChecklists!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitKits != null) { -// data['preventiveVisitKits'] = this.preventiveVisitKits!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitTimers != null) { -// data['preventiveVisitTimers'] = this.preventiveVisitTimers!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitSuppliers != null) { -// data['preventiveVisitSuppliers'] = this.preventiveVisitSuppliers!.map((v) => v.toJson()).toList(); -// } -// return data; -// } -// -// bool _isLocalUrl(String url) { -// if (url.isEmpty != false) return false; -// return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); -// } -// -// Future validate(BuildContext context) async { -// if (visitStatus?.id == null) { -// await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.status}"); -// return false; -// } -// if (acutalDateOfVisit == null) { -// await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.actualDate}"); -// return false; -// } -// // if (expectedDate == null) { -// // await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.visitDate}"); -// // return false; -// // } -// if (tbsTimer?.startAt == null) { -// await Fluttertoast.showToast(msg: "Working Hours Required"); -// return false; -// } -// if (tbsTimer?.endAt == null) { -// await Fluttertoast.showToast(msg: "Please Stop The Timer"); -// return false; -// } -// -// // if (externalEngineerTimer?.startAt != null && externalEngineerTimer?.endAt == null) { -// // await Fluttertoast.showToast(msg: "Please Stop External Engineer Timer"); -// // return false; -// // } -// -// return true; -// } -// -// void removeEmptyObjects() { -// // if (vCalibrationTools?.isNotEmpty ?? false) vCalibrationTools!.removeWhere((element) => element.assetId == null && element.calibrationDateOfTesters == null); -// // if (vKits?.isNotEmpty ?? false) vKits!.removeWhere((element) => element.partName == null && element.partNumber == null); -// } -// } - -// class Asset { -// num? id; -// String? assetNumber; -// String? assetSerialNo; -// -// Asset({this.id, this.assetNumber, this.assetSerialNo}); -// -// Asset.fromJson(Map json) { -// id = json['id']; -// assetNumber = json['assetNumber']; -// assetSerialNo = json['assetSerialNo']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['assetNumber'] = this.assetNumber; -// data['assetSerialNo'] = this.assetSerialNo; -// return data; -// } -// } - class AssignedEmployee { String? userId; String? userName; @@ -588,50 +308,6 @@ class AssignedEmployee { } } -// class Lookup { -// int? id; -// String? name; -// int? value; -// -// Lookup({this.id, this.name, this.value}); -// -// Lookup.fromJson(Map json) { -// id = json['id']; -// name = json['name']; -// value = json['value']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['name'] = this.name; -// data['value'] = this.value; -// return data; -// } -// } - -// class VisitStatus { -// int? id; -// String? name; -// int? value; -// -// VisitStatus({this.id, this.name, this.value}); -// -// VisitStatus.fromJson(Map json) { -// id = json['id']; -// name = json['name']; -// value = json['value']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['name'] = this.name; -// data['value'] = this.value; -// return data; -// } -// } - class PreventiveVisitChecklists { int? id; Lookup? taskStatus; @@ -788,171 +464,6 @@ class PreventiveVisitSuppliers { } } -// class Supplier { -// int? id; -// String? suppliername; -// String? name; -// String? website; -// String? email; -// String? code; -// int? suppNo; -// String? suppStatusId; -// String? cityId; -// String? person; -// String? comment; -// String? zipcode; -// String? contact; -// List? telephones; -// List? faxes; -// List? addresses; -// List? attachments; -// List? suppPersons; -// List? suppTCodes; -// -// Supplier( -// {this.id, -// this.suppliername, -// this.name, -// this.website, -// this.email, -// this.code, -// this.suppNo, -// this.suppStatusId, -// this.cityId, -// this.person, -// this.comment, -// this.zipcode, -// this.contact, -// this.telephones, -// this.faxes, -// this.addresses, -// this.attachments, -// this.suppPersons, -// this.suppTCodes}); -// -// Supplier.fromJson(Map json) { -// id = json['id']; -// suppliername = json['suppliername']; -// name = json['name']; -// website = json['website']; -// email = json['email']; -// code = json['code']; -// suppNo = json['suppNo']; -// suppStatusId = json['suppStatusId']; -// cityId = json['cityId']; -// person = json['person']; -// comment = json['comment']; -// zipcode = json['zipcode']; -// contact = json['contact']; -// if (json['telephones'] != null) { -// telephones = []; -// json['telephones'].forEach((v) { -// telephones!.add(v); -// }); -// } -// if (json['faxes'] != null) { -// faxes = []; -// json['faxes'].forEach((v) { -// faxes!.add(v); -// }); -// } -// if (json['addresses'] != null) { -// addresses = []; -// json['addresses'].forEach((v) { -// addresses!.add(v); -// }); -// } -// if (json['attachments'] != null) { -// attachments = []; -// json['attachments'].forEach((v) { -// attachments!.add(v); -// }); -// } -// if (json['suppPersons'] != null) { -// suppPersons = []; -// json['suppPersons'].forEach((v) { -// suppPersons!.add(SuppPersons.fromJson(v)); -// }); -// } -// if (json['suppTCodes'] != null) { -// suppTCodes = []; -// json['suppTCodes'].forEach((v) { -// suppTCodes!.add(v); -// }); -// } -// } -// -// Map toJson() { -// final Map data = {}; -// data['id'] = id; -// data['suppliername'] = suppliername; -// data['name'] = name; -// data['website'] = website; -// data['email'] = email; -// data['code'] = code; -// data['suppNo'] = suppNo; -// data['suppStatusId'] = suppStatusId; -// data['cityId'] = cityId; -// data['person'] = person; -// data['comment'] = comment; -// data['zipcode'] = zipcode; -// data['contact'] = contact; -// if (telephones != null) { -// data['telephones'] = telephones!.map((v) => v).toList(); -// } -// if (faxes != null) { -// data['faxes'] = faxes!.map((v) => v).toList(); -// } -// if (addresses != null) { -// data['addresses'] = addresses!.map((v) => v).toList(); -// } -// if (attachments != null) { -// data['attachments'] = attachments!.map((v) => v).toList(); -// } -// if (suppPersons != null) { -// data['suppPersons'] = suppPersons!.map((v) => v.toJson()).toList(); -// } -// if (suppTCodes != null) { -// data['suppTCodes'] = suppTCodes!.map((v) => v).toList(); -// } -// return data; -// } -// } - -// class SuppPersons { -// int? id; -// int? supplierId; -// String? personName; -// int? personRoleId; -// String? contact; -// String? externalEngCode; -// String? email; -// -// SuppPersons({this.id, this.supplierId, this.personName, this.personRoleId, this.contact, this.externalEngCode, this.email}); -// -// SuppPersons.fromJson(Map json) { -// id = json['id']; -// supplierId = json['supplierId']; -// personName = json['personName']; -// personRoleId = json['personRoleId']; -// contact = json['contact']; -// externalEngCode = json['externalEngCode']; -// email = json['email']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['supplierId'] = this.supplierId; -// data['personName'] = this.personName; -// data['personRoleId'] = this.personRoleId; -// data['contact'] = this.contact; -// data['externalEngCode'] = this.externalEngCode; -// data['email'] = this.email; -// return data; -// } -// } - class PreventiveVisitKits { int? id; PartCatalogItem? partCatalogItem; @@ -999,3 +510,80 @@ class PartCatalogItem { return data; } } + +class PMSparePartActivityModel { + int? id; + PartCatalogItem? partCatalogItem; + Lookup? activityStatus; + double? quantity; + double? installQty; + double? returnQty; + String? comment; + dynamic price; + + List activitySparePartPPMAttachments; + + PMSparePartActivityModel({ + this.id, + this.partCatalogItem, + this.activityStatus, + this.quantity, + this.installQty, + this.returnQty, + this.comment, + this.price, + List? activitySparePartPPMAttachments, + }) : activitySparePartPPMAttachments = activitySparePartPPMAttachments ?? []; + + PMSparePartActivityModel.fromJson(Map json) : activitySparePartPPMAttachments = [] { + id = json['id']; + + partCatalogItem = json['partCatalogItem'] != null ? PartCatalogItem.fromJson(json['partCatalogItem']) : null; + + activityStatus = json['activityStatus'] != null ? Lookup.fromJson(json['activityStatus']) : null; + + quantity = json['quantity']?.toDouble(); + installQty = json['installQty']?.toDouble(); + returnQty = json['returnQty']?.toDouble(); + + comment = json['comment']; + price = json['price']; + + // Handle typo in API response: "acitiySparePartPPMAttachments" instead of "activitySparePartPPMAttachments" + final attachmentsKey = json.containsKey('acitiySparePartPPMAttachments') + ? 'acitiySparePartPPMAttachments' + : 'activitySparePartPPMAttachments'; + + activitySparePartPPMAttachments = json[attachmentsKey] == null + ? [] + : List.from(json[attachmentsKey]).map((e) => SparePartAttachments.fromJson(e)).toList(); + } + + Map toJson() { + final Map data = {}; + + data['id'] = id; + + if (partCatalogItem != null) { + data['partCatalogItem'] = partCatalogItem!.toJson(); + } + + if (activityStatus != null) { + data['activityStatus'] = activityStatus!.toJson(); + } + + data['quantity'] = quantity; + data['installQty'] = installQty; + data['returnQty'] = returnQty; + data['comment'] = comment; + data['price'] = price; + + data['activitySparePartPPMAttachments'] = activitySparePartPPMAttachments + .map( + (v) => v.toJson(), + ) + .toList(); + + return data; + } +} diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index d0294f6d..b589e787 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -251,7 +251,6 @@ class _ActivitiesListViewState extends State { label: context.translation.assistantEmployee, value: activity.activityMaintenance?.assistantEmployees?.first.user?.userName, ), - ] else ...[ InfoTextWidget( label: context.translation.assignedEmployee, @@ -344,29 +343,30 @@ class _ActivitiesListViewState extends State { } void editSparePartRequest({required BuildContext context, required CMDetailProvider requestDetailProvider, required Activities activity}) async { - requestDetailProvider.sparePartHelperModel = SparePartHelperModel( + final model = SparePartHelperModel( id: activity.id, workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId, comment: activity.activitySparePart?.comment, sparePartAttachments: activity.activitySparePart?.acitiySparePartAttachments ?? [], activityStatus: activity.activityStatus, sparePart: SparePart( - id: activity.activitySparePart?.partCatalogItem?.id, - partName: activity.activitySparePart?.partCatalogItem?.partName, - partNo: activity.activitySparePart?.partCatalogItem?.partNumber, - oracleCode: activity.activitySparePart?.partCatalogItem?.oracleCode), + id: activity.activitySparePart?.partCatalogItem?.id, + partName: activity.activitySparePart?.partCatalogItem?.partName, + partNo: activity.activitySparePart?.partCatalogItem?.partNumber, + oracleCode: activity.activitySparePart?.partCatalogItem?.oracleCode, + ), quantity: activity.activitySparePart?.quantity, installQty: activity.activitySparePart?.installQty, returnQty: activity.activitySparePart?.returnQty, activityStatusId: activity.activityStatus?.id, ); - requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel); - + // Navigate and let SparePartRequest._initializeModel() handle provider setup Navigator.of(context).push(MaterialPageRoute( builder: (_) => SparePartRequest( - model: requestDetailProvider.sparePartHelperModel, + model: model, provider: requestDetailProvider, + fromCm: true, ), )); } diff --git a/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart b/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart index 72e0b6f9..2272212a 100644 --- a/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart +++ b/lib/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/app_strings/app_asset.dart'; +import 'package:test_sa/controllers/providers/api/ppm_provider.dart'; import 'package:test_sa/controllers/providers/api/service_requests_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; @@ -671,14 +672,20 @@ class ServiceRequestBottomSheet { CMDetailProvider requestDetailProvider = Provider.of(context, listen: false); switch (index) { case 0: - requestDetailProvider.sparePartHelperModel = SparePartHelperModel(); + // Create fresh model - SparePartRequest will handle setting it in provider + final model = SparePartHelperModel( + id: 0, + workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId, + ); Navigator.pushReplacement( context, MaterialPageRoute( - builder: (context) => SparePartRequest( - model: requestDetailProvider.sparePartHelperModel, - provider: requestDetailProvider, - )), + builder: (context) => SparePartRequest( + model: model, + provider: requestDetailProvider, + fromCm: true, + ), + ), ); break; case 1: @@ -772,7 +779,7 @@ class ServiceRequestBottomSheet { })); } - static Future addAnotherSpareRequestBottomSheet({required BuildContext context}) { + static Future addAnotherSpareRequestBottomSheet({required BuildContext context, bool fromCm = false}) { return buildBottomSheetParent( context: context, childWidget: Consumer( @@ -808,16 +815,23 @@ class ServiceRequestBottomSheet { buttonColor: AppColor.primary10, loading: false, onPressed: () { - CMDetailProvider provider = Provider.of(context, listen: false); + dynamic provider = fromCm ? Provider.of(context, listen: false) : Provider.of(context, listen: false); Navigator.pop(context); - provider.sparePartHelperModel = SparePartHelperModel(); + final model = SparePartHelperModel( + id: 0, + workOrderId: fromCm? provider.currentWorkOrder?.data?.requestId:null, + pmVisitId: !fromCm? provider.planPreventiveVisit?.id:null, + ); + Navigator.pushReplacement( context, MaterialPageRoute( - builder: (context) => SparePartRequest( - model: provider.sparePartHelperModel, - provider: provider, - )), + builder: (context) => SparePartRequest( + model: model, + provider: provider, + fromCm: fromCm, + ), + ), ); }, ).expanded, diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index 766c5586..6e4e3bd3 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -355,7 +355,6 @@ class _ServiceRequestDetailViewState extends State { context, MaterialPageRoute( builder: (context) => CostDetailFormScreen( - isEdit: true, model: provider.workOrderCostModel, provider: provider, ))); diff --git a/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart b/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart index 1c21e035..94b7f842 100644 --- a/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart +++ b/lib/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart @@ -1,9 +1,10 @@ +import 'dart:developer'; + import 'package:flutter/material.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; -import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; @@ -13,13 +14,11 @@ import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; class CostDetailFormScreen extends StatefulWidget { static const String id = "/cost-detail-form-screen"; - final bool isEdit; final WorkOrderCostModel? model; - final CMDetailProvider provider; + final dynamic provider; // CMDetailProvider or PpmProvider const CostDetailFormScreen({ Key? key, - required this.isEdit, required this.model, required this.provider, }) : super(key: key); @@ -28,13 +27,29 @@ class CostDetailFormScreen extends StatefulWidget { _CostDetailFormScreenState createState() => _CostDetailFormScreenState(); } -class _CostDetailFormScreenState extends State with TickerProviderStateMixin { - final GlobalKey _scaffoldKey = GlobalKey(); +class _CostDetailFormScreenState extends State { + late WorkOrderCostModel _localModel; + + @override + void initState() { + super.initState(); + _localModel = WorkOrderCostModel( + workOrderId: widget.model?.workOrderId, + labourCost: widget.model?.labourCost, + sparePartCost: widget.model?.sparePartCost, + travelCost: widget.model?.travelCost, + qAmount: widget.model?.qAmount, + prNo: widget.model?.prNo, + poNo: widget.model?.poNo, + mrNo: widget.model?.mrNo, + exchangeCost: widget.model?.exchangeCost, + ); + log('Initialized Cost Model: ${_localModel.toJson()}'); + } @override Widget build(BuildContext context) { return Scaffold( - key: _scaffoldKey, appBar: const DefaultAppBar(title: "Cost Details"), body: ListenableBuilder( listenable: widget.provider, @@ -43,142 +58,131 @@ class _CostDetailFormScreenState extends State with Ticker crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - SingleChildScrollView( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - AppTextFormField( - labelText: "Spare Part Cost", - backgroundColor: AppColor.neutral100, - initialValue: widget.model?.sparePartCost?.toString(), - textAlign: TextAlign.center, - enable: false, - labelStyle: AppTextStyles.textFieldLabelStyle, - textInputType: TextInputType.number, - showShadow: false, - onChange: (value) { - widget.model?.sparePartCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - initialValue: widget.model?.labourCost?.toString(), - textAlign: TextAlign.center, - labelText: "Labor Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.labourCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Travel Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.travelCost?.toString(), - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.travelCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Quot Amount", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.qAmount?.toString(), - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.qAmount = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "PR No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.prNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.prNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "PO No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.poNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.poNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "MR No", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.mrNo, - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.mrNo = value; - }, - style: Theme.of(context).textTheme.titleMedium, - ), - 8.height, - AppTextFormField( - labelText: "Exchange Cost", - backgroundColor: AppColor.fieldBgColor(context), - labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), - initialValue: widget.model?.exchangeCost != null ? widget.model?.exchangeCost.toString() : '', - textAlign: TextAlign.center, - textInputType: const TextInputType.numberWithOptions(decimal: true), - showShadow: false, - onChange: (value) { - widget.model?.exchangeCost = num.parse(value); - }, - style: Theme.of(context).textTheme.titleMedium, - ), - ], - ).toShadowContainer(context).paddingAll(16), - ).expanded, + Expanded( + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AppTextFormField( + labelText: "Spare Part Cost", + backgroundColor: AppColor.neutral100, + initialValue: _localModel.sparePartCost?.toString() ?? '0', + textAlign: TextAlign.center, + enable: false, + labelStyle: AppTextStyles.textFieldLabelStyle, + textInputType: TextInputType.number, + showShadow: false, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + initialValue: _localModel.labourCost?.toString() ?? '', + textAlign: TextAlign.center, + labelText: "Labor Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + _localModel.labourCost = num.tryParse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Travel Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.travelCost?.toString() ?? '', + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + _localModel.travelCost = num.tryParse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Quot Amount", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.qAmount?.toString() ?? '', + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + _localModel.qAmount = num.tryParse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "PR No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.prNo ?? '', + textAlign: TextAlign.center, + textInputType: TextInputType.text, + showShadow: false, + onChange: (value) { + _localModel.prNo = value.isEmpty ? null : value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "PO No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.poNo ?? '', + textAlign: TextAlign.center, + textInputType: TextInputType.text, + showShadow: false, + onChange: (value) { + _localModel.poNo = value.isEmpty ? null : value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "MR No", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.mrNo ?? '', + textAlign: TextAlign.center, + textInputType: TextInputType.text, + showShadow: false, + onChange: (value) { + _localModel.mrNo = value.isEmpty ? null : value; + }, + style: Theme.of(context).textTheme.titleMedium, + ), + 8.height, + AppTextFormField( + labelText: "Exchange Cost", + backgroundColor: AppColor.fieldBgColor(context), + labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)), + initialValue: _localModel.exchangeCost?.toString() ?? '', + textAlign: TextAlign.center, + textInputType: const TextInputType.numberWithOptions(decimal: true), + showShadow: false, + onChange: (value) { + _localModel.exchangeCost = num.tryParse(value); + }, + style: Theme.of(context).textTheme.titleMedium, + ), + ], + ).toShadowContainer(context).paddingAll(16), + ), + ), FooterActionButton.footerContainer( context: context, child: AppFilledButton( label: "Update Cost Details", buttonColor: AppColor.primary10, - onPressed: () async { - if (validateForm()) { - showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); - await widget.provider.engineerUpdateCost().then((success) { - Navigator.pop(context); - if (success) { - Navigator.pop(context); - } - }); - } - }, + onPressed: () => _onSubmit(), ), ), ], @@ -188,11 +192,25 @@ class _CostDetailFormScreenState extends State with Ticker ); } - bool validateForm() { - bool isValid = true; - if (!widget.isEdit) { - return true; + Future _onSubmit() async { + widget.provider.workOrderCostModel = _localModel; + showDialog( + context: context, + barrierDismissible: false, + builder: (context) => const AppLazyLoading(), + ); + + try { + final success = await widget.provider.engineerUpdateCost(); + + if (mounted) Navigator.pop(context); // Close loading + + if (success && mounted) { + Navigator.pop(context); + } + } catch (e) { + if (mounted) Navigator.pop(context); + log('Error updating cost: $e'); } - return isValid; } } diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 46a51f77..2cc85ef4 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -1,7 +1,7 @@ -import 'dart:async'; + import 'dart:convert'; +import 'dart:developer'; import 'dart:io'; - import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/providers/api/parts_provider.dart'; @@ -16,7 +16,6 @@ import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; import 'package:test_sa/models/size_config.dart'; -import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart'; @@ -33,339 +32,372 @@ import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; class SparePartRequest extends StatefulWidget { static const String id = "/spare-part-request"; - final SparePartHelperModel ?model; - final CMDetailProvider provider; + final SparePartHelperModel? model; + final dynamic provider; + final bool fromCm; const SparePartRequest({ Key? key, required this.model, required this.provider, + this.fromCm = false, }) : super(key: key); @override _SparePartRequestState createState() => _SparePartRequestState(); } -class _SparePartRequestState extends State with TickerProviderStateMixin { +class _SparePartRequestState extends State { PartsProvider? _partsProvider; bool _isLoading = false; List _spareParts = []; + List _attachments = []; - List attachments = []; final GlobalKey _formKey = GlobalKey(); - final GlobalKey _scaffoldKey = GlobalKey(); - final TextEditingController _partQtyController = TextEditingController(); - final TextEditingController _installQtyController = TextEditingController(); - final TextEditingController _returnQtyController = TextEditingController(); - final TextEditingController _oracleNoController = TextEditingController(); - final TextEditingController _descriptionController = TextEditingController(); - Lookup statusLookup = Lookup.fromJson({"id": 5619, "name": "New", "value": 1}); - int? activityStatus; @override void initState() { super.initState(); _partsProvider = Provider.of(context, listen: false); - - // Initialize model with existing values or defaults - widget.provider.sparePartHelperModel = SparePartHelperModel( - id: widget.model?.id ?? 0, - workOrderId: widget.model?.workOrderId ?? widget.provider.currentWorkOrder?.data?.requestId, - sparePartAttachments: widget.model?.sparePartAttachments ?? [], - sparePart: widget.model?.sparePart ?? SparePart(), - quantity: widget.model?.quantity, - installQty: widget.model?.installQty, - returnQty: widget.model?.returnQty, - activityStatusId: widget.model?.activityStatusId ?? statusLookup.id, - activityStatus: widget.model?.activityStatus ?? statusLookup, - comment: widget.model?.comment ?? '', - ); - - _partQtyController.text = widget.provider.sparePartHelperModel?.quantity != null ? widget.provider.sparePartHelperModel!.quantity!.round().toString() : ''; - _installQtyController.text = widget.provider.sparePartHelperModel?.installQty != null ? widget.provider.sparePartHelperModel!.installQty!.round().toString() : ''; - _returnQtyController.text = widget.provider.sparePartHelperModel?.returnQty != null ? widget.provider.sparePartHelperModel!.returnQty!.round().toString() : ''; - _oracleNoController.text = widget.provider.sparePartHelperModel?.sparePart?.oracleCode != null ? widget.provider.sparePartHelperModel!.sparePart!.oracleCode! : ''; - _descriptionController.text = widget.provider.sparePartHelperModel?.comment != null ? widget.provider.sparePartHelperModel!.comment! : ''; - activityStatus = widget.provider.sparePartHelperModel?.activityStatus?.value; - - scheduleMicrotask(() async { - _isLoading = true; - attachments = widget.provider.sparePartHelperModel?.sparePartAttachments?.map((e) => GenericAttachmentModel(id: e.id!, name: e.name ?? '')).toList() ?? []; - setState(() {}); - _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: widget.provider.currentWorkOrder?.data?.asset?.id); - _isLoading = false; - setState(() {}); - }); + _initializeModel(); + _loadInitialData(); } - void restValues({required CMDetailProvider requestDetailProvider}) { - requestDetailProvider.sparePartHelperModel = SparePartHelperModel(id: 0, workOrderId: widget.provider.currentWorkOrder?.data?.requestId, sparePartAttachments: []); - _partQtyController.clear(); - _installQtyController.clear(); - _returnQtyController.clear(); - _oracleNoController.clear(); - _descriptionController.clear(); - attachments = []; + void _initializeModel() { + final bool isNewActivity = widget.model?.id == null || widget.model?.id == 0; + if (isNewActivity) { + widget.provider.sparePartHelperModel = SparePartHelperModel( + id: 0, + workOrderId: widget.fromCm ? widget.provider.currentWorkOrder?.data?.requestId : null, + pmVisitId: !widget.fromCm ? widget.provider.planPreventiveVisit?.id : null, + sparePartAttachments: [], + sparePart: SparePart(), + quantity: null, + installQty: null, + returnQty: null, + activityStatusId: statusLookup.id, + activityStatus: statusLookup, + comment: '', + ); + } else if (widget.provider.sparePartHelperModel == null || + widget.provider.sparePartHelperModel?.id != widget.model?.id) { + widget.provider.sparePartHelperModel = SparePartHelperModel( + id: widget.model?.id ?? 0, + workOrderId: widget.fromCm ? widget.model?.workOrderId ?? widget.provider.currentWorkOrder?.data?.requestId : null, + pmVisitId: !widget.fromCm ? widget.model?.pmVisitId : null, + sparePartAttachments: widget.model?.sparePartAttachments ?? [], + sparePart: widget.model?.sparePart ?? SparePart(), + quantity: widget.model?.quantity, + installQty: widget.model?.installQty, + returnQty: widget.model?.returnQty, + activityStatusId: widget.model?.activityStatusId ?? statusLookup.id, + activityStatus: widget.model?.activityStatus ?? statusLookup, + comment: widget.model?.comment ?? '', + ); + } + log('Initialized SparePartHelperModel: ${widget.provider.sparePartHelperModel?.toJson()}'); } - @override - void dispose() { - _partQtyController.dispose(); - _installQtyController.dispose(); - _returnQtyController.dispose(); - _oracleNoController.dispose(); - _descriptionController.dispose(); - super.dispose(); - } + Future _loadInitialData() async { + setState(() => _isLoading = true); + _spareParts = await _partsProvider!.getPartsListByDisplayName( + assetId: widget.fromCm + ? widget.provider.currentWorkOrder?.data?.asset?.id + : widget.provider.planPreventiveVisit.asset.id, + ); + final bool isNewActivity = widget.model?.id == null || widget.model?.id == 0; + _attachments = []; + if (!isNewActivity) { + try { + final attachmentsList = widget.model?.sparePartAttachments; + if (attachmentsList != null && attachmentsList.isNotEmpty) { + for (var item in attachmentsList) { + _attachments.add(GenericAttachmentModel( + id: item.id ?? 0, + name: item.name ?? '', + )); + } + } + log('Loaded ${_attachments.length} attachments for existing activity'); + } catch (e) { + log('Error loading attachments: $e'); + _attachments = []; + } + } else { + log('New activity - starting with empty attachments'); + } - bool _isLocalUrl(String url) { - if (url.isEmpty != false) return false; - return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); + if (mounted) setState(() => _isLoading = false); } @override Widget build(BuildContext context) { - bool showInstallAndReturnQty = activityStatus == 3 || activityStatus == 4; return Scaffold( - key: _scaffoldKey, appBar: DefaultAppBar(title: context.translation.sparePartRequest), - body: Consumer(builder: (context, CMDetailProvider requestDetailProvider, child) { - return Form( - key: _formKey, - child: Column( - children: [ - SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: IgnorePointer( - ignoring: widget.provider.isReadOnlyRequest, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Column( + body: ListenableBuilder( + listenable: widget.provider, + builder: (context, _) { + final provider = widget.provider; + final model = provider.sparePartHelperModel; + final bool showInstallAndReturnQty = (model?.activityStatus?.value == 3 || model?.activityStatus?.value == 4); + final bool isReadOnly = provider.isReadOnlyRequest ?? false; + + return Form( + key: _formKey, + child: Column( + children: [ + Expanded( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: IgnorePointer( + ignoring: isReadOnly, + child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - context.translation.sparePartDetails.heading5(context).custom(color: AppColor.textStyleColor(context)), - // 12.height, - // SingleItemDropDownMenu( - // context: context, - // height: 56.toScreenHeight, - // title: context.translation.activityStatus, - // showShadow: false, - // backgroundColor: AppColor.neutral100, - // initialValue: requestDetailProvider.sparePartHelperModel?.activityStatus, - // onSelect: (status) { - // requestDetailProvider.sparePartHelperModel?.activityStatus = status; - // }, - // ), - 12.height, - SingleItemDropDownMenu( - context: context, - title: context.translation.part, - staticData: _spareParts, - showShadow: false, - showAsBottomSheet: true, - loading: _isLoading, - initialValue: requestDetailProvider.sparePartHelperModel?.sparePart, - // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90, - onSelect: (part) async { - if (part != null) { - requestDetailProvider.sparePartHelperModel?.sparePart = part; - _oracleNoController.text = part.oracleCode ?? ''; - requestDetailProvider.updateSparePartHelperModel(widget.provider.sparePartHelperModel); - } - }, - ), - - if (requestDetailProvider.sparePartHelperModel?.sparePart?.id != null) ...[ - 12.height, - SizedBox( - height: 30.toScreenHeight, - child: Text('View Parts Availability', - style: TextStyle( - fontSize: 12.toScreenWidth, - fontWeight: FontWeight.w500, - fontStyle: FontStyle.normal, - color: AppColor.primary10, - decorationColor: AppColor.primary10, - decoration: TextDecoration.underline, - )).onPress( - () async { - requestDetailProvider.getStoreAvailabilityById(partId: requestDetailProvider.sparePartHelperModel?.sparePart?.id); - showModalBottomSheet( - context: context, - useSafeArea: true, - isScrollControlled: true, - isDismissible: true, - backgroundColor: AppColor.bottomSheetColor(context), - builder: (BuildContext context) => PartDetailBottomSheetSheet().bottomSheetContainer(context), - ); - }, - ), - ), - ], - 12.height, - AppTextFormField( - controller: _partQtyController, - labelText: context.translation.quantity, - textInputType: TextInputType.number, - labelStyle: AppTextStyles.textFieldLabelStyle, - // showWithoutDecoration: true, - // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90, - enable: requestDetailProvider.sparePartHelperModel?.sparePart?.id != null, - validator: (value) => value == null || value.isEmpty - ? context.translation.requiredField - : Validator.isNumeric(value) - ? null - : context.translation.onlyNumbers, - onChange: (value) { - requestDetailProvider.sparePartHelperModel?.quantity = num.tryParse(value ?? ""); - }, - onSaved: (text) { - requestDetailProvider.sparePartHelperModel?.quantity = num.tryParse(text ?? ""); - }, - ), - 12.height, - if (showInstallAndReturnQty) ...[ - AppTextFormField( - controller: _installQtyController, - labelText: context.translation.installedQty, - textInputType: const TextInputType.numberWithOptions(decimal: true), - labelStyle: AppTextStyles.textFieldLabelStyle, - // showWithoutDecoration: true, - // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90, - enable: requestDetailProvider.sparePartHelperModel?.sparePart?.id != null, - validator: (value) => value == null || value.isEmpty - ? context.translation.requiredField - : Validator.isNumeric(value) - ? null - : context.translation.onlyNumbers, - onChange: (value) { - requestDetailProvider.sparePartHelperModel?.installQty = num.tryParse(value ?? ""); - }, - onSaved: (text) { - requestDetailProvider.sparePartHelperModel?.installQty = num.tryParse(text ?? ""); - }, - ), - 12.height, - AppTextFormField( - controller: _returnQtyController, - labelText: context.translation.returnQty, - textInputType: TextInputType.number, - labelStyle: AppTextStyles.textFieldLabelStyle, - // showWithoutDecoration: true, - // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90, - enable: requestDetailProvider.sparePartHelperModel?.sparePart?.id != null, - validator: (value) => value == null || value.isEmpty - ? context.translation.requiredField - : Validator.isNumeric(value) - ? null - : context.translation.onlyNumbers, - onChange: (value) { - requestDetailProvider.sparePartHelperModel?.returnQty = num.tryParse(value ?? ""); - }, - onSaved: (text) { - requestDetailProvider.sparePartHelperModel?.returnQty = num.tryParse(text ?? ""); - }, - ), - 12.height, - ], - AppTextFormField( - labelStyle: AppTextStyles.textFieldLabelStyle, - controller: _oracleNoController, - labelText: context.translation.oracleNo, - textInputType: TextInputType.number, - // showWithoutDecoration: true, - backgroundColor: AppColor.disableFieldBackground(context), - enable: false, - ), - 12.height, - AppTextFormField( - initialValue: requestDetailProvider.sparePartHelperModel?.comment, - labelStyle: AppTextStyles.textFieldLabelStyle, - controller: _descriptionController, - showSpeechToText: true, - // backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral90, - labelText: "Engineer Comment", - alignLabelWithHint: true, - // showWithoutDecoration: true, - textInputType: TextInputType.multiline, - onChange: (value) { - requestDetailProvider.sparePartHelperModel?.comment = value; - }, - onSaved: (value) { - requestDetailProvider.sparePartHelperModel?.comment = value; - }, - ), - 12.height, - AttachmentPicker( - label: context.translation.attachQuotation, - attachment: attachments, - buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), - buttonColor: AppColor.primary10, + _buildFormContent( + context, + model, + provider, + showInstallAndReturnQty, ), ], - ).toShadowContainer(context), - 8.height, - ], + ), + ), ), ), - ).expanded, - if (!requestDetailProvider.isReadOnlyRequest) - FooterActionButton.footerContainer( - context: context, - child: AppFilledButton( - label: widget.provider.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity, - buttonColor: AppColor.green70, - onPressed: () { - _onSubmit(requestDetailProvider: requestDetailProvider); - }, - )), - ], + if (!isReadOnly) _buildSubmitButton(context, provider), + ], + ), + ); + }, + ), + ); + } + + Widget _buildFormContent( + BuildContext context, + SparePartHelperModel? model, + dynamic provider, + bool showInstallAndReturnQty, + ) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + context.translation.sparePartDetails.heading5(context).custom(color: AppColor.textStyleColor(context)), + 12.height, + SingleItemDropDownMenu( + context: context, + title: context.translation.part, + staticData: _spareParts, + showShadow: false, + showAsBottomSheet: true, + loading: _isLoading, + initialValue: model?.sparePart, + onSelect: (part) { + if (part != null) { + model?.sparePart = part; + provider.updateSparePartHelperModel(model); + } + }, + ), + if (model?.sparePart?.id != null) ...[ + 12.height, + SizedBox( + height: 30.toScreenHeight, + child: Text( + 'View Parts Availability', + style: TextStyle( + fontSize: 12.toScreenWidth, + fontWeight: FontWeight.w500, + color: AppColor.primary10, + decorationColor: AppColor.primary10, + decoration: TextDecoration.underline, + ), + ).onPress(() { + provider.getStoreAvailabilityById(partId: model?.sparePart?.id); + showModalBottomSheet( + context: context, + useSafeArea: true, + isScrollControlled: true, + isDismissible: true, + backgroundColor: AppColor.bottomSheetColor(context), + builder: (ctx) => PartDetailBottomSheetSheet(provider: provider).bottomSheetContainer(ctx), + ); + }), ), - ); - }), + ], + + 12.height, + AppTextFormField( + key: ValueKey('quantity_${model?.quantity}'), + initialValue: model?.quantity?.round().toString() ?? '', + labelText: context.translation.quantity, + textInputType: TextInputType.number, + labelStyle: AppTextStyles.textFieldLabelStyle, + enable: model?.sparePart?.id != null, + validator: (value) => value == null || value.isEmpty + ? context.translation.requiredField + : Validator.isNumeric(value) + ? null + : context.translation.onlyNumbers, + onChange: (value) { + model?.quantity = num.tryParse(value); + }, + onSaved: (text) { + model?.quantity = num.tryParse(text ?? ''); + }, + ), + + 12.height, + + if (showInstallAndReturnQty) ...[ + AppTextFormField( + key: ValueKey('installQty_${model?.installQty}'), + initialValue: model?.installQty?.round().toString() ?? '', + labelText: context.translation.installedQty, + textInputType: const TextInputType.numberWithOptions(decimal: true), + labelStyle: AppTextStyles.textFieldLabelStyle, + enable: model?.sparePart?.id != null, + validator: (value) => value == null || value.isEmpty + ? context.translation.requiredField + : Validator.isNumeric(value) + ? null + : context.translation.onlyNumbers, + onChange: (value) { + model?.installQty = num.tryParse(value); + }, + onSaved: (text) { + model?.installQty = num.tryParse(text ?? ''); + }, + ), + 12.height, + AppTextFormField( + key: ValueKey('returnQty_${model?.returnQty}'), + initialValue: model?.returnQty?.round().toString() ?? '', + labelText: context.translation.returnQty, + textInputType: TextInputType.number, + labelStyle: AppTextStyles.textFieldLabelStyle, + enable: model?.sparePart?.id != null, + validator: (value) => value == null || value.isEmpty + ? context.translation.requiredField + : Validator.isNumeric(value) + ? null + : context.translation.onlyNumbers, + onChange: (value) { + model?.returnQty = num.tryParse(value); + }, + onSaved: (text) { + model?.returnQty = num.tryParse(text ?? ''); + }, + ), + 12.height, + ], + AppTextFormField( + key: ValueKey('oracle_${model?.sparePart?.oracleCode}'), + initialValue: model?.sparePart?.oracleCode ?? '', + labelStyle: AppTextStyles.textFieldLabelStyle, + labelText: context.translation.oracleNo, + textInputType: TextInputType.number, + backgroundColor: AppColor.disableFieldBackground(context), + enable: false, + ), + + 12.height, + AppTextFormField( + key: ValueKey('comment_${model?.comment}'), + initialValue: model?.comment ?? '', + labelStyle: AppTextStyles.textFieldLabelStyle, + showSpeechToText: true, + labelText: "Engineer Comment", + alignLabelWithHint: true, + textInputType: TextInputType.multiline, + onChange: (value) { + model?.comment = value; + }, + onSaved: (value) { + model?.comment = value; + }, + ), + + 12.height, + AttachmentPicker( + label: context.translation.attachQuotation, + attachment: _attachments, + buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), + buttonColor: AppColor.primary10, + ), + ], + ).toShadowContainer(context); + } + + Widget _buildSubmitButton(BuildContext context, dynamic provider) { + return FooterActionButton.footerContainer( + context: context, + child: AppFilledButton( + label: provider.sparePartHelperModel?.id == 0 ? context.translation.addSparePartActivity : context.translation.updateSparePartActivity, + buttonColor: AppColor.green70, + onPressed: () => _onSubmit(provider), + ), ); } - _onSubmit({required CMDetailProvider requestDetailProvider}) async { - if (requestDetailProvider.sparePartHelperModel?.sparePart?.id == null) { + Future _onSubmit(dynamic provider) async { + final model = provider.sparePartHelperModel; + + if (model?.sparePart?.id == null) { "Please select spare part".showToast; return; - } else if (requestDetailProvider.sparePartHelperModel?.quantity == null) { + } else if (model?.quantity == null) { "Please enter quantity".showToast; return; } - requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.clear(); - - for (var item in attachments) { + model?.sparePartAttachments?.clear(); + for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.add( + + model?.sparePartAttachments?.add( SparePartAttachments(id: item.id, name: fileName), ); } - // Show loading dialog + // Show loading showDialog( context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading(), ); + + // Submit bool success = false; - if (widget.provider.sparePartHelperModel?.id == 0) { - success = await requestDetailProvider.createActivitySparePart(); + if (model?.id == 0) { + success = await provider.createActivitySparePart(); } else { - success = await requestDetailProvider.updateActivitySparePart(); + success = await provider.updateActivitySparePart(); } - if (mounted) Navigator.pop(context); + + if (mounted) Navigator.pop(context); // Close loading + if (success) { - requestDetailProvider.getWorkOrderById( - id: requestDetailProvider.currentWorkOrder!.data!.requestId!, - ); - if (mounted) Navigator.pop(context); - if (widget.provider.sparePartHelperModel?.id == 0) { - ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context); + if (widget.fromCm) { + provider.getWorkOrderById( + id: provider.currentWorkOrder!.data!.requestId!, + ); + } + else{ + provider.getPlanPreventiveVisitById( + int.tryParse(provider.planPreventiveVisit?.id ?? ''), + ); + } + + if (mounted) Navigator.pop(context); // Close form + + if (model?.id == 0) { + ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet( + context: context, + fromCm: widget.fromCm + ); const SizedBox().flushBar( context: context, title: context.translation.sparePartActivitySuccess, @@ -376,8 +408,14 @@ class _SparePartRequestState extends State with TickerProvider } } +/// Bottom Sheet for showing parts availability class PartDetailBottomSheetSheet extends StatelessWidget { - PartDetailBottomSheetSheet({Key? key}) : super(key: key); + final dynamic provider; + + const PartDetailBottomSheetSheet({ + Key? key, + required this.provider, + }) : super(key: key); @override Widget build(BuildContext context) { @@ -390,31 +428,61 @@ class PartDetailBottomSheetSheet extends StatelessWidget { children: [ 8.height, 'Parts Availability'.heading6(context).paddingOnly(top: 12, start: 12), - Consumer(builder: (context, requestDetailProvider, child) { - return requestDetailProvider.isLoading - ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center - : requestDetailProvider.storeAvailability.isEmpty - ? const NoDataFound().center - : ListView.separated( - padding: const EdgeInsets.only(top: 12), - itemCount: requestDetailProvider.storeAvailability.length, - separatorBuilder: (czt, index) => 12.height, - itemBuilder: (context, index) { - StoreAvailability model = requestDetailProvider.storeAvailability[index]; - return partAvailableQuantityCard(context: context, model: model); - }, - ); - }).expanded, + Expanded( + child: ListenableBuilder( + listenable: provider, + builder: (context, _) { + return provider.isLoading + ? CircularProgressIndicator( + color: AppColor.loadingColor(context), + ).center + : provider.storeAvailability.isEmpty + ? const NoDataFound().center + : ListView.separated( + padding: const EdgeInsets.only(top: 12), + itemCount: provider.storeAvailability.length, + separatorBuilder: (czt, index) => 12.height, + itemBuilder: (context, index) { + StoreAvailability model = provider.storeAvailability[index]; + return _partAvailableQuantityCard( + context: context, + model: model, + ); + }, + ); + }, + ), + ), ], ), ); } - Widget partAvailableQuantityCard({required StoreAvailability model, required BuildContext context}) { - return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - InfoTextWidget(label: "Site Name:".addTranslation, value: model.siteName ?? ''), - InfoTextWidget(label: "Store Name:".addTranslation, value: model.storeName ?? ''), - InfoTextWidget(label: "Available Quantity:".addTranslation, value: model.availablityQty != null ? model.availablityQty.toString() : ''), - ]).toShadowContainer(context, padding: 12, showShadow: false,); + Widget _partAvailableQuantityCard({ + required StoreAvailability model, + required BuildContext context, + }) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InfoTextWidget( + label: "Site Name:".addTranslation, + value: model.siteName ?? '', + ), + InfoTextWidget( + label: "Store Name:".addTranslation, + value: model.storeName ?? '', + ), + InfoTextWidget( + label: "Available Quantity:".addTranslation, + value: model.availablityQty?.toString() ?? '', + ), + ], + ).toShadowContainer( + context, + padding: 12, + showShadow: false, + ); } } diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index 4d61b068..fa749597 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -1,29 +1,24 @@ + import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/controllers/providers/api/ppm_provider.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/user_types.dart'; -import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart'; import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; -import 'package:test_sa/models/new_models/work_order_detail_model.dart'; +import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; -import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; -import 'package:test_sa/models/service_request/supplier_details.dart'; -import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; -import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/maintenance_request_main.dart'; import 'package:test_sa/modules/cm_module/views/forms/spare_part/spare_part_request.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/views/widgets/images/files_list.dart'; -import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; import 'package:test_sa/views/widgets/requests/request_status.dart'; @@ -50,9 +45,7 @@ class _PmActivitiesListViewState extends State { super.dispose(); } - List reOrderActivities = []; - - List activities = []; + List activities = []; bool disableNewActivity = false; @@ -60,15 +53,12 @@ class _PmActivitiesListViewState extends State { Widget build(BuildContext context) { UserProvider userProvider = Provider.of(context); return Scaffold( - appBar: const DefaultAppBar( - title: 'PM Activities', - // actions: [if (!showReorderView) IconButton(onPressed: () => activities.isEmpty ? null : setState(() => showReorderView = true), icon: const Icon(Icons.reorder_rounded))], + appBar: DefaultAppBar( + showHomeActionButton: true, + title: context.translation.activities, ), - - ///TODO replace with pm provider and data from pm provider - body: Consumer(builder: (context, CMDetailProvider requestDetailProvider, child) { - activities = requestDetailProvider.currentWorkOrder!.data!.activities; - requestDetailProvider.lastVisitedRequestActivityId = (activities.isNotEmpty ? activities.last.id : -1)!; + body: Consumer(builder: (context, PpmProvider pmProvider, child) { + activities = pmProvider.planPreventiveVisit?.activities ?? []; if (activities.isNotEmpty && (activities.last.activityStatus!.value == 14 || activities.last.activityStatus!.value == 19)) { disableNewActivity = true; } else { @@ -77,28 +67,42 @@ class _PmActivitiesListViewState extends State { return Column( children: [ - (activities.isEmpty && reOrderActivities.isEmpty) + (activities.isEmpty) ? NoDataFound(message: context.translation.noDataFound).center.expanded : ListView.separated( padding: const EdgeInsets.all(16), itemCount: activities.length, - separatorBuilder: (czt, index) => 16.height, + separatorBuilder: (czt, index) => 12.height, itemBuilder: (context, index) { - return sparePartActivityCard(requestDetailProvider: requestDetailProvider, userProvider: userProvider, context: context, activity: activities[index]); + return sparePartActivityCard(pmProvider: pmProvider, userProvider: userProvider, context: context, activity: activities[index]); }, ).expanded, if (userProvider.user!.type == UsersTypes.engineer && - (requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && requestDetailProvider.currentWorkOrder?.data?.status?.value != 3)) + (pmProvider.planPreventiveVisit?.visitStatus?.value != 5 && pmProvider.planPreventiveVisit?.visitStatus?.value != 3)) FooterActionButton.footerContainer( context: context, child: AppFilledButton( - label: 'Create New Spare Part', + label: context.translation.createNewActivity, maxWidth: true, buttonColor: AppColor.primary10, - loading: requestDetailProvider.isLoading, + loading: pmProvider.isLoading, disableButton: disableNewActivity, onPressed: () async { - // ServiceRequestBottomSheet.activityTypeBottomSheet(context: context); + final model = SparePartHelperModel( + id: 0, + pmVisitId: pmProvider.planPreventiveVisit?.id, + ); + + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => SparePartRequest( + model: model, + provider: pmProvider, + fromCm: false, + ), + ), + ); }, )) ], @@ -107,11 +111,11 @@ class _PmActivitiesListViewState extends State { ); } - Widget sparePartActivityCard({required CMDetailProvider requestDetailProvider, required UserProvider userProvider, required BuildContext context, required Activities activity}) { - bool showActionButtons = userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId && + Widget sparePartActivityCard({required PpmProvider pmProvider, required UserProvider userProvider, required BuildContext context, required PMSparePartActivityModel activity}) { + bool showActionButtons = userProvider.user!.userID == pmProvider.planPreventiveVisit?.assignedEmployee?.userId && userProvider.user!.type == UsersTypes.engineer && - requestDetailProvider.currentWorkOrder?.data?.status?.value != 5 && - requestDetailProvider.currentWorkOrder?.data?.status?.value != 3; + pmProvider.planPreventiveVisit?.visitStatus?.value != 5 && + pmProvider.planPreventiveVisit?.visitStatus?.value != 3; return Column( mainAxisSize: MainAxisSize.min, @@ -131,14 +135,14 @@ class _PmActivitiesListViewState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() { - editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); + editSparePartRequest(context: context, pmProvider: pmProvider, activity: activity); }), 12.width, "delete_icon".toSvgAsset(height: 24, width: 24).onPress(() async { showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); - int status = await requestDetailProvider.deleteActivitySparePart(id: activity.id!, workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!); + int status = await pmProvider.deleteActivitySparePart(id: activity.id!); if (status == 200) { - await requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!); + await pmProvider.getPlanPreventiveVisitById((int.tryParse(pmProvider.planPreventiveVisit?.id ?? '')) as int); Navigator.pop(context); } else { Navigator.pop(context); @@ -149,58 +153,61 @@ class _PmActivitiesListViewState extends State { ], ), 6.height, - InfoHeaderWidget(activity.activityType?.cleanupWhitespace.capitalizeFirstOfEach ?? '-'), InfoTextWidget( label: context.translation.partName, - value: activity.activitySparePart?.partCatalogItem?.partName, + value: activity.partCatalogItem?.partName, ), InfoTextWidget( label: context.translation.partNo, - value: activity.activitySparePart?.partCatalogItem?.partNumber, - showArrow: true, + value: activity.partCatalogItem?.partNumber, + ), + InfoTextWidget( + label: context.translation.oracleCode, + value: activity.partCatalogItem?.oracleCode, ), - if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[ - 6.height, + if (activity.comment?.isNotEmpty ?? false) ...[ const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), + InfoTextLabelWidget(label: activity.comment ?? ""), + ], + if (activity.activitySparePartPPMAttachments.isNotEmpty) ...[ + const Divider().defaultStyle(context), + FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name??'')??'').toList()), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { - ///Move to cost page .. - // if (showActionButtons) return; - // if (requestDetailProvider.isReadOnlyRequest) { - // editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); - // } else if (userProvider.user!.userID == requestDetailProvider.currentWorkOrder?.data?.assignedEmployee?.userId) { - // requestDetailProvider.isReadOnlyRequest = true; - // editSparePartRequest(context: context, requestDetailProvider: requestDetailProvider, activity: activity); - // } + if (showActionButtons) return; + if (pmProvider.isReadOnlyRequest) { + editSparePartRequest(context: context, pmProvider: pmProvider, activity: activity); + } else if (userProvider.user!.userID == pmProvider.planPreventiveVisit?.assignedEmployee?.userId) { + pmProvider.isReadOnlyRequest = true; + editSparePartRequest(context: context, pmProvider: pmProvider, activity: activity); + } }); } - void editSparePartRequest({required BuildContext context, required CMDetailProvider requestDetailProvider, required Activities activity}) async { - requestDetailProvider.sparePartHelperModel = SparePartHelperModel( + void editSparePartRequest({required BuildContext context, required PpmProvider pmProvider, required PMSparePartActivityModel activity}) async { + final model = SparePartHelperModel( id: activity.id, - workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId, - comment: activity.activitySparePart?.comment, - sparePartAttachments: activity.activitySparePart?.acitiySparePartAttachments ?? [], + pmVisitId: pmProvider.planPreventiveVisit?.id, + comment: activity.comment, + sparePartAttachments: activity.activitySparePartPPMAttachments, activityStatus: activity.activityStatus, sparePart: SparePart( - id: activity.activitySparePart?.partCatalogItem?.id, - partName: activity.activitySparePart?.partCatalogItem?.partName, - partNo: activity.activitySparePart?.partCatalogItem?.partNumber, - oracleCode: activity.activitySparePart?.partCatalogItem?.oracleCode), - quantity: activity.activitySparePart?.quantity, - installQty: activity.activitySparePart?.installQty, - returnQty: activity.activitySparePart?.returnQty, + id: activity.partCatalogItem?.id, + partName: activity.partCatalogItem?.partName, + partNo: activity.partCatalogItem?.partNumber, + oracleCode: activity.partCatalogItem?.oracleCode, + ), + quantity: activity.quantity, + installQty: activity.installQty, + returnQty: activity.returnQty, activityStatusId: activity.activityStatus?.id, ); - - requestDetailProvider.updateSparePartHelperModel(requestDetailProvider.sparePartHelperModel); - Navigator.of(context).push(MaterialPageRoute( builder: (_) => SparePartRequest( - model: requestDetailProvider.sparePartHelperModel, - provider: requestDetailProvider, + model: model, + provider: pmProvider, + fromCm: false, // This is PM, not CM ), )); } diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart b/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart deleted file mode 100644 index 24cd885b..00000000 --- a/lib/modules/pm_module/ppm_wo/activities/pm_cost_detail_page.dart +++ /dev/null @@ -1,127 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:provider/provider.dart'; -import 'package:test_sa/controllers/api_routes/urls.dart'; -import 'package:test_sa/controllers/providers/api/user_provider.dart'; -import 'package:test_sa/controllers/providers/settings/setting_provider.dart'; -import 'package:test_sa/extensions/context_extension.dart'; -import 'package:test_sa/extensions/int_extensions.dart'; -import 'package:test_sa/extensions/string_extensions.dart'; -import 'package:test_sa/extensions/text_extensions.dart'; -import 'package:test_sa/extensions/widget_extensions.dart'; -import 'package:test_sa/models/enums/user_types.dart'; -import 'package:test_sa/models/enums/work_order_next_step.dart'; -import 'package:test_sa/models/generic_attachment_model.dart'; -import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; -import 'package:test_sa/models/new_models/work_order_detail_model.dart'; -import 'package:test_sa/modules/cm_module/cm_detail_provider.dart'; -import 'package:test_sa/modules/cm_module/views/forms/asset_retired/asset_retired.dart'; -import 'package:test_sa/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart'; -import 'package:test_sa/new_views/app_style/app_color.dart'; -import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; -import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart'; -import 'package:test_sa/views/widgets/images/files_list.dart'; -import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; -import 'package:test_sa/views/widgets/item_views/info_date_widget.dart'; -import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; -import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; -import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; -import 'package:test_sa/views/widgets/requests/request_status.dart'; -import 'package:test_sa/views/widgets/sound/sound_player.dart'; - -class PmCostDetailsView extends StatefulWidget { - PmCostDetailsView({Key? key}) : super(key: key); - - @override - State createState() => _PmCostDetailsViewState(); -} - -class _PmCostDetailsViewState extends State { - @override - void initState() { - super.initState(); - } - - @override - Widget build(BuildContext context) { - UserProvider userProvider = Provider.of(context, listen: false); - - ///TODO: replace with pm provider and data from provider and remove the extra widgets as well. - return Consumer(builder: (pContext, requestProvider, _) { - bool showCostCard = context.userProvider.user!.type == UsersTypes.engineer && - !requestProvider.isReadOnlyRequest && - requestProvider.currentWorkOrder?.data?.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity; - - return requestProvider.isLoading - ? CircularProgressIndicator(color: AppColor.loadingColor(context)).center - : requestProvider.currentWorkOrder == null - ? const NoDataFound() - : Column( - children: [ - SingleChildScrollView( - padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (showCostCard) ...[ - 16.height, - costCard(context, requestProvider), - ], - ], - ), - ).expanded, - ], - ); - }); - } - - Widget costCard(BuildContext context, CMDetailProvider provider) { - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - children: [ - InfoHeader16Widget("Cost"), - const Spacer(), - if (!provider.isReadOnlyRequest) - - ///TODO replace with exact provider and data from provider and remove the extra widgets as well. - "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async { - WorkOrderData currentWorkOrderData = provider.currentWorkOrder!.data!; - provider.workOrderCostModel = WorkOrderCostModel( - workOrderId: currentWorkOrderData.requestId, - labourCost: currentWorkOrderData.labourCost, - sparePartCost: currentWorkOrderData.sparePartCost, - travelCost: currentWorkOrderData.travelCost, - qAmount: currentWorkOrderData.qAmount, - prNo: currentWorkOrderData.prNo, - poNo: currentWorkOrderData.poNo, - mrNo: currentWorkOrderData.mrNo, - exchangeCost: currentWorkOrderData.exchangeCost, - ); - provider.refreshTimer = false; - await Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CostDetailFormScreen( - isEdit: true, - model: provider.workOrderCostModel, - provider: provider, - ))); - provider.refreshTimer = true; - }), - ], - ), - InfoTextWidget(label: 'Spare Part Cost'.addTranslation, value: provider.currentWorkOrder?.data?.sparePartCost?.toString() ?? '-'), - InfoTextWidget(label: 'Labor Cost'.addTranslation, value: provider.currentWorkOrder?.data?.labourCost?.toString() ?? '-'), - InfoTextWidget(label: 'Travel Cost'.addTranslation, value: provider.currentWorkOrder?.data?.travelCost?.toString() ?? '-'), - InfoTextWidget(label: 'Quot Amount'.addTranslation, value: provider.currentWorkOrder?.data?.qAmount?.toString() ?? '-'), - InfoTextWidget(label: 'PR No'.addTranslation, value: provider.currentWorkOrder?.data?.prNo?.toString() ?? '-'), - InfoTextWidget(label: 'PO No'.addTranslation, value: provider.currentWorkOrder?.data?.poNo?.toString() ?? '-'), - InfoTextWidget(label: 'MR No'.addTranslation, value: provider.currentWorkOrder?.data?.mrNo?.toString() ?? '-'), - InfoTextWidget(label: 'Exchange Cost'.addTranslation, value: provider.currentWorkOrder?.data?.exchangeCost?.toString() ?? '-'), - ], - ).toShadowContainer(context); - } -} diff --git a/lib/modules/pm_module/ppm_wo/ppm_details_page.dart b/lib/modules/pm_module/ppm_wo/ppm_details_page.dart index 84bac35f..ffcc3679 100644 --- a/lib/modules/pm_module/ppm_wo/ppm_details_page.dart +++ b/lib/modules/pm_module/ppm_wo/ppm_details_page.dart @@ -117,7 +117,7 @@ class _PpmDetailsPageState extends State { ], ).toShadowContainer(context), ).expanded, - if (userProvider!.user!.type == UsersTypes.engineer && (!ppmProvider.isReadOnly)) ...[ + // if (userProvider!.user!.type == UsersTypes.engineer && (!ppmProvider.isReadOnly)) ...[ FooterActionButton.footerContainer( child: Column( children: [ @@ -126,22 +126,14 @@ class _PpmDetailsPageState extends State { await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdatePpm(ppm: null, planPreventiveVisit: planPreventiveVisit))); getVisitData(); }, - label: context.translation.updateWorkOrder, - ), - 12.height, - AppFilledButton( - onPressed: () async { - await Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); - getVisitData(); - }, - buttonColor: AppColor.neutral50, - label: context.translation.activities, + label: userProvider!.user!.type == UsersTypes.engineer && (!ppmProvider.isReadOnly)? context.translation.updateWorkOrder:context.translation.viewDetails, ), + ], ), context: context, ) - ] + // ] ]) : const Center(child: NoDataFound()); }), diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart index a61a8efd..e431d5de 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart @@ -14,6 +14,7 @@ import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model import 'package:test_sa/models/ppm/ppm.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; @@ -94,27 +95,36 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { @override void initState() { + super.initState(); ppmProvider = Provider.of(context, listen: false); _planPreventiveVisit = widget.planPreventiveVisit; - // WidgetsBinding.instance.addPostFrameCallback((_) { - initTabs(_planPreventiveVisit.typeOfService); - // }); - super.initState(); + int initialTabs = (_planPreventiveVisit.typeOfService?.value == 2) ? 4 : 3; + _tabController = TabController(length: initialTabs, vsync: this); + WidgetsBinding.instance.addPostFrameCallback((_) { + ppmProvider.totalTabs = initialTabs; + }); } + void initTabs(typeOfService) { if (typeOfService == null) { return; } - if (typeOfService?.value == 2) { - ppmProvider.totalTabs = 4; - } else { - ppmProvider.totalTabs = 3; + + int newTabCount = (typeOfService?.value == 2) ? 4 : 3; + + // Only recreate TabController if tab count has changed + if (_tabController?.length != newTabCount) { + _tabController?.dispose(); + _tabController = TabController(length: newTabCount, vsync: this); + + // Update provider safely after current build + WidgetsBinding.instance.addPostFrameCallback((_) { + ppmProvider.totalTabs = newTabCount; + }); } - _tabController?.dispose; - _tabController = TabController(length: ppmProvider.totalTabs, vsync: this); } int tabIndex = 0; @@ -208,70 +218,84 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { ).expanded, FooterActionButton.footerContainer( context: context, - child: Row( + child: Column( children: [ - if (tabIndex == 1) ...[ - AppFilledButton( - buttonColor: _tabController!.index == 0 ? null : AppColor.background(context), - // buttonColor: _tabController!.index == 0 ? null : AppColor.background(context), - textColor: _tabController!.index == 0 ? null : AppColor.blueStatus(context), - showBorder: true, - disableButton: _tabController!.index == 0, - onPressed: () { - if (_tabController!.index == 0) { - return; - } - _tabController?.animateTo(_tabController!.index - 1); - setState(() {}); - return; - }, - label: context.translation.back, - ).expanded, - 8.width, - ], - if (!ppmProvider.isReadOnly) ...[ - AppFilledButton( - // buttonColor: AppColor.white60, - // textColor: AppColor.neutral50, - buttonColor: context.isDark ? AppColor.neutral50 : AppColor.white60, - textColor: context.isDark ? Colors.white : AppColor.neutral50, - onPressed: () { - _onSubmit(status: 0); - }, - label: context.translation.save, - ).expanded, - 8.width, - AppFilledButton( - onPressed: () { - if (tabIndex == 0) { - _onSubmit(status: 1); - return; - } - if (ppmProvider.totalTabs == _tabController!.index + 1) { - _onSubmit(status: 1); - } else { - _tabController?.animateTo(_tabController!.index + 1); - setState(() {}); - } - }, - label: tabIndex == 0 ? "Complete".addTranslation : ((ppmProvider.totalTabs == _tabController!.index + 1) ? "Complete".addTranslation : context.translation.next), - ).expanded, - ] else ...[ - Visibility( - visible: tabIndex != 0, - child: AppFilledButton( - onPressed: () { - if (ppmProvider.totalTabs == _tabController!.index + 1) { - Navigator.pop(context); + Row( + children: [ + if (tabIndex == 1) ...[ + AppFilledButton( + buttonColor: _tabController!.index == 0 ? null : AppColor.background(context), + // buttonColor: _tabController!.index == 0 ? null : AppColor.background(context), + textColor: _tabController!.index == 0 ? null : AppColor.blueStatus(context), + showBorder: true, + disableButton: _tabController!.index == 0, + onPressed: () { + if (_tabController!.index == 0) { + return; + } + _tabController?.animateTo(_tabController!.index - 1); + setState(() {}); return; - } - _tabController?.animateTo(_tabController!.index + 1); - setState(() {}); - }, - label: ppmProvider.totalTabs == _tabController!.index + 1 ? context.translation.close : context.translation.next, - ).expanded, - ), - ] + }, + label: context.translation.back, + ).expanded, + 8.width, + ], + if (!ppmProvider.isReadOnly) ...[ + AppFilledButton( + // buttonColor: AppColor.white60, + // textColor: AppColor.neutral50, + buttonColor: context.isDark ? AppColor.neutral50 : AppColor.white60, + textColor: context.isDark ? Colors.white : AppColor.neutral50, + onPressed: () { + _onSubmit(status: 0); + }, + label: context.translation.save, + ).expanded, + 8.width, + AppFilledButton( + onPressed: () { + if (tabIndex == 0) { + _onSubmit(status: 1); + return; + } + if (ppmProvider.totalTabs == _tabController!.index + 1) { + _onSubmit(status: 1); + } else { + _tabController?.animateTo(_tabController!.index + 1); + setState(() {}); + } + }, + label: tabIndex == 0 ? "Complete".addTranslation : ((ppmProvider.totalTabs == _tabController!.index + 1) ? "Complete".addTranslation : context.translation.next), + ).expanded, + ] else ...[ + Visibility( + visible: tabIndex != 0, + child: AppFilledButton( + onPressed: () { + if (ppmProvider.totalTabs == _tabController!.index + 1) { + Navigator.pop(context); + return; + } + _tabController?.animateTo(_tabController!.index + 1); + setState(() {}); + }, + label: ppmProvider.totalTabs == _tabController!.index + 1 ? context.translation.close : context.translation.next, + ).expanded, + ), + ] + ], + ), + + 12.height, + AppFilledButton( + onPressed: () async { + Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); + // getVisitData(); + }, + buttonColor: AppColor.neutral50, + label: context.translation.activities, + ), ], ), ), diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart index 55170e3b..91eafc9d 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart @@ -13,6 +13,7 @@ import 'package:test_sa/models/device/asset.dart'; import 'package:test_sa/models/device/model_definition.dart'; import 'package:test_sa/models/device/supplier.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; import 'package:test_sa/models/new_models/department.dart'; @@ -21,6 +22,7 @@ import 'package:test_sa/models/new_models/room_model.dart'; import 'package:test_sa/models/new_models/site.dart'; import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; +import 'package:test_sa/modules/cm_module/views/forms/cost/cost_detail_form_screen.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart'; @@ -357,6 +359,8 @@ class _WoInfoFormState extends State { ), ], ).toShadowContainer(context), + 16.height, + costCard(context, ppmProvider), ], ), ), @@ -454,6 +458,79 @@ class _WoInfoFormState extends State { ); } + Widget costCard(BuildContext context, PpmProvider provider) { + ///Need to update this when actual flow decided... + PlanPreventiveVisit? model = provider.planPreventiveVisit; + final costModel = WorkOrderCostModel( + workOrderId: int.tryParse(model?.id ?? ''), + labourCost: model?.labourCost, + sparePartCost: model?.sparePartCost, + travelCost: model?.travelCost, + qAmount: model?.qAmount, + prNo: model?.prNo, + poNo: model?.poNo, + mrNo: model?.mrNo, + exchangeCost: model?.exchangeCost, + ); + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + InfoHeader16Widget("Cost"), + const Spacer(), + if (!provider.isReadOnlyRequest) + "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async { + provider.workOrderCostModel = costModel; + await Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CostDetailFormScreen( + model: provider.workOrderCostModel, + provider: provider, + ), + ), + ); + }), + ], + ), + InfoTextWidget( + label: 'Spare Part Cost'.addTranslation, + value: costModel.sparePartCost?.toString() ?? '-', + ), + InfoTextWidget( + label: 'Labor Cost'.addTranslation, + value: costModel.labourCost?.toString() ?? '-', + ), + InfoTextWidget( + label: 'Travel Cost'.addTranslation, + value: costModel.travelCost?.toString() ?? '-', + ), + InfoTextWidget( + label: 'Quot Amount'.addTranslation, + value: costModel.qAmount?.toString() ?? '-', + ), + InfoTextWidget( + label: 'PR No'.addTranslation, + value: costModel.prNo?.toString() ?? '-', + ), + InfoTextWidget( + label: 'PO No'.addTranslation, + value: costModel.poNo?.toString() ?? '-', + ), + InfoTextWidget( + label: 'MR No'.addTranslation, + value: costModel.mrNo?.toString() ?? '-', + ), + InfoTextWidget( + label: 'Exchange Cost'.addTranslation, + value: costModel.exchangeCost?.toString() ?? '-', + ), + ], + ).toShadowContainer(context); + } + // String formatDuration1(int seconds) { // int hours = seconds ~/ 3600; // int minutes = (seconds % 3600) ~/ 60; From 75349c4724d785c19e49dc0dc899244c8af92984 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 11 Aug 2026 16:08:51 +0300 Subject: [PATCH 03/47] improvements --- .../plan_preventive_visit_model.dart | 1 - .../forms/spare_part/spare_part_request.dart | 63 +++++-------------- .../ppm_wo/update_ppm/update_ppm.dart | 10 +-- .../ppm_wo/update_ppm/wo_info_form.dart | 16 ++--- lib/views/widgets/timer/app_timer.dart | 4 +- 5 files changed, 25 insertions(+), 69 deletions(-) diff --git a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart index 87087c3b..1feb33d7 100644 --- a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart +++ b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart @@ -197,7 +197,6 @@ class PlanPreventiveVisit { }); } if (json['activitySparePartsPPM'] != null) { - log("activitySparePartsPPM: ${json['activitySparePartsPPM']}"); activities = []; json['activitySparePartsPPM'].forEach((v) { activities!.add(PMSparePartActivityModel.fromJson(v)); diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 2cc85ef4..f961f470 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -1,4 +1,3 @@ - import 'dart:convert'; import 'dart:developer'; import 'dart:io'; @@ -27,6 +26,7 @@ import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart'; import 'package:test_sa/providers/loading_list_notifier.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; @@ -80,8 +80,7 @@ class _SparePartRequestState extends State { activityStatus: statusLookup, comment: '', ); - } else if (widget.provider.sparePartHelperModel == null || - widget.provider.sparePartHelperModel?.id != widget.model?.id) { + } else if (widget.provider.sparePartHelperModel == null || widget.provider.sparePartHelperModel?.id != widget.model?.id) { widget.provider.sparePartHelperModel = SparePartHelperModel( id: widget.model?.id ?? 0, workOrderId: widget.fromCm ? widget.model?.workOrderId ?? widget.provider.currentWorkOrder?.data?.requestId : null, @@ -102,9 +101,7 @@ class _SparePartRequestState extends State { Future _loadInitialData() async { setState(() => _isLoading = true); _spareParts = await _partsProvider!.getPartsListByDisplayName( - assetId: widget.fromCm - ? widget.provider.currentWorkOrder?.data?.asset?.id - : widget.provider.planPreventiveVisit.asset.id, + assetId: widget.fromCm ? widget.provider.currentWorkOrder?.data?.asset?.id : widget.provider.planPreventiveVisit.asset.id, ); final bool isNewActivity = widget.model?.id == null || widget.model?.id == 0; _attachments = []; @@ -183,9 +180,9 @@ class _SparePartRequestState extends State { ) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: 12, children: [ - context.translation.sparePartDetails.heading5(context).custom(color: AppColor.textStyleColor(context)), - 12.height, + InfoHeader16Widget(context.translation.sparePartDetails), SingleItemDropDownMenu( context: context, title: context.translation.part, @@ -202,9 +199,8 @@ class _SparePartRequestState extends State { }, ), if (model?.sparePart?.id != null) ...[ - 12.height, SizedBox( - height: 30.toScreenHeight, + // height: 30.toScreenHeight, child: Text( 'View Parts Availability', style: TextStyle( @@ -227,8 +223,6 @@ class _SparePartRequestState extends State { }), ), ], - - 12.height, AppTextFormField( key: ValueKey('quantity_${model?.quantity}'), initialValue: model?.quantity?.round().toString() ?? '', @@ -248,9 +242,6 @@ class _SparePartRequestState extends State { model?.quantity = num.tryParse(text ?? ''); }, ), - - 12.height, - if (showInstallAndReturnQty) ...[ AppTextFormField( key: ValueKey('installQty_${model?.installQty}'), @@ -271,7 +262,6 @@ class _SparePartRequestState extends State { model?.installQty = num.tryParse(text ?? ''); }, ), - 12.height, AppTextFormField( key: ValueKey('returnQty_${model?.returnQty}'), initialValue: model?.returnQty?.round().toString() ?? '', @@ -291,7 +281,6 @@ class _SparePartRequestState extends State { model?.returnQty = num.tryParse(text ?? ''); }, ), - 12.height, ], AppTextFormField( key: ValueKey('oracle_${model?.sparePart?.oracleCode}'), @@ -302,8 +291,6 @@ class _SparePartRequestState extends State { backgroundColor: AppColor.disableFieldBackground(context), enable: false, ), - - 12.height, AppTextFormField( key: ValueKey('comment_${model?.comment}'), initialValue: model?.comment ?? '', @@ -319,8 +306,6 @@ class _SparePartRequestState extends State { model?.comment = value; }, ), - - 12.height, AttachmentPicker( label: context.translation.attachQuotation, attachment: _attachments, @@ -384,20 +369,16 @@ class _SparePartRequestState extends State { provider.getWorkOrderById( id: provider.currentWorkOrder!.data!.requestId!, ); - } - else{ + } else { provider.getPlanPreventiveVisitById( - int.tryParse(provider.planPreventiveVisit?.id ?? ''), + int.tryParse(provider.planPreventiveVisit?.id ?? ''), ); } if (mounted) Navigator.pop(context); // Close form if (model?.id == 0) { - ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet( - context: context, - fromCm: widget.fromCm - ); + ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context, fromCm: widget.fromCm); const SizedBox().flushBar( context: context, title: context.translation.sparePartActivitySuccess, @@ -426,8 +407,8 @@ class PartDetailBottomSheetSheet extends StatelessWidget { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - 8.height, - 'Parts Availability'.heading6(context).paddingOnly(top: 12, start: 12), + 12.height, + 'Parts Availability'.heading4(context), Expanded( child: ListenableBuilder( listenable: provider, @@ -444,10 +425,7 @@ class PartDetailBottomSheetSheet extends StatelessWidget { separatorBuilder: (czt, index) => 12.height, itemBuilder: (context, index) { StoreAvailability model = provider.storeAvailability[index]; - return _partAvailableQuantityCard( - context: context, - model: model, - ); + return _partAvailableQuantityCard(context: context, model: model); }, ); }, @@ -458,31 +436,24 @@ class PartDetailBottomSheetSheet extends StatelessWidget { ); } - Widget _partAvailableQuantityCard({ - required StoreAvailability model, - required BuildContext context, - }) { + Widget _partAvailableQuantityCard({required StoreAvailability model, required BuildContext context}) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ InfoTextWidget( - label: "Site Name:".addTranslation, + label: "Site Name".addTranslation, value: model.siteName ?? '', ), InfoTextWidget( - label: "Store Name:".addTranslation, + label: "Store Name".addTranslation, value: model.storeName ?? '', ), InfoTextWidget( - label: "Available Quantity:".addTranslation, + label: "Available Quantity".addTranslation, value: model.availablityQty?.toString() ?? '', ), ], - ).toShadowContainer( - context, - padding: 12, - showShadow: false, - ); + ).toShadowContainer(context); } } diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart index e431d5de..f6be4486 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart @@ -45,7 +45,6 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { TabController? _tabController; late PpmProvider ppmProvider; - _onSubmit({required int status}) async { if (ppmProvider.validate()) { showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); @@ -105,9 +104,6 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { }); } - - - void initTabs(typeOfService) { if (typeOfService == null) { return; @@ -286,15 +282,13 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { ] ], ), - 12.height, AppFilledButton( onPressed: () async { - Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); - // getVisitData(); + Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); }, buttonColor: AppColor.neutral50, - label: context.translation.activities, + label: "View Spare Parts", ), ], ), diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart index 91eafc9d..3b25ec42 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart @@ -106,6 +106,7 @@ class _WoInfoFormState extends State { IgnorePointer( ignoring: ppmProvider.isReadOnly, child: Column( + spacing: 12, children: [ Column( mainAxisSize: MainAxisSize.min, @@ -147,7 +148,6 @@ class _WoInfoFormState extends State { // '${context.translation.executionTimeFrame}: ${widget.planPreventiveVisit.executionTimeFrame ?? ""} days'.bodyText2(context).custom(color: AppColor.neutral120), ], ).toShadowContainer(context), - 12.height, Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -221,9 +221,10 @@ class _WoInfoFormState extends State { // } // }, // ), - 8.height, + // 8.height,// Column( mainAxisAlignment: MainAxisAlignment.start, + spacing: 12, children: [ SingleItemDropDownMenu( context: context, @@ -238,7 +239,6 @@ class _WoInfoFormState extends State { } }, ), - 8.height, ADatePicker( label: context.translation.actualVisit, hideShadow: true, @@ -285,8 +285,6 @@ class _WoInfoFormState extends State { // } // }, // ), - - 8.height, SingleItemDropDownMenu( context: context, backgroundColor: AppColor.fieldBgColor(context), @@ -299,7 +297,6 @@ class _WoInfoFormState extends State { } }, ), - 8.height, SingleItemDropDownMenu( context: context, backgroundColor: AppColor.fieldBgColor(context), @@ -314,7 +311,6 @@ class _WoInfoFormState extends State { } }, ), - 8.height, SingleItemDropDownMenu( context: context, backgroundColor: AppColor.fieldBgColor(context), @@ -335,9 +331,7 @@ class _WoInfoFormState extends State { } }, ), - 8.height, _timerWidget(context, totalWorkingHours), - 8.height, AppTextFormField( labelText: context.translation.comment, backgroundColor: AppColor.fieldBgColor(context), @@ -349,7 +343,6 @@ class _WoInfoFormState extends State { widget.planPreventiveVisit.comments = value; }, ), - 16.height, AttachmentPicker( label: context.translation.attachments, attachment: ppmProvider.ppmPlanAttachments, @@ -359,7 +352,6 @@ class _WoInfoFormState extends State { ), ], ).toShadowContainer(context), - 16.height, costCard(context, ppmProvider), ], ), @@ -417,6 +409,7 @@ class _WoInfoFormState extends State { Widget _timerWidget(BuildContext context, double totalWorkingHours) { return Column( + spacing: 12, children: [ AppTimer( label: context.translation.workingHours, @@ -438,7 +431,6 @@ class _WoInfoFormState extends State { return true; }, ), - 11.height, if (totalWorkingHours > 0.0) ...[ WorkingTimeTile( timerList: timerList, diff --git a/lib/views/widgets/timer/app_timer.dart b/lib/views/widgets/timer/app_timer.dart index d33b0274..759a9c17 100644 --- a/lib/views/widgets/timer/app_timer.dart +++ b/lib/views/widgets/timer/app_timer.dart @@ -158,6 +158,7 @@ class _AppTimerState extends State { @override Widget build(BuildContext context) { return Column( + spacing: 12, children: [ if (canPickTime) ...[ Row( @@ -228,7 +229,6 @@ class _AppTimerState extends State { ], ), if (_tempPickerTimer != null) ...[ - 8.height, Row( children: [ Column( @@ -248,7 +248,7 @@ class _AppTimerState extends State { ], ).toShadowContainer(context) ], - 8.height, + // 8.height, ], if (widget.showTimer) Container( From c88b5770c9b7c8baccbc3ce5b20a2882134ec470 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 12 Aug 2026 10:11:17 +0300 Subject: [PATCH 04/47] improvements --- .../cm_module/views/forms/spare_part/spare_part_request.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index f961f470..cc5fb0a1 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -377,7 +377,7 @@ class _SparePartRequestState extends State { if (mounted) Navigator.pop(context); // Close form - if (model?.id == 0) { + if (model?.id == 0&&widget.fromCm) { ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context, fromCm: widget.fromCm); const SizedBox().flushBar( context: context, From 86aa0f67d85fac53b33ee8424b71abc9278de745 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 12 Aug 2026 11:34:06 +0300 Subject: [PATCH 05/47] improvements --- .../spare_part/activity_spare_part_model.dart | 2 ++ .../activities/pm_activities_list_view.dart | 21 +++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart index 548d47bb..79b8b162 100644 --- a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart +++ b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart @@ -73,6 +73,8 @@ class SparePartHelperModel { data['partCatalogItemId'] = sparePart?.id; data['quantity'] = quantity; data['comment'] = comment; + data['installQty'] = installQty; + data['returnQty'] = returnQty; if (sparePartAttachments.isNotEmpty) { data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toJson()).toList(); } diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index fa749597..bf8527e0 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -1,4 +1,3 @@ - import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; @@ -77,8 +76,7 @@ class _PmActivitiesListViewState extends State { return sparePartActivityCard(pmProvider: pmProvider, userProvider: userProvider, context: context, activity: activities[index]); }, ).expanded, - if (userProvider.user!.type == UsersTypes.engineer && - (pmProvider.planPreventiveVisit?.visitStatus?.value != 5 && pmProvider.planPreventiveVisit?.visitStatus?.value != 3)) + if (userProvider.user!.type == UsersTypes.engineer && (pmProvider.planPreventiveVisit?.visitStatus?.value != 5 && pmProvider.planPreventiveVisit?.visitStatus?.value != 3)) FooterActionButton.footerContainer( context: context, child: AppFilledButton( @@ -165,13 +163,28 @@ class _PmActivitiesListViewState extends State { label: context.translation.oracleCode, value: activity.partCatalogItem?.oracleCode, ), + if (activity.quantity != null && activity.quantity! > 0) + InfoTextWidget( + label: context.translation.quantity, + value: activity.quantity.toString(), + ), + if (activity.installQty != null && activity.installQty! > 0) + InfoTextWidget( + label: context.translation.installedQty, + value: activity.installQty.toString(), + ), + if (activity.returnQty != null && activity.returnQty! > 0) + InfoTextWidget( + label: context.translation.returnQty, + value: activity.returnQty.toString(), + ), if (activity.comment?.isNotEmpty ?? false) ...[ const Divider().defaultStyle(context), InfoTextLabelWidget(label: activity.comment ?? ""), ], if (activity.activitySparePartPPMAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name??'')??'').toList()), + FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { From d63f7d8939b3cba6c757c5c4449780480149b66c Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 17 Aug 2026 14:39:58 +0300 Subject: [PATCH 06/47] improvements --- .../forms/spare_part/spare_part_request.dart | 60 ++++++++++--------- .../ppm_wo/update_ppm/update_ppm.dart | 2 +- 2 files changed, 32 insertions(+), 30 deletions(-) diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index cc5fb0a1..63dcd3b7 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -377,7 +377,7 @@ class _SparePartRequestState extends State { if (mounted) Navigator.pop(context); // Close form - if (model?.id == 0&&widget.fromCm) { + if (model?.id == 0 && widget.fromCm) { ServiceRequestBottomSheet.addAnotherSpareRequestBottomSheet(context: context, fromCm: widget.fromCm); const SizedBox().flushBar( context: context, @@ -403,35 +403,37 @@ class PartDetailBottomSheetSheet extends StatelessWidget { return SizedBox( height: SizeConfig.screenHeight! / 2.2, width: SizeConfig.screenWidth, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - 12.height, - 'Parts Availability'.heading4(context), - Expanded( - child: ListenableBuilder( - listenable: provider, - builder: (context, _) { - return provider.isLoading - ? CircularProgressIndicator( - color: AppColor.loadingColor(context), - ).center - : provider.storeAvailability.isEmpty - ? const NoDataFound().center - : ListView.separated( - padding: const EdgeInsets.only(top: 12), - itemCount: provider.storeAvailability.length, - separatorBuilder: (czt, index) => 12.height, - itemBuilder: (context, index) { - StoreAvailability model = provider.storeAvailability[index]; - return _partAvailableQuantityCard(context: context, model: model); - }, - ); - }, + child: SafeArea( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + 12.height, + 'Parts Availability'.heading4(context), + Expanded( + child: ListenableBuilder( + listenable: provider, + builder: (context, _) { + return provider.isLoading + ? CircularProgressIndicator( + color: AppColor.loadingColor(context), + ).center + : provider.storeAvailability.isEmpty + ? const NoDataFound().center + : ListView.separated( + padding: const EdgeInsets.only(top: 12,bottom: 12), + itemCount: provider.storeAvailability.length, + separatorBuilder: (czt, index) => 12.height, + itemBuilder: (context, index) { + StoreAvailability model = provider.storeAvailability[index]; + return _partAvailableQuantityCard(context: context, model: model); + }, + ); + }, + ), ), - ), - ], + ], + ), ), ); } diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart index f6be4486..0e5a39ab 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart @@ -287,7 +287,7 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { onPressed: () async { Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); }, - buttonColor: AppColor.neutral50, + buttonColor: context.isDark ? AppColor.primary10 : AppColor.neutral50, label: "View Spare Parts", ), ], From 63d4c79a739a0e8b171e1aaf33a0710284a5bee2 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Mon, 17 Aug 2026 14:53:59 +0300 Subject: [PATCH 07/47] document library CR implementation --- lib/controllers/api_routes/urls.dart | 9 +- .../api/device_transfer_provider.dart | 1 + lib/helper/utils.dart | 70 +++ lib/main.dart | 1 + lib/models/device/asset_by_id_model.dart | 8 +- .../device/asset_transfer_attachment.dart | 69 ++- lib/models/device/device_transfer.dart | 40 +- lib/models/generic_attachment_model.dart | 264 +++++++- .../asset_retired/asset_retired_model.dart | 14 +- .../spare_part/activity_spare_part_model.dart | 22 +- .../workorder/work_order_helper_models.dart | 44 +- lib/models/new_models/gas_refill_model.dart | 76 +-- .../task_request/task_request_model.dart | 39 +- .../new_models/work_order_detail_model.dart | 15 +- .../plan_preventive_visit_model.dart | 567 +----------------- lib/models/ppm/ppm.dart | 9 +- lib/models/ppm/ppm_attachment.dart | 80 +-- .../service_request/search_work_order.dart | 24 +- .../service_request/service_report.dart | 10 +- .../service_request/supplier_details.dart | 93 +-- .../pages/attachment_view.dart | 2 + .../provider/attachment_type_provider.dart | 32 +- .../models/asset_inventory_model.dart | 46 +- .../pages/asset_inventory_form_view.dart | 3 +- lib/modules/cm_module/cm_detail_provider.dart | 6 +- lib/modules/cm_module/create_cm_request.dart | 5 +- .../components/activities_list_view.dart | 3 +- .../service_request_detail_view.dart | 29 +- .../forms/asset_retired/asset_retired.dart | 6 +- .../forms/spare_part/spare_part_request.dart | 7 +- .../demo_module/create_demo_request_page.dart | 52 +- .../demo_module/demo_detail_view_page.dart | 11 +- .../demo_document_lookup_provider.dart | 3 +- .../models/demo_attachment_model.dart | 62 +- .../demo_module/models/demo_form_model.dart | 34 +- .../models/demo_request_model.dart | 14 +- .../demo_module/update_demo-request_view.dart | 57 +- .../create_incident_request_page.dart | 7 +- .../incident_attachment_model.dart | 48 +- .../incident_module/incident_data_model.dart | 9 +- .../incident_module/incident_detail_page.dart | 5 +- .../models/engineer_data_model.dart | 8 +- .../equipment_internal_audit_data_model.dart | 11 +- .../equipment_internal_audit_form_model.dart | 6 +- .../internal_audit_attachment_model.dart | 58 +- .../system_internal_audit_data_model.dart | 9 +- .../system_internal_audit_form_model.dart | 6 +- .../models/update_audit_form_model.dart | 8 +- .../create_equipment_internal_audit_form.dart | 9 +- .../equipment_internal_audit_detail_page.dart | 8 +- .../update_equipment_internal_audit_page.dart | 11 +- .../create_system_internal_audit_form.dart | 13 +- .../system_internal_audit_detail_page.dart | 8 +- .../update_system_internal_audit_page.dart | 8 +- .../models/loan_attachment_model.dart | 79 +-- .../loan_module/models/loan_form_model.dart | 79 +-- .../loan_installation_pullout_form_model.dart | 22 +- .../models/loan_request_model.dart | 13 +- .../pages/create_loan_request_page.dart | 2 +- .../pages/installation_form_view.dart | 2 +- .../pages/installation_pullout_form_view.dart | 2 +- .../pages/intallation_details_view.dart | 2 +- .../pages/loan_equipment_detail_page.dart | 6 +- .../update_delivery_notes_page.dart | 6 +- .../update_medical_gas_inspection_page.dart | 1 - .../ppm_wo/update_ppm/update_ppm.dart | 7 +- .../ppm_wo/update_ppm/wo_info_form.dart | 3 +- .../create_device_transfer_request.dart | 5 +- .../device_transfer_details.dart | 6 +- .../update_device_transfer.dart | 10 +- .../gas_refill/gas_refill_details.dart | 9 +- .../gas_refill/gas_refill_request_form.dart | 3 +- .../gas_refill/update_gas_refill_request.dart | 5 +- .../tm_module/tasks/create_task_view.dart | 10 +- .../tasks/task_request_detail_view.dart | 3 +- .../tasks/update_task_request_view.dart | 11 +- .../traf_module/create_traf_request_page.dart | 3 +- .../traf_module/traf_request_detail_page.dart | 3 +- .../traf_module/traf_request_model.dart | 62 +- .../traf_module/update_traf_request_page.dart | 5 +- .../widgets/equipment/asset_detail_page.dart | 380 ++---------- .../widgets/equipment/asset_details_view.dart | 346 +++++++++++ .../asset_document_history_view.dart | 29 + .../equipment/asset_image_upload_page.dart | 2 + lib/views/widgets/images/files_list.dart | 26 +- .../widgets/images/multi_image_picker.dart | 248 ++++---- 86 files changed, 1641 insertions(+), 1808 deletions(-) create mode 100644 lib/views/widgets/equipment/asset_details_view.dart create mode 100644 lib/views/widgets/equipment/asset_document_history_view.dart diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 2028d9d7..0dd6626e 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -3,12 +3,12 @@ class URLs { static const String appReleaseBuildNumber = "50"; - static const host1 = "https://atomsm.hmg.com"; // production url + // static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + static const host1 = "https://atomsmuat.hmg.com"; // local UAT url - static final String _baseUrl = "$_host/mobile"; // host local UAT - // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis + // static final String _baseUrl = "$_host/mobile"; // host local UAT + static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation @@ -309,6 +309,7 @@ class URLs { static get genderLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=3065"; static get getDemoDocumentTypes => "$_baseUrl/Lookups/GetLookup?lookupEnum=4106"; + static get getAttachmentTypesLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=4021"; static get getClassificationTypeLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=450"; diff --git a/lib/controllers/providers/api/device_transfer_provider.dart b/lib/controllers/providers/api/device_transfer_provider.dart index 63468cc5..60afd310 100644 --- a/lib/controllers/providers/api/device_transfer_provider.dart +++ b/lib/controllers/providers/api/device_transfer_provider.dart @@ -153,6 +153,7 @@ class DeviceTransferProvider extends ChangeNotifier { Response response; try { showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); + log('payload: ${model.toCreateAssetTransferJson()}'); response = await ApiManager.instance.post(URLs.createAssetTransferRequest, body: model.toCreateAssetTransferJson()); stateCode = response.statusCode; if (response.statusCode >= 200 && response.statusCode < 300) { diff --git a/lib/helper/utils.dart b/lib/helper/utils.dart index 53496f1f..a2ab7f05 100644 --- a/lib/helper/utils.dart +++ b/lib/helper/utils.dart @@ -7,9 +7,12 @@ import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:google_api_availability/google_api_availability.dart'; import 'package:haptic_feedback/haptic_feedback.dart'; +import 'package:http/http.dart' as http; import 'package:nfc_manager/nfc_manager.dart'; import 'package:nfc_manager/nfc_manager_android.dart' show NfcAAndroid, NfcBAndroid; import 'package:nfc_manager/nfc_manager_ios.dart' show MiFareIos, Iso15693Ios; +import 'package:open_file/open_file.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; import 'package:test_sa/views/widgets/dialogs/confirm_dialog.dart'; @@ -193,6 +196,73 @@ class Utils { ); } + static Future downloadFile( + String url, { + bool autoOpen = true, + bool showToast = true, + String? authToken, + String? fileName, + }) async { + final client = http.Client(); + try { + if (showToast) { + Utils.showToast("Downloading file...", longDuration: false); + } + fileName ??= url.split('/').last.split('?').first; + if (!fileName.contains('.')) { + fileName = 'downloaded_file_${DateTime.now().millisecondsSinceEpoch}.jpg'; + } + final request = http.Request('GET', Uri.parse(url)); + if (authToken != null) { + request.headers['Authorization'] = 'Bearer $authToken'; + } + request.followRedirects = false; + final streamedResponse = await client.send(request); + File? file; + final dir = await getTemporaryDirectory(); + if (streamedResponse.statusCode == 302) { + final redirectUrl = streamedResponse.headers['location']; + if (redirectUrl == null) { + throw Exception('302 Redirect missing Location header'); + } + final headers = authToken != null ? {'Authorization': 'Bearer $authToken'} : {}; + final fileResponse = await http.get(Uri.parse(redirectUrl), headers: headers); + if (fileResponse.statusCode == 200) { + file = File('${dir.path}/$fileName'); + await file.writeAsBytes(fileResponse.bodyBytes); + } else { + throw Exception('Download from redirect failed: ${fileResponse.statusCode}'); + } + } + else if (streamedResponse.statusCode == 200) { + file = File('${dir.path}/$fileName'); + await file.writeAsBytes(await streamedResponse.stream.toBytes()); + } + else { + throw Exception('Download failed with status: ${streamedResponse.statusCode}'); + } + if (showToast) { + Utils.showToast("File downloaded successfully", longDuration: false); + } + if (autoOpen) { + await OpenFile.open(file.path); + } + return file; + } catch (ex) { + if (showToast) { + Utils.showToast("Download failed: ${ex.toString()}"); + } + return null; + } finally { + client.close(); + } + } + + static bool isLocalFile(String path) { + if (path.isEmpty) return false; + return path.startsWith("/") || path.startsWith("file://") || (path.length > 1 && path.substring(1).startsWith(':\\')); + } + // // static Widget getNoDataWidget(BuildContext context) { // return Column( diff --git a/lib/main.dart b/lib/main.dart index 50847d8f..d65c1255 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -249,6 +249,7 @@ class MyApp extends StatelessWidget { ChangeNotifierProvider(create: (_) => EndUserStatusLookupProvider(), lazy: true), ChangeNotifierProvider(create: (_) => EndUserRejectionReasonLookupProvider(), lazy: true), ChangeNotifierProvider(create: (_) => AttachmentTypeLookupProvider(), lazy: true), + ChangeNotifierProvider(create: (_) => AttachmentTypeLookupProviderLatest(), lazy: true), ChangeNotifierProvider(create: (_) => DemoPeriodLookupProvider(), lazy: true), ChangeNotifierProvider(create: (_) => DemoDocumentLookupProvider(), lazy: true), ChangeNotifierProvider(create: (_) => IncidentStatusLookupProvider(), lazy: true), diff --git a/lib/models/device/asset_by_id_model.dart b/lib/models/device/asset_by_id_model.dart index ab177b23..4c7dee4d 100644 --- a/lib/models/device/asset_by_id_model.dart +++ b/lib/models/device/asset_by_id_model.dart @@ -55,7 +55,7 @@ class AssetByIdModel { String? comment; bool? isEnabled; String? tagCode; - List? assetAttachments; + List? assetAttachments; String? retirementTypeName; String? retirementStatusName; String? retirementDate; @@ -198,9 +198,9 @@ class AssetByIdModel { isEnabled = json['isEnabled']; tagCode = json['tagCode']; if (json['assetAttachments'] != null) { - assetAttachments = []; + assetAttachments = []; json['assetAttachments'].forEach((v) { - assetAttachments!.add(AssetAttachment.fromJson(v)); + assetAttachments!.add(GenericAttachmentModel.fromAssetJson(v)); }); } retirementTypeName = json['retirementTypeName']; @@ -298,7 +298,7 @@ class AssetByIdModel { data['isEnabled'] = isEnabled; data['tagCode'] = tagCode; if (assetAttachments != null) { - data['assetAttachments'] = assetAttachments!.map((v) => v).toList(); + data['assetAttachments'] = assetAttachments!.map((v) => v.toAssetJson()).toList(); } data['retirementTypeName'] = retirementTypeName; data['retirementStatusName'] = retirementStatusName; diff --git a/lib/models/device/asset_transfer_attachment.dart b/lib/models/device/asset_transfer_attachment.dart index 7aed25f8..48186ed1 100644 --- a/lib/models/device/asset_transfer_attachment.dart +++ b/lib/models/device/asset_transfer_attachment.dart @@ -1,30 +1,39 @@ -class AssetTransferAttachment { - AssetTransferAttachment({ - this.id, - this.attachmentName, - }); - - AssetTransferAttachment.fromJson(dynamic json) { - id = json['id']; - attachmentName = json['attachmentName']; - } - - num? id; // Now nullable - String? attachmentName; // Now nullable - - AssetTransferAttachment copyWith({ - num? id, // Parameter is now nullable - String? attachmentName, // Parameter is now nullable - }) => - AssetTransferAttachment( - id: id ?? this.id, - attachmentName: attachmentName ?? this.attachmentName, - ); - - Map toJson() { - final map = {}; - map['id'] = id; - map['attachmentName'] = attachmentName; - return map; - } -} +//TODO: need to remove this class +// import 'package:test_sa/models/lookup.dart'; +// +// class AssetTransferAttachment { +// AssetTransferAttachment({ +// this.id, +// this.attachmentName, +// this.documentType, +// +// }); +// +// AssetTransferAttachment.fromJson(dynamic json) { +// id = json['id']; +// attachmentName = json['attachmentName']; +// } +// +// num? id; // Now nullable +// String? attachmentName; // Now nullable +// Lookup ? documentType; +// +// AssetTransferAttachment copyWith({ +// num? id, // Parameter is now nullable +// String? attachmentName, // Parameter is now nullable +// Lookup? documentType, // Parameter is now nullable +// }) => +// AssetTransferAttachment( +// id: id ?? this.id, +// attachmentName: attachmentName ?? this.attachmentName, +// documentType: documentType ?? this.documentType, +// ); +// +// Map toJson() { +// final map = {}; +// map['id'] = id; +// map['attachmentName'] = attachmentName; +// map['documentTypeId'] = documentType?.id; +// return map; +// } +// } diff --git a/lib/models/device/device_transfer.dart b/lib/models/device/device_transfer.dart index 67b7d465..ef7f96ff 100644 --- a/lib/models/device/device_transfer.dart +++ b/lib/models/device/device_transfer.dart @@ -1,4 +1,5 @@ import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/assistant_employee.dart'; import 'package:test_sa/models/new_models/work_order_detail_model.dart'; @@ -95,7 +96,6 @@ class DeviceTransfer { this.assistantEmployList, this.assetTransferAssistantEmployeesReceiver, this.assetTransferAssistantEmployeesSender, - this.statusValue, }); @@ -130,13 +130,13 @@ class DeviceTransfer { if (json['senderAttachments'] != null) { senderAttachments = []; json['senderAttachments'].forEach((v) { - senderAttachments!.add(AssetTransferAttachment.fromJson(v)); + senderAttachments!.add(GenericAttachmentModel.fromAssetTransferJson(v)); }); } if (json['assetTransferAttachments'] != null) { assetTransferAttachments = []; json['assetTransferAttachments'].forEach((v) { - assetTransferAttachments?.add(AssetTransferAttachment.fromJson(v)); + assetTransferAttachments?.add(GenericAttachmentModel.fromAssetTransferJson(v)); }); } if (json['assetTransferContactPersons'] != null) { @@ -198,7 +198,7 @@ class DeviceTransfer { if (json['receiverAttachments'] != null) { receiverAttachments = []; json['receiverAttachments'].forEach((v) { - receiverAttachments!.add(AssetTransferAttachment.fromJson(v)); + receiverAttachments!.add(GenericAttachmentModel.fromAssetTransferJson(v)); }); } assetNumber = json['assetNumber']; @@ -270,9 +270,9 @@ class DeviceTransfer { String? senderWorkingHours; String? senderTravelingHours; String? senderEngSignature; - List? senderAttachments; - List? attachments; - List? assetTransferAttachments; + List? senderAttachments; + List? attachments; + List? assetTransferAttachments; String? receiverAssignedEmployeeId; String? receiverAssignedEmployeeNumber; num? receiverMachineStatusId; @@ -283,7 +283,7 @@ class DeviceTransfer { String? receiverWorkingHours; String? receiverTravelingHours; String? receiverEngSignature; - List? receiverAttachments; + List? receiverAttachments; num? supplierId; String? supplierName; String? destSiteName; @@ -314,11 +314,11 @@ class DeviceTransfer { List? assetTransferEngineerTimers; List? timerModelList = []; List? assistantEmployees; - List? assetTransferAssistantEmployeesSender=[]; - List? assetTransferAssistantEmployeesReceiver=[]; + List? assetTransferAssistantEmployeesSender = []; + List? assetTransferAssistantEmployeesReceiver = []; List? assetTransferContactPersons; AssetTransferAssistantEmployees? modelAssistantEmployees; - List? assistantEmployList=[]; + List? assistantEmployList = []; TimerModel? tbsTimer = TimerModel(); TimerModel? deviceTimePicker; @@ -349,7 +349,7 @@ class DeviceTransfer { String? senderWorkingHours, String? senderTravelingHours, String? senderEngSignature, - List? senderAttachments, + List? senderAttachments, String? receiverAssignedEmployeeId, String? receiverAssignedEmployeeNumber, num? receiverMachineStatusId, @@ -359,7 +359,7 @@ class DeviceTransfer { String? receiverWorkingHours, String? receiverTravelingHours, String? receiverEngSignature, - List? receiverAttachments, + List? receiverAttachments, num? supplierId, String? supplierName, String? destSiteName, @@ -472,7 +472,7 @@ class DeviceTransfer { senderVisitTimers: senderVisitTimers ?? this.senderVisitTimers, receiverVisitTimers: receiverVisitTimers ?? this.receiverVisitTimers, tbsTimer: tbsTimer ?? this.tbsTimer, - assistantEmployList: assistantEmployList??this.assistantEmployList, + assistantEmployList: assistantEmployList ?? this.assistantEmployList, deviceTimePicker: deviceTimePicker ?? this.deviceTimePicker, manufacturerName: manufacturerName ?? this.manufacturerName); @@ -510,7 +510,7 @@ class DeviceTransfer { map['assetTransferReceiverTimers'] = receiverVisitTimers!.map((v) => v.toJson()).toList(); } if (senderAttachments != null) { - map['senderAttachments'] = senderAttachments!.map((v) => v.toJson()).toList(); + map['senderAttachments'] = senderAttachments!.map((v) => v.toAssetTransferJson()).toList(); } map['receiverAssignedEmployeeId'] = receiverAssignedEmployeeId; map['receiverAssignedEmployeeNumber'] = receiverAssignedEmployeeNumber; @@ -522,7 +522,7 @@ class DeviceTransfer { map['receiverTravelingHours'] = receiverTravelingHours; map['receiverEngSignature'] = receiverEngSignature; if (receiverAttachments != null) { - map['receiverAttachments'] = receiverAttachments!.map((v) => v.toJson()).toList(); + map['receiverAttachments'] = receiverAttachments?.map((v) => v.toAssetTransferJson() ?? {}).toList(); } map["supplierId"] = supplierId; map["supplierName"] = supplierName; @@ -571,7 +571,7 @@ class DeviceTransfer { map['destRoomId'] = destRoomId; map['comment'] = comment; if (attachments != null) { - map['attachments'] = attachments!.map((v) => v.toJson()).toList(); + map['attachments'] = attachments!.map((v) => v.toAssetTransferJson()).toList(); } return map; } @@ -586,7 +586,7 @@ class DeviceTransfer { map['assetTransferAssistantEmployees'] = modelAssistantEmployees; map['assetTransferEngineerTimers'] = assetTransferEngineerTimers; if (attachments != null) { - map['attachments'] = attachments!.map((v) => v.toJson()).toList(); + map['attachments'] = attachments!.map((v) => v.toAssetTransferJson()).toList(); } if (assetTransferEngineerTimers != null) { map['assetTransferEngineerTimers'] = assetTransferEngineerTimers!.map((v) => v.toJson()).toList(); @@ -634,7 +634,7 @@ class DeviceTransfer { map['senderTravelingHours'] = senderTravelingHours; map['senderEngSignature'] = senderEngSignature; if (senderAttachments != null) { - map['senderAttachments'] = senderAttachments!.map((v) => v.toJson()).toList(); + map['senderAttachments'] = senderAttachments!.map((v) => v.toAssetTransferJson()).toList(); } if (senderVisitTimers != null) { map['assetTransferSenderTimers'] = senderVisitTimers!.map((v) => v.toJson()).toList(); @@ -652,7 +652,7 @@ class DeviceTransfer { map['receiverTravelingHours'] = receiverTravelingHours; map['receiverEngSignature'] = receiverEngSignature; if (receiverAttachments != null) { - map['receiverAttachments'] = receiverAttachments!.map((v) => v.toJson()).toList(); + map['receiverAttachments'] = receiverAttachments!.map((v) => v.toAssetTransferJson() ?? {}).toList(); } return map; } diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 6ba126e1..6a6d552b 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -1,33 +1,287 @@ -import 'dart:io'; - import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/models/lookup.dart'; class GenericAttachmentModel { - GenericAttachmentModel({this.id, this.name, this.originalName, this.createdBy, this.documentTypeId}); + GenericAttachmentModel({ + this.id, + this.name, + this.originalName, + this.createdBy, + this.documentType, + this.attachmentDescription, + this.attachmentURL, + this.moduleReferenceId, + this.attachmentTypeId, + this.createdDate, + this.modifiedBy, + this.modifiedDate, + this.supplierId, + }); int? id; String? name; String? createdBy; String? originalName; - Lookup? documentTypeId; + Lookup? documentType; + String? attachmentDescription; + String? attachmentURL; + num? moduleReferenceId; + num? attachmentTypeId; + String? createdDate; + String? modifiedBy; + String? modifiedDate; + num? supplierId; GenericAttachmentModel.fromJson(Map json, {bool convertToLink = false}) { id = json['id']; - name = json['name'] ?? json['imageName']; + name = json['name'] ?? json['attachmentName'] ?? json['imageName']; createdBy = json['createdBy']; + documentType = json['documentType']; originalName = json['originalName'] ?? json['imageOriginalName']; + if (convertToLink) { name = URLs.getFileUrl(name); } } + GenericAttachmentModel.fromWorkOrderJson(Map json) { + id = json['id']; + name = json['name']; + createdBy = json['createdBy']; + } + + GenericAttachmentModel.fromLoanJson(Map json) { + id = json['id']?.toInt(); + name = json['attachmentName']; + attachmentDescription = json['attachmentDescription']; + documentType = json['documentType']; + moduleReferenceId = json['loanId']; + attachmentTypeId = json['loanAttachmentTypeId']; + } + + GenericAttachmentModel.fromLoanDetailJson(Map json) { + id = json['id']; + name = json['attachmentName']; + attachmentDescription = json['attachmentDescription']; + moduleReferenceId = json['loanId']; + attachmentTypeId = json['loanAttachmentTypeId']; + createdBy = json['createdBy']; + createdDate = json['createdDate']; + modifiedBy = json['modifiedBy']; + modifiedDate = json['modifiedDate']; + } + + GenericAttachmentModel.fromPpmJson(Map json) { + id = json['id']; + name = json['attachmentName'] ?? json['name']; + moduleReferenceId = json['visitId']; + attachmentURL = json['attachmentURL']; + } + GenericAttachmentModel.fromSupplierJson(Map json) { + id = json['id']; + name = json['attachmentName'] ?? json['name']; + supplierId = json['supplierId']; + moduleReferenceId = json['visitId']; + attachmentURL = json['attachmentURL']; + } + + GenericAttachmentModel.fromGasRefillJson(Map json) { + id = json['id']; + name = json['attachmentName']; + moduleReferenceId = json['gasRefillId']; + documentType = json['documentType']; + } + + GenericAttachmentModel.fromIncidentJson(Map json) { + id = json['id']; + name = json['attachmentName']; + moduleReferenceId = json['incidentId']; + attachmentDescription = json['attachmentDescription']; + } + + GenericAttachmentModel.fromAssetTransferJson(Map json) { + id = json['id']; + name = json['attachmentName']; + } + + GenericAttachmentModel.fromDemoJson(Map json) { + id = json['id']; + name = json['attachmentName']; + originalName = json['originalName']; + moduleReferenceId = json['demoRequestId']; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; + } + + GenericAttachmentModel.fromInternalAuditJson(Map json) { + id = json['id']; + name = (json['name'] != null && !json['name'].toString().startsWith('data:image/jpeg')) ? json['name'] : null; + originalName = json['originalName']; + createdBy = json['createdBy']; + documentType = json['documentType']; + } + + GenericAttachmentModel.fromPreventiveVisitJson(Map json) { + id = json['id']; + name = json['attachmentName']; + documentType = json['documentType']; + } + + GenericAttachmentModel.fromAssetJson(Map json) { + id = json['id']; + name = json['attachmentName']; + attachmentURL = json['attachmentURL']; + originalName = json['originalName']; + } + + GenericAttachmentModel.fromTrafJson(Map json) { + id = json['id']; + name = json['attachmentName']; + moduleReferenceId = json['trafId']; + documentType = json['documentType']; + } + + Map toJson() { final Map data = {}; data['id'] = id; data['name'] = name; data['createdBy'] = createdBy; data['originalName'] = originalName; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toWorkOrderJson() { + final Map data = {}; + data['id'] = id; + data['name'] = name; + data['createdBy'] = createdBy; + ///TODO need to keep same variable for document type in backend for all modules, currently it is different for different modules + if (documentType != null) { + data['attachmentTypeId'] = documentType?.id; + } + return data; + } + + Map toLoanJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['loanId'] = moduleReferenceId; + data['loanAttachmentTypeId'] = attachmentTypeId; + data['documentTypeId'] = documentType?.id; + data['attachmentDescription'] = attachmentDescription; + return data; + } + + Map toLoanDetailJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['loanId'] = moduleReferenceId; + data['loanAttachmentTypeId'] = attachmentTypeId; + data['attachmentDescription'] = attachmentDescription; + data['createdBy'] = createdBy; + data['createdDate'] = createdDate; + data['documentTypeId'] = documentType?.id; + + data['modifiedBy'] = modifiedBy; + data['modifiedDate'] = modifiedDate; + return data; + } +//TODO need to check where to use this need to verify with backend team. + Map toPpmJson() { + final Map data = {}; + data['id'] = id; + data['visitId'] = moduleReferenceId; + data['attachmentName'] = name; + data['documentTypeId'] = documentType?.id; + data['attachmentURL'] = attachmentURL; + return data; + } + + Map toGasRefillJson() { + final Map data = {}; + data['id'] = id; + data['gasRefillId'] = moduleReferenceId; + data['attachmentName'] = name; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toIncidentJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['incidentId'] = moduleReferenceId; + data['documentTypeId'] = documentType?.id; + data['attachmentDescription'] = attachmentDescription; + return data; + } + + Map toAssetTransferJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toDemoJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['demoRequestId'] = moduleReferenceId; + data['originalName'] = originalName; + if (documentType != null) { + data['documentTypeId'] = documentType?.id; + } + return data; + } + + Map toInternalAuditJson() { + final Map data = {}; + data['id'] = id; + data['name'] = name; + data['originalName'] = originalName; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toPreventiveVisitJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toAssetJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['attachmentURL'] = attachmentURL; + data['documentTypeId'] = documentType?.id; + data['originalName'] = originalName; + return data; + } + + Map toTrafJson() { + final Map data = {}; + data['id'] = id; + data['trafId'] = moduleReferenceId; + data['attachmentName'] = name; + data['documentTypeId'] = documentType?.id; + return data; + } + + Map toSupplierJson() { + final Map data = {}; + data['id'] = id; + data['supplierId'] = supplierId; + data['documentTypeId'] = documentType?.id; + data['attachmentName'] = name; + data['attachmentURL'] = attachmentURL; return data; } } diff --git a/lib/models/helper_data_models/asset_retired/asset_retired_model.dart b/lib/models/helper_data_models/asset_retired/asset_retired_model.dart index 172d816a..e7b80f2f 100644 --- a/lib/models/helper_data_models/asset_retired/asset_retired_model.dart +++ b/lib/models/helper_data_models/asset_retired/asset_retired_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; class AssetRetiredHelperModel { @@ -5,7 +6,7 @@ class AssetRetiredHelperModel { int? workOrderId; Lookup? retirmentReason; String? retirementComment; - List? + List? activityAssetToBeRetiredAttachments=[]; AssetRetiredHelperModel( @@ -30,14 +31,3 @@ class AssetRetiredHelperModel { } } -class ActivityAssetToBeRetiredAttachments { - int? id; - String? name; - ActivityAssetToBeRetiredAttachments({this.id, this.name}); - Map toJson() { - final Map data = {}; - data['id'] = id; - data['name'] = name; - return data; - } -} diff --git a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart index 1c51821f..74a1049a 100644 --- a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart +++ b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; @@ -12,7 +13,7 @@ class SparePartHelperModel { num? installQty; num? returnQty; String? comment; - List? sparePartAttachments; + List? sparePartAttachments; SparePartHelperModel({ this.id, @@ -42,27 +43,10 @@ class SparePartHelperModel { data['comment'] = comment; if (sparePartAttachments != null) { data['acitiySparePartAttachments'] = - sparePartAttachments!.map((v) => v.toJson()).toList(); + sparePartAttachments!.map((v) => v?.toJson() ?? {}).toList(); } return data; } } -class SparePartAttachments { - int? id; - String? name; - - SparePartAttachments({this.id, this.name}); - SparePartAttachments.fromJson(Map json) { - id = json['id']; - name = json['name']; - } - - Map toJson() { - final Map data = {}; - data['id'] = id; - data['name'] = name; - return data; - } -} \ No newline at end of file diff --git a/lib/models/helper_data_models/workorder/work_order_helper_models.dart b/lib/models/helper_data_models/workorder/work_order_helper_models.dart index b15924d6..21bf4ef9 100644 --- a/lib/models/helper_data_models/workorder/work_order_helper_models.dart +++ b/lib/models/helper_data_models/workorder/work_order_helper_models.dart @@ -1,4 +1,5 @@ import 'package:test_sa/models/fault_description.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import '../../new_models/work_order_detail_model.dart'; @@ -24,7 +25,7 @@ class WorkOrderHelperModel { int? problemDescriptionId; String? comments; String? voiceNote; - List? workOrderAttachments; + List? workOrderAttachments; WorkOrderHelperModel({this.assetId, this.equipmentStatusId, this.priorityId, this.problemDescriptionId, this.comments, this.voiceNote, this.workOrderAttachments}); @@ -37,42 +38,21 @@ class WorkOrderHelperModel { data['comments'] = comments; data['voiceNote'] = voiceNote; if (workOrderAttachments != null) { - data['workOrderAttachments'] = workOrderAttachments!.map((v) => v.toJson()).toList(); + data['workOrderAttachments'] = workOrderAttachments!.map((v) => v.toWorkOrderJson()).toList(); } return data; } - Map toUploadAttachmentJson(int? workOrderId, List? workOrderAttachments) { + Map toUploadAttachmentJson(int? workOrderId, List? workOrderAttachments) { final Map data = {}; data['workOrderId'] = workOrderId; if (workOrderAttachments != null) { - data['workOrderAttachments'] = workOrderAttachments!.map((v) => v.toJson()).toList(); + data['workOrderAttachments'] = workOrderAttachments.map((v) => v.toWorkOrderJson()).toList(); } return data; } } -class WorkOrderAttachments { - WorkOrderAttachments({this.id, this.name,this.createdBy}); - - int? id; - String? name; - String ?createdBy; - WorkOrderAttachments.fromJson(Map json) { - id = json['id']; - name = json['name']; - createdBy = json['createdBy']; - } - - Map toJson() { - final Map data = {}; - data['id'] = id; - data['name'] = name; - data['createdBy'] = createdBy; - return data; - } -} - class EngineerUpdateWorkOrderHelperModel { int? workOrderId; Lookup? equipmentStatus; @@ -173,9 +153,19 @@ class WorkOrderCostModel { String? mrNo; num? exchangeCost; - WorkOrderCostModel({this.workOrderId, this.sparePartCost, this.labourCost, this.travelCost, this.qAmount, this.poNo, this.prNo,this.mrNo,this.exchangeCost}); + WorkOrderCostModel({this.workOrderId, this.sparePartCost, this.labourCost, this.travelCost, this.qAmount, this.poNo, this.prNo, this.mrNo, this.exchangeCost}); Map toJson() { - return {'workOrderId': workOrderId, 'sparePartCost': sparePartCost, 'laborCost': labourCost, 'travelCost': travelCost, 'qAmount': qAmount, 'prNo': prNo, 'poNo': poNo,'mrNo':mrNo,'exchangeCost':exchangeCost}; + return { + 'workOrderId': workOrderId, + 'sparePartCost': sparePartCost, + 'laborCost': labourCost, + 'travelCost': travelCost, + 'qAmount': qAmount, + 'prNo': prNo, + 'poNo': poNo, + 'mrNo': mrNo, + 'exchangeCost': exchangeCost + }; } } diff --git a/lib/models/new_models/gas_refill_model.dart b/lib/models/new_models/gas_refill_model.dart index a50373df..da5400b7 100644 --- a/lib/models/new_models/gas_refill_model.dart +++ b/lib/models/new_models/gas_refill_model.dart @@ -3,6 +3,7 @@ import 'dart:typed_data'; import 'package:flutter/cupertino.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/assigned_employee.dart'; import 'package:test_sa/models/new_models/building.dart'; @@ -87,7 +88,7 @@ class GasRefillModel { TimerModel? gasRefillTimePicker; List? timerModelList = []; List? gasRefillTimers = []; - List? gasRefillAttachments; + List? gasRefillAttachments; List? gasRefillContactPerson; int? statusValue; @@ -115,9 +116,9 @@ class GasRefillModel { workingHours = json['gasRefillTimers'].fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item['endDate']).difference(DateTime.parse(item['startDate'])).inSeconds) ?? 0; } if (json['gasRefillAttachments'] != null) { - gasRefillAttachments = []; + gasRefillAttachments = []; json['gasRefillAttachments'].forEach((v) { - gasRefillAttachments!.add(GasRefillAttachments.fromJson(v)); + gasRefillAttachments!.add(GenericAttachmentModel.fromGasRefillJson(v)); }); } if (json['gasRefillContactPerson'] != null) { @@ -127,24 +128,6 @@ class GasRefillModel { }); } - // try { - // final DateTime? sd = DateTime.tryParse(startDate ?? ""); - // final DateTime? st = DateTime.tryParse(startTime ?? ""); - // final DateTime? ed = DateTime.tryParse(endDate ?? ""); - // final DateTime? et = DateTime.tryParse(endTime ?? ""); - // timer = TimerModel( - // startAt: st == null ? sd : sd?.add(Duration(hours: st.hour, minutes: st.minute, seconds: st.second)), // Handle potential null 'sd' - // endAt: et == null ? ed : ed?.add(Duration(hours: et.hour, minutes: et.minute, seconds: et.second)), // Handle potential null 'ed' - // ); - // if (timer!.endAt != null && timer!.startAt != null) { - // // Use '!' since timer could be null after initialization - // timer!.durationInSecond = (timer!.endAt!.difference(timer!.startAt!)).inSeconds; - // workingHours = (((timer!.durationInSecond ?? 0) / 60) / 60); - // } - // } catch (e) { - // print(e); - // } - engSignature = json['engSignature']; nurseSignature = json['nurseSignature']; site = json['site'] != null ? Site.fromJson(json['site']) : null; @@ -188,7 +171,7 @@ class GasRefillModel { map['comment'] = comment; if (gasRefillAttachments != null) { - map['gasRefillAttachments'] = gasRefillAttachments?.map((v) => v.toJson()).toList(); + map['gasRefillAttachments'] = gasRefillAttachments?.map((v) => v.toGasRefillJson() ?? {}).toList(); } //older code..... @@ -241,8 +224,8 @@ class GasRefillModel { if (gasRefillTimers != null) { map['gasRefillTimers'] = gasRefillTimers?.map((v) => v.toJson()).toList(); } - if (gasRefillAttachments != null) { - map['gasRefillAttachments'] = gasRefillAttachments?.map((v) => v.toJson()).toList(); + if (gasRefillContactPerson != null) { + map['gasRefillContactPerson'] = gasRefillContactPerson?.map((v) => v?.toJson() ?? {}).toList(); } return map; @@ -454,27 +437,30 @@ class GasRefillTimer { } } -class GasRefillAttachments { - int? id; - num? gasRefillId; - String? attachmentName; - - GasRefillAttachments({this.id, this.attachmentName, this.gasRefillId}); - - GasRefillAttachments.fromJson(Map json) { - id = json['id']; - gasRefillId = json['gasRefillId']; - attachmentName = json['attachmentName']; - } - - Map toJson() { - final Map data = {}; - data['id'] = id; - data['gasRefillId'] = gasRefillId; - data['attachmentName'] = attachmentName; - return data; - } -} +// class GasRefillAttachments { +// int? id; +// num? gasRefillId; +// String? attachmentName; +// Lookup ? documentType; +// +// GasRefillAttachments({this.id, this.attachmentName,this.documentType, this.gasRefillId}); +// +// GasRefillAttachments.fromJson(Map json) { +// id = json['id']; +// gasRefillId = json['gasRefillId']; +// attachmentName = json['attachmentName']; +// documentType = json['documentType']; +// } +// +// Map toJson() { +// final Map data = {}; +// data['id'] = id; +// data['gasRefillId'] = gasRefillId; +// data['attachmentName'] = attachmentName; +// data['documentTypeId'] = documentType?.id; +// return data; +// } +// } class GasRefillContactPerson { int? id; diff --git a/lib/models/new_models/task_request/task_request_model.dart b/lib/models/new_models/task_request/task_request_model.dart index 235b3851..6bce945a 100644 --- a/lib/models/new_models/task_request/task_request_model.dart +++ b/lib/models/new_models/task_request/task_request_model.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; import 'package:test_sa/models/base.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/assistant_employee.dart'; import 'package:test_sa/models/new_models/building.dart'; @@ -63,7 +64,7 @@ class TaskData { Department? department; Rooms? room; String? callComment; - List? taskJobAttachments; + List? taskJobAttachments; TaskContactUser? assignedEngineer; List? taskJobAssistantEmployees = []; TaskJobAssistantEmployees? modelAssistantEmployees; @@ -146,18 +147,18 @@ class TaskData { }); } if (json['attachments'] != null) { - taskJobAttachments = []; + taskJobAttachments = []; json['attachments'].forEach((v) { - taskJobAttachments!.add(TaskJobAttachment.fromJson(v)); + taskJobAttachments!.add(GenericAttachmentModel.fromJson(v)); }); } taskType = json['taskType'] != null ? TaskTypeModel.fromJson(json['taskType']) : null; taskJobStatus = json['taskJobStatus'] != null ? TaskJobStatus.fromJson(json['taskJobStatus']) : null; callComment = json['callComment']; if (json['taskJobAttachments'] != null) { - taskJobAttachments = []; + taskJobAttachments = []; json['taskJobAttachments'].forEach((v) { - taskJobAttachments!.add(TaskJobAttachment.fromJson(v)); + taskJobAttachments!.add(GenericAttachmentModel.fromJson(v)); }); } assignedEngineer = json['assignedEngineer'] != null ? TaskContactUser.fromJson(json['assignedEngineer']) : null; @@ -283,7 +284,7 @@ class TaskData { data['callComment'] = callComment; if (taskJobAttachments != null) { - data['taskJobAttachments'] = taskJobAttachments!.map((e) => e.toJson()).toList(); + data['taskJobAttachments'] = taskJobAttachments!.map((e) => e?.toJson() ?? {}).toList(); } if (assignedEngineer != null) { @@ -368,7 +369,7 @@ class TaskData { data['taskJobActivityEngineerTimers'] = taskJobActivityEngineerTimers!.map((v) => v.toJson()).toList(); } if (taskJobAttachments != null) { - data['attachments'] = taskJobAttachments!.map((v) => v.toJson()).toList(); + data['attachments'] = taskJobAttachments!.map((v) => v?.toJson() ?? {}).toList(); } data['installationBuildingId'] = building?.id; data['installationFloorId'] = floor?.id; @@ -567,26 +568,6 @@ class TaskJobStatus { }; } -class TaskJobAttachment { - final int? id; - final String? name; - String? createdBy; - - TaskJobAttachment({this.id, this.name, this.createdBy}); - - factory TaskJobAttachment.fromJson(Map json) => TaskJobAttachment( - id: json['id'], - name: json['name'], - createdBy: json['createdBy'], - ); - - Map toJson() => { - 'id': id, - 'name': name, - 'createdBy': createdBy, - }; -} - class TaskJobAssistantEmployees { DateTime? startDate; int? id; @@ -755,7 +736,7 @@ class AddTaskModel { TaskEvaluatorUser? taskEvaluatorUser; String? alertNo; String? estimationDeliveryDate; - List? attachments; + List? attachments; String? reasonOfFSCA; String? correctiveActionDescription; @@ -800,7 +781,7 @@ class AddTaskModel { 'reasonOfFSCA': reasonOfFSCA, 'correctiveActionDescription': correctiveActionDescription, 'evaluatorUserId': taskEvaluatorUser?.userId, - 'attachments': attachments?.map((x) => x.toJson()).toList(), + 'attachments': attachments?.map((x) => x.toJson() ?? {}).toList(), }; } diff --git a/lib/models/new_models/work_order_detail_model.dart b/lib/models/new_models/work_order_detail_model.dart index 984edca5..8bfb5e9a 100644 --- a/lib/models/new_models/work_order_detail_model.dart +++ b/lib/models/new_models/work_order_detail_model.dart @@ -1,5 +1,6 @@ import 'package:flutter/foundation.dart'; import 'package:test_sa/models/fault_description.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; import 'package:test_sa/models/lookup.dart'; @@ -146,7 +147,7 @@ class WorkOrderData { Lookup? problemDescription; String? comments; String? voiceNote; - List workOrderAttachments; + List workOrderAttachments; String? returnToService; Lookup? serviceType; Lookup? failureReasone; @@ -232,7 +233,7 @@ class WorkOrderData { comments: json["comments"], voiceNote: json["voiceNote"], edd: json["edd"], - workOrderAttachments: json["workOrderAttachments"] == null ? [] : List.from(json['workOrderAttachments']).map((e) => WorkOrderAttachments.fromJson(e)).toList(), + workOrderAttachments: json["workOrderAttachments"] == null ? [] : List.from(json['workOrderAttachments']).map((e) => GenericAttachmentModel.fromWorkOrderJson(e)).toList(), returnToService: json["returnToService"], serviceType: json["serviceType"] == null ? null : Lookup.fromJson(json["serviceType"]), failureReasone: json["failureReasone"] == null ? null : Lookup.fromJson(json["failureReasone"]), @@ -286,7 +287,7 @@ class WorkOrderData { "edd": edd, 'mrNo': mrNo, 'exchangeCost': exchangeCost, - "workOrderAttachments": workOrderAttachments.map((e) => e.toJson()).toList(), + "workOrderAttachments": workOrderAttachments.map((e) => e.toWorkOrderJson() ?? {}).toList(), "returnToService": returnToService, "serviceType": serviceType?.toJson(), "failureReasone": failureReasone?.toJson(), @@ -503,7 +504,7 @@ class ActivitySparePart { double? installQty; double? returnQty; String? comment; - List? acitiySparePartAttachments; + List? acitiySparePartAttachments; ActivitySparePart({this.id, this.partCatalogItem, this.quantity, this.installQty, this.returnQty, this.comment, this.acitiySparePartAttachments}); @@ -515,9 +516,9 @@ class ActivitySparePart { returnQty = json['returnQty']; comment = json['comment']; if (json['acitiySparePartAttachments'] != null) { - acitiySparePartAttachments = []; + acitiySparePartAttachments = []; json['acitiySparePartAttachments'].forEach((v) { - acitiySparePartAttachments!.add(SparePartAttachments.fromJson(v)); + acitiySparePartAttachments!.add(GenericAttachmentModel.fromJson(v)); }); } } @@ -533,7 +534,7 @@ class ActivitySparePart { data['returnQty'] = returnQty; data['comment'] = comment; if (acitiySparePartAttachments != null) { - data['acitiySparePartAttachments'] = acitiySparePartAttachments!.map((v) => v.toJson()).toList(); + data['acitiySparePartAttachments'] = acitiySparePartAttachments!.map((v) => v?.toJson() ?? {}).toList(); } return data; } diff --git a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart index b8f5fd94..6af49ca6 100644 --- a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart +++ b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart @@ -4,6 +4,7 @@ import 'package:flutter/widgets.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/supplier_details.dart'; import 'package:test_sa/models/timer_model.dart'; @@ -42,7 +43,7 @@ class PlanPreventiveVisit { Lookup? safety; String? engSignature; String? nurseSignature; - List? preventiveVisitAttachments; + List? preventiveVisitAttachments; List? attachments = []; List? preventiveVisitCalibrations; List? preventiveVisitChecklists; @@ -132,9 +133,9 @@ class PlanPreventiveVisit { engSignature = json['engSignature']; nurseSignature = json['nurseSignature']; if (json['preventiveVisitAttachments'] != null) { - preventiveVisitAttachments = []; + preventiveVisitAttachments = []; json['preventiveVisitAttachments'].forEach((v) { - preventiveVisitAttachments!.add(PreventiveVisitAttachments.fromJson(v)); + preventiveVisitAttachments!.add(GenericAttachmentModel.fromPreventiveVisitJson(v)); }); } if (json['preventiveVisitCalibrations'] != null) { @@ -183,53 +184,9 @@ class PlanPreventiveVisit { data['safetyId'] = safety?.id; data['engSignature'] = engSignature; data['nurseSignature'] = nurseSignature; - // - // if (asset != null) { - // data['asset'] = asset!.toJson(); - // } - // data['visitNo'] = visitNo; - // data['planNo'] = planNo; - // data['planName'] = planName; - // data['nextPMDate'] = nextPMDate; - // data['assetName'] = assetName; - // data['model'] = model; - // data['manufacturer'] = manufacturer; - // data['supplierName'] = supplierName; - // data['siteName'] = siteName; - // data['buildingName'] = buildingName; - // data['floorName'] = floorName; - // data['departmentName'] = departmentName; - // data['roomName'] = roomName; - // data['fromDate'] = fromDate; - // data['toDate'] = toDate; - // if (assignedEmployee != null) { - // data['assignedEmployee'] = assignedEmployee!.toJson(); - // } - // data['acutalDateOfVisit'] = acutalDateOfVisit; - // if (typeOfService != null) { - // data['typeOfService'] = typeOfService!.toJson(); - // } - // if (visitStatus != null) { - // data['visitStatus'] = visitStatus!.toJson(); - // } - // data['travelingHours'] = travelingHours; - // data['comments'] = comments; - // data['executionTimeFrame'] = executionTimeFrame; - // if (taskStatus != null) { - // data['taskStatus'] = taskStatus!.toJson(); - // } - // if (deviceStatus != null) { - // data['deviceStatus'] = deviceStatus!.toJson(); - // } - // data['assetAvailability'] = assetAvailability; - // if (safety != null) { - // data['safety'] = safety!.toJson(); - // } - // data['engSignature'] = engSignature; - // data['nurseSignature'] = nurseSignature; if (preventiveVisitAttachments != null) { - data['preventiveVisitAttachments'] = preventiveVisitAttachments!.map((v) => v.toJson()).toList(); + data['preventiveVisitAttachments'] = preventiveVisitAttachments!.map((v) => v.toPreventiveVisitJson()).toList(); } if (preventiveVisitCalibrations != null) { data['preventiveVisitCalibrations'] = preventiveVisitCalibrations!.map((v) => v.toJson()).toList(); @@ -249,10 +206,6 @@ class PlanPreventiveVisit { return data; } - bool _isLocalUrl(String url) { - if (url.isEmpty != false) return false; - return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); - } Future validate(BuildContext context) async { if (visitStatus?.id == null) { @@ -263,10 +216,6 @@ class PlanPreventiveVisit { await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.actualDate}"); return false; } - // if (expectedDate == null) { - // await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.visitDate}"); - // return false; - // } if (tbsTimer?.startAt == null) { await Fluttertoast.showToast(msg: "Working Hours Required"); return false; @@ -276,11 +225,6 @@ class PlanPreventiveVisit { return false; } - // if (externalEngineerTimer?.startAt != null && externalEngineerTimer?.endAt == null) { - // await Fluttertoast.showToast(msg: "Please Stop External Engineer Timer"); - // return false; - // } - return true; } @@ -290,275 +234,6 @@ class PlanPreventiveVisit { } } -// class PlanPreventiveVisit { -// String? id; -// String? visitNo; -// Asset? asset; -// String? planNo; -// String? planName; -// String? nextPMDate; -// String? assetName; -// String? model; -// String? manufacturer; -// String? supplierName; -// String? siteName; -// String? buildingName; -// String? floorName; -// String? departmentName; -// String? roomName; -// String? fromDate; -// String? toDate; -// AssignedEmployee? assignedEmployee; -// String? acutalDateOfVisit; -// TypeOfService? typeOfService; -// VisitStatus? visitStatus; -// String? travelingHours; -// String? comments; -// int? executionTimeFrame; -// Lookup? taskStatus; -// String? deviceStatus; -// Lookup? assetAvailability; -// Lookup? safety; -// String? engSignature; -// String? nurseSignature; -// List? preventiveVisitAttachments; -// List? preventiveVisitCalibrations; -// List? preventiveVisitChecklists; -// List? preventiveVisitKits; -// List? preventiveVisitTimers; -// List? preventiveVisitSuppliers; -// TimerModel? tbsTimer = TimerModel(); -// -// PlanPreventiveVisit( -// {this.id, -// this.visitNo, -// this.asset, -// this.planNo, -// this.planName, -// this.nextPMDate, -// this.assetName, -// this.model, -// this.manufacturer, -// this.supplierName, -// this.siteName, -// this.buildingName, -// this.floorName, -// this.departmentName, -// this.roomName, -// this.fromDate, -// this.toDate, -// this.assignedEmployee, -// this.acutalDateOfVisit, -// this.typeOfService, -// this.visitStatus, -// this.travelingHours, -// this.comments, -// this.executionTimeFrame, -// this.taskStatus, -// this.deviceStatus, -// this.assetAvailability, -// this.safety, -// this.engSignature, -// this.nurseSignature, -// this.preventiveVisitAttachments, -// this.preventiveVisitCalibrations, -// this.preventiveVisitChecklists, -// this.preventiveVisitKits, -// this.preventiveVisitTimers, -// this.preventiveVisitSuppliers}); -// -// PlanPreventiveVisit.fromJson(Map json) { -// id = json['id']; -// visitNo = json['visitNo']; -// asset = json['asset'] != null ? Asset.fromJson(json['asset']) : null; -// planNo = json['planNo']; -// planName = json['planName']; -// nextPMDate = json['nextPMDate']; -// assetName = json['assetName']; -// model = json['model']; -// manufacturer = json['manufacturer']; -// supplierName = json['supplierName']; -// siteName = json['siteName']; -// buildingName = json['buildingName']; -// floorName = json['floorName']; -// departmentName = json['departmentName']; -// roomName = json['roomName']; -// fromDate = json['fromDate']; -// toDate = json['toDate']; -// assignedEmployee = json['assignedEmployee'] != null ? AssignedEmployee.fromJson(json['assignedEmployee']) : null; -// acutalDateOfVisit = json['acutalDateOfVisit']; -// typeOfService = json['typeOfService'] != null ? TypeOfService.fromJson(json['typeOfService']) : null; -// visitStatus = json['visitStatus'] != null ? VisitStatus.fromJson(json['visitStatus']) : null; -// travelingHours = json['travelingHours']; -// comments = json['comments']; -// executionTimeFrame = json['executionTimeFrame']; -// taskStatus = json['taskStatus']; -// deviceStatus = json['deviceStatus']; -// assetAvailability = json['assetAvailability']; -// safety = json['safety']; -// engSignature = json['engSignature']; -// nurseSignature = json['nurseSignature']; -// if (json['preventiveVisitAttachments'] != null) { -// preventiveVisitAttachments = []; -// json['preventiveVisitAttachments'].forEach((v) { -// preventiveVisitAttachments!.add(PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitCalibrations'] != null) { -// preventiveVisitCalibrations = []; -// json['preventiveVisitCalibrations'].forEach((v) { -// preventiveVisitCalibrations!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitChecklists'] != null) { -// preventiveVisitChecklists = []; -// json['preventiveVisitChecklists'].forEach((v) { -// preventiveVisitChecklists!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitKits'] != null) { -// preventiveVisitKits = []; -// json['preventiveVisitKits'].forEach((v) { -// preventiveVisitKits!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// if (json['preventiveVisitTimers'] != null) { -// preventiveVisitTimers = []; -// json['preventiveVisitTimers'].forEach((v) { -// preventiveVisitTimers!.add( PreventiveVisitTimers.fromJson(v)); -// }); -// } -// if (json['preventiveVisitSuppliers'] != null) { -// preventiveVisitSuppliers = []; -// json['preventiveVisitSuppliers'].forEach((v) { -// preventiveVisitSuppliers!.add( PreventiveVisitChecklists.fromJson(v)); -// }); -// } -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['visitNo'] = this.visitNo; -// if (this.asset != null) { -// data['asset'] = this.asset!.toJson(); -// } -// data['planNo'] = this.planNo; -// data['planName'] = this.planName; -// data['nextPMDate'] = this.nextPMDate; -// data['assetName'] = this.assetName; -// data['model'] = this.model; -// data['manufacturer'] = this.manufacturer; -// data['supplierName'] = this.supplierName; -// data['siteName'] = this.siteName; -// data['buildingName'] = this.buildingName; -// data['floorName'] = this.floorName; -// data['departmentName'] = this.departmentName; -// data['roomName'] = this.roomName; -// data['fromDate'] = this.fromDate; -// data['toDate'] = this.toDate; -// if (this.assignedEmployee != null) { -// data['assignedEmployee'] = this.assignedEmployee!.toJson(); -// } -// data['acutalDateOfVisit'] = this.acutalDateOfVisit; -// if (this.typeOfService != null) { -// data['typeOfService'] = this.typeOfService!.toJson(); -// } -// if (this.visitStatus != null) { -// data['visitStatus'] = this.visitStatus!.toJson(); -// } -// data['travelingHours'] = this.travelingHours; -// data['comments'] = this.comments; -// data['executionTimeFrame'] = this.executionTimeFrame; -// data['taskStatus'] = this.taskStatus; -// data['deviceStatus'] = this.deviceStatus; -// data['assetAvailability'] = this.assetAvailability; -// data['safety'] = this.safety; -// data['engSignature'] = this.engSignature; -// data['nurseSignature'] = this.nurseSignature; -// if (this.preventiveVisitAttachments != null) { -// data['preventiveVisitAttachments'] = this.preventiveVisitAttachments!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitCalibrations != null) { -// data['preventiveVisitCalibrations'] = this.preventiveVisitCalibrations!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitChecklists != null) { -// data['preventiveVisitChecklists'] = this.preventiveVisitChecklists!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitKits != null) { -// data['preventiveVisitKits'] = this.preventiveVisitKits!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitTimers != null) { -// data['preventiveVisitTimers'] = this.preventiveVisitTimers!.map((v) => v.toJson()).toList(); -// } -// if (this.preventiveVisitSuppliers != null) { -// data['preventiveVisitSuppliers'] = this.preventiveVisitSuppliers!.map((v) => v.toJson()).toList(); -// } -// return data; -// } -// -// bool _isLocalUrl(String url) { -// if (url.isEmpty != false) return false; -// return url.startsWith("/") || url.startsWith("file://") || url.substring(1).startsWith(':\\'); -// } -// -// Future validate(BuildContext context) async { -// if (visitStatus?.id == null) { -// await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.status}"); -// return false; -// } -// if (acutalDateOfVisit == null) { -// await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.actualDate}"); -// return false; -// } -// // if (expectedDate == null) { -// // await Fluttertoast.showToast(msg: "${context.translation.youHaveToSelect} ${context.translation.visitDate}"); -// // return false; -// // } -// if (tbsTimer?.startAt == null) { -// await Fluttertoast.showToast(msg: "Working Hours Required"); -// return false; -// } -// if (tbsTimer?.endAt == null) { -// await Fluttertoast.showToast(msg: "Please Stop The Timer"); -// return false; -// } -// -// // if (externalEngineerTimer?.startAt != null && externalEngineerTimer?.endAt == null) { -// // await Fluttertoast.showToast(msg: "Please Stop External Engineer Timer"); -// // return false; -// // } -// -// return true; -// } -// -// void removeEmptyObjects() { -// // if (vCalibrationTools?.isNotEmpty ?? false) vCalibrationTools!.removeWhere((element) => element.assetId == null && element.calibrationDateOfTesters == null); -// // if (vKits?.isNotEmpty ?? false) vKits!.removeWhere((element) => element.partName == null && element.partNumber == null); -// } -// } - -// class Asset { -// num? id; -// String? assetNumber; -// String? assetSerialNo; -// -// Asset({this.id, this.assetNumber, this.assetSerialNo}); -// -// Asset.fromJson(Map json) { -// id = json['id']; -// assetNumber = json['assetNumber']; -// assetSerialNo = json['assetSerialNo']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['assetNumber'] = this.assetNumber; -// data['assetSerialNo'] = this.assetSerialNo; -// return data; -// } -// } class AssignedEmployee { String? userId; @@ -588,49 +263,6 @@ class AssignedEmployee { } } -// class Lookup { -// int? id; -// String? name; -// int? value; -// -// Lookup({this.id, this.name, this.value}); -// -// Lookup.fromJson(Map json) { -// id = json['id']; -// name = json['name']; -// value = json['value']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['name'] = this.name; -// data['value'] = this.value; -// return data; -// } -// } - -// class VisitStatus { -// int? id; -// String? name; -// int? value; -// -// VisitStatus({this.id, this.name, this.value}); -// -// VisitStatus.fromJson(Map json) { -// id = json['id']; -// name = json['name']; -// value = json['value']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['name'] = this.name; -// data['value'] = this.value; -// return data; -// } -// } class PreventiveVisitChecklists { int? id; @@ -655,9 +287,6 @@ class PreventiveVisitChecklists { data['taskStatusId'] = taskStatus?.id; data['taskComment'] = taskComment; data['measuredValue'] = measuredValue; - // if (instructionText != null) { - // data['instructionText'] = instructionText!.toJson(); - // } return data; } } @@ -706,25 +335,6 @@ class PreventiveVisitTimers { } } -class PreventiveVisitAttachments { - int? id; - String? attachmentName; - - PreventiveVisitAttachments({this.id, this.attachmentName}); - - PreventiveVisitAttachments.fromJson(Map json) { - id = json['id']; - attachmentName = json['attachmentName']; - } - - Map toJson() { - final Map data = {}; - data['id'] = id; - data['attachmentName'] = attachmentName; - return data; - } -} - class PreventiveVisitCalibrations { num? id; Asset? asset; @@ -742,7 +352,6 @@ class PreventiveVisitCalibrations { final Map data = {}; data['id'] = id; if (asset != null) { - // data['asset'] = asset!.toJson(); data['assetId'] = asset?.id; } data['calibrationDateOfTesters'] = calibrationDateOfTesters; @@ -774,11 +383,9 @@ class PreventiveVisitSuppliers { final Map data = {}; data['id'] = id; if (supplier != null) { - // data['supplier'] = supplier!.toJson(); data['supplierId'] = supplier?.id; } if (suppPerson != null) { - // data['suppPerson'] = suppPerson!.toJson(); data['suppPersonId'] = suppPerson?.id; } data['startDateTime'] = startDateTime?.toIso8601String(); @@ -788,170 +395,6 @@ class PreventiveVisitSuppliers { } } -// class Supplier { -// int? id; -// String? suppliername; -// String? name; -// String? website; -// String? email; -// String? code; -// int? suppNo; -// String? suppStatusId; -// String? cityId; -// String? person; -// String? comment; -// String? zipcode; -// String? contact; -// List? telephones; -// List? faxes; -// List? addresses; -// List? attachments; -// List? suppPersons; -// List? suppTCodes; -// -// Supplier( -// {this.id, -// this.suppliername, -// this.name, -// this.website, -// this.email, -// this.code, -// this.suppNo, -// this.suppStatusId, -// this.cityId, -// this.person, -// this.comment, -// this.zipcode, -// this.contact, -// this.telephones, -// this.faxes, -// this.addresses, -// this.attachments, -// this.suppPersons, -// this.suppTCodes}); -// -// Supplier.fromJson(Map json) { -// id = json['id']; -// suppliername = json['suppliername']; -// name = json['name']; -// website = json['website']; -// email = json['email']; -// code = json['code']; -// suppNo = json['suppNo']; -// suppStatusId = json['suppStatusId']; -// cityId = json['cityId']; -// person = json['person']; -// comment = json['comment']; -// zipcode = json['zipcode']; -// contact = json['contact']; -// if (json['telephones'] != null) { -// telephones = []; -// json['telephones'].forEach((v) { -// telephones!.add(v); -// }); -// } -// if (json['faxes'] != null) { -// faxes = []; -// json['faxes'].forEach((v) { -// faxes!.add(v); -// }); -// } -// if (json['addresses'] != null) { -// addresses = []; -// json['addresses'].forEach((v) { -// addresses!.add(v); -// }); -// } -// if (json['attachments'] != null) { -// attachments = []; -// json['attachments'].forEach((v) { -// attachments!.add(v); -// }); -// } -// if (json['suppPersons'] != null) { -// suppPersons = []; -// json['suppPersons'].forEach((v) { -// suppPersons!.add(SuppPersons.fromJson(v)); -// }); -// } -// if (json['suppTCodes'] != null) { -// suppTCodes = []; -// json['suppTCodes'].forEach((v) { -// suppTCodes!.add(v); -// }); -// } -// } -// -// Map toJson() { -// final Map data = {}; -// data['id'] = id; -// data['suppliername'] = suppliername; -// data['name'] = name; -// data['website'] = website; -// data['email'] = email; -// data['code'] = code; -// data['suppNo'] = suppNo; -// data['suppStatusId'] = suppStatusId; -// data['cityId'] = cityId; -// data['person'] = person; -// data['comment'] = comment; -// data['zipcode'] = zipcode; -// data['contact'] = contact; -// if (telephones != null) { -// data['telephones'] = telephones!.map((v) => v).toList(); -// } -// if (faxes != null) { -// data['faxes'] = faxes!.map((v) => v).toList(); -// } -// if (addresses != null) { -// data['addresses'] = addresses!.map((v) => v).toList(); -// } -// if (attachments != null) { -// data['attachments'] = attachments!.map((v) => v).toList(); -// } -// if (suppPersons != null) { -// data['suppPersons'] = suppPersons!.map((v) => v.toJson()).toList(); -// } -// if (suppTCodes != null) { -// data['suppTCodes'] = suppTCodes!.map((v) => v).toList(); -// } -// return data; -// } -// } - -// class SuppPersons { -// int? id; -// int? supplierId; -// String? personName; -// int? personRoleId; -// String? contact; -// String? externalEngCode; -// String? email; -// -// SuppPersons({this.id, this.supplierId, this.personName, this.personRoleId, this.contact, this.externalEngCode, this.email}); -// -// SuppPersons.fromJson(Map json) { -// id = json['id']; -// supplierId = json['supplierId']; -// personName = json['personName']; -// personRoleId = json['personRoleId']; -// contact = json['contact']; -// externalEngCode = json['externalEngCode']; -// email = json['email']; -// } -// -// Map toJson() { -// final Map data = Map(); -// data['id'] = this.id; -// data['supplierId'] = this.supplierId; -// data['personName'] = this.personName; -// data['personRoleId'] = this.personRoleId; -// data['contact'] = this.contact; -// data['externalEngCode'] = this.externalEngCode; -// data['email'] = this.email; -// return data; -// } -// } class PreventiveVisitKits { int? id; diff --git a/lib/models/ppm/ppm.dart b/lib/models/ppm/ppm.dart index 44090346..5cdee63f 100644 --- a/lib/models/ppm/ppm.dart +++ b/lib/models/ppm/ppm.dart @@ -5,6 +5,7 @@ import 'dart:typed_data'; import 'package:flutter/cupertino.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/ppm/ppm_attachment.dart'; import 'package:test_sa/models/ppm/ppm_calibration_tools.dart'; import 'package:test_sa/models/ppm/ppm_check_list.dart'; @@ -173,7 +174,7 @@ class Ppm { if (json['vAttachments'] != null) { files = []; json['vAttachments'].forEach((v) { - files!.add(PpmAttachments.fromJson(v)); + files!.add(GenericAttachmentModel.fromPpmJson(v)); }); } visitStatusId = json['visitStatusId']; @@ -286,7 +287,7 @@ class Ppm { List? vKits; List? vContacts; List? vChecklists; - List? files; + List? files; num? visitStatusId; List? visitTimers; @@ -380,7 +381,7 @@ class Ppm { List? vKits, List? vContacts, List? vChecklists, - List? files, + List? files, num? visitStatusId, List? visitTimers, String? startDate, @@ -574,7 +575,7 @@ class Ppm { if (files?.isNotEmpty ?? false) { map["vAttachments"] = files! .map((file) => - {"attachmentName": _isLocalUrl(file.attachmentName!) ? ("${file.attachmentName!.split("/").last}|${base64Encode(File(file.attachmentName!).readAsBytesSync())}") : file.attachmentName}) + {"attachmentName": _isLocalUrl(file.name!) ? ("${file.name!.split("/").last}|${base64Encode(File(file.name!).readAsBytesSync())}") : file.name}) .toList(); } map['visitStatusId'] = visitStatusId; diff --git a/lib/models/ppm/ppm_attachment.dart b/lib/models/ppm/ppm_attachment.dart index e1e15df8..b0d7df0e 100644 --- a/lib/models/ppm/ppm_attachment.dart +++ b/lib/models/ppm/ppm_attachment.dart @@ -1,40 +1,42 @@ -class PpmAttachments { - PpmAttachments({ - this.id, - this.visitId, - this.attachmentName, - this.attachmentURL, - }); +//TODO need to delete this - PpmAttachments.fromJson(dynamic json) { - id = json['id']; - visitId = json['visitId']; - attachmentName = json['attachmentName'] ?? json['attachmentURL']; // Handle potential null and prioritize'attachmentName' - } - - num? id; // Now nullable - num? visitId; // Now nullable - String? attachmentName; // Now nullable - String? attachmentURL; // Now nullable - - PpmAttachments copyWith({ - num? id, - num? visitId, - String? attachmentName, - String? attachmentURL, - }) => - PpmAttachments( - id: id ?? this.id, - visitId: visitId ?? this.visitId, - attachmentName: attachmentName ?? this.attachmentName,attachmentURL: attachmentURL ?? this.attachmentURL, - ); - - Map toJson() { - final map = {}; - map['id'] = id; - map['visitId'] = visitId; - map['attachmentName'] = attachmentName; - map['attachmentURL'] = attachmentURL; - return map; - } -} \ No newline at end of file +// class PpmAttachments { +// PpmAttachments({ +// this.id, +// this.visitId, +// this.attachmentName, +// this.attachmentURL, +// }); +// +// PpmAttachments.fromJson(dynamic json) { +// id = json['id']; +// visitId = json['visitId']; +// attachmentName = json['attachmentName'] ?? json['attachmentURL']; // Handle potential null and prioritize'attachmentName' +// } +// +// num? id; // Now nullable +// num? visitId; // Now nullable +// String? attachmentName; // Now nullable +// String? attachmentURL; // Now nullable +// +// PpmAttachments copyWith({ +// num? id, +// num? visitId, +// String? attachmentName, +// String? attachmentURL, +// }) => +// PpmAttachments( +// id: id ?? this.id, +// visitId: visitId ?? this.visitId, +// attachmentName: attachmentName ?? this.attachmentName,attachmentURL: attachmentURL ?? this.attachmentURL, +// ); +// +// Map toJson() { +// final map = {}; +// map['id'] = id; +// map['visitId'] = visitId; +// map['attachmentName'] = attachmentName; +// map['attachmentURL'] = attachmentURL; +// return map; +// } +// } \ No newline at end of file diff --git a/lib/models/service_request/search_work_order.dart b/lib/models/service_request/search_work_order.dart index 41f282cf..611339dc 100644 --- a/lib/models/service_request/search_work_order.dart +++ b/lib/models/service_request/search_work_order.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/service_report.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; @@ -10,7 +11,6 @@ import 'package:test_sa/models/service_request/wo_call_request.dart'; import 'package:test_sa/models/service_request/wo_parent.dart'; import 'package:test_sa/models/timer_model.dart'; -import '../../attachment.dart'; import '../fault_description.dart'; import '../new_models/assigned_employee.dart'; import '../new_models/assistant_employee.dart'; @@ -41,12 +41,12 @@ class SearchWorkOrder { this.travelingHours, this.travelingExpenses, this.faultDescription, - this.sparePartsWorkOrders, - this.reviewComment, - this.comment, - this.attachmentsWorkOrder, - this.equipmentStatus, - this.suppEngineerWorkOrders, + this.sparePartsWorkOrders, + this.reviewComment, + this.comment, + List? attachmentsWorkOrder, + this.equipmentStatus, + this.suppEngineerWorkOrders, this.engSignature, this.nurseSignature, this.woParentDto, @@ -106,7 +106,7 @@ class SearchWorkOrder { if (json['attachmentsWorkOrder'] != null) { attachmentsWorkOrder = []; json['attachmentsWorkOrder'].forEach((v) { - attachmentsWorkOrder!.add(Attachment.fromJson(v)); + attachmentsWorkOrder!.add(GenericAttachmentModel.fromJson(v)); }); } equipmentStatus = json['equipmentStatus'] != null ? Lookup.fromJson(json['equipmentStatus']) : null; @@ -155,8 +155,8 @@ class SearchWorkOrder { sparePartsWorkOrders = (wo.sparePartsWorkOrders ?? sparePartsWorkOrders)?.map((e) => SparePartsWorkOrders.fromJson(e.toJson() ?? {})).toList() ?? []; reviewComment = wo.reviewComment ?? reviewComment; comment = wo.comment ?? comment; - attachmentsWorkOrder = (wo.attachmentsWorkOrder ?? attachmentsWorkOrder)?.map((e) => Attachment.fromJson(e.toJson() ?? {})).toList() ?? []; - equipmentStatus = Lookup.fromJson((wo.equipmentStatus ?? equipmentStatus)?.toJson() ?? {}); + attachmentsWorkOrder = (wo.attachmentsWorkOrder ?? attachmentsWorkOrder)?.map((e) => GenericAttachmentModel.fromJson(e?.toJson() ?? {})).toList() ?? []; + equipmentStatus = wo.equipmentStatus ?? equipmentStatus; suppEngineerWorkOrders = (wo.suppEngineerWorkOrders ?? suppEngineerWorkOrders)?.map((e) => SuppEngineerWorkOrders.fromJson(e.toJson() ?? {})).toList() ?? []; engSignature = wo.engSignature ?? engSignature; nurseSignature = wo.nurseSignature ?? nurseSignature; @@ -191,7 +191,7 @@ class SearchWorkOrder { List? sparePartsWorkOrders; String? reviewComment; String? comment; - List? attachmentsWorkOrder; + List? attachmentsWorkOrder; Lookup? equipmentStatus; List? suppEngineerWorkOrders; String? engSignature; @@ -233,7 +233,7 @@ class SearchWorkOrder { List? sparePartsWorkOrders, String? reviewComment, String? comment, - List? attachmentsWorkOrder, + List? attachmentsWorkOrder, Lookup? equipmentStatus, List? suppEngineerWorkOrders, String? engSignature, diff --git a/lib/models/service_request/service_report.dart b/lib/models/service_request/service_report.dart index 56a1da6f..e09c9ac8 100644 --- a/lib/models/service_request/service_report.dart +++ b/lib/models/service_request/service_report.dart @@ -5,6 +5,7 @@ import 'package:fluttertoast/fluttertoast.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; @@ -13,7 +14,6 @@ import 'package:test_sa/models/service_request/wo_call_request.dart'; import 'package:test_sa/models/service_request/wo_parent.dart'; import 'package:test_sa/models/timer_model.dart'; -import '../../attachment.dart'; import '../device/asset.dart'; import '../fault_description.dart'; import '../new_models/assigned_employee.dart'; @@ -118,7 +118,7 @@ class ServiceReport { attachmentsWorkOrder = []; json['attachmentsWorkOrder'].forEach((v) { v["name"] = URLs.getFileUrl(v["name"]); - attachmentsWorkOrder!.add(Attachment.fromJson(v)); + attachmentsWorkOrder!.add(GenericAttachmentModel.fromJson(v)); }); } equipmentStatus = json['equipmentStatus'] != null ? Lookup.fromJson(json['equipmentStatus']) : null; @@ -163,7 +163,7 @@ class ServiceReport { List? sparePartsWorkOrders; String? reviewComment; String? comment; - List? attachmentsWorkOrder; + List? attachmentsWorkOrder; Lookup? equipmentStatus; List? suppEngineerWorkOrders; String? engSignature; @@ -204,7 +204,7 @@ class ServiceReport { List? sparePartsWorkOrders, String? reviewComment, String? comment, - List? attachmentsWorkOrder, + List? attachmentsWorkOrder, Lookup? equipmentStatus, List? suppEngineerWorkOrders, String? engSignature, @@ -311,7 +311,7 @@ class ServiceReport { map['reviewComment'] = reviewComment; map['comment'] = comment; if (attachmentsWorkOrder != null) { - map['attachmentsWorkOrder'] = attachmentsWorkOrder!.map((v) => {"name": v.name!.getFileName}).toList(); + map['attachmentsWorkOrder'] = attachmentsWorkOrder!.where((v) => v?.name != null).map((v) => {"name": v!.name!.getFileName}).toList(); } if (equipmentStatus != null) { map['equipmentStatus'] = equipmentStatus!.toJson(); diff --git a/lib/models/service_request/supplier_details.dart b/lib/models/service_request/supplier_details.dart index 884206ad..06447c00 100644 --- a/lib/models/service_request/supplier_details.dart +++ b/lib/models/service_request/supplier_details.dart @@ -1,4 +1,5 @@ import 'package:test_sa/models/base.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; class SupplierDetails extends Base { SupplierDetails({ @@ -60,7 +61,7 @@ class SupplierDetails extends Base { if (json['attachments'] != null) { attachments = []; json['attachments'].forEach((v) { - attachments!.add(Attachments.fromJson(v)); + attachments!.add(GenericAttachmentModel.fromSupplierJson(v)); }); } if (json['suppPersons'] != null) { @@ -93,7 +94,7 @@ class SupplierDetails extends Base { List? telephones; List? faxes; List? addresses; - List? attachments; + List? attachments; List? suppPersons; List? suppTCodes; @@ -114,7 +115,7 @@ class SupplierDetails extends Base { List? telephones, List? faxes, List? addresses, - List? attachments, + List? attachments, List? suppPersons, List? suppTCodes, }) => @@ -165,7 +166,7 @@ class SupplierDetails extends Base { map['addresses'] = addresses!.map((v) => v.toJson()).toList(); } if (attachments != null) { - map['attachments'] = attachments!.map((v) => v.toJson()).toList(); + map['attachments'] = attachments!.map((v) => v.toSupplierJson()).toList(); } if (suppPersons != null) { map['suppPersons'] = suppPersons!.map((v) => v.toJson()).toList(); @@ -283,48 +284,48 @@ class SuppPersons extends Base { } } -class Attachments { - Attachments({ - this.id, - this.supplierId, - this.attachmentName, - this.attachmentURL, - }); - - Attachments.fromJson(dynamic json) { - id = json['id']; - supplierId = json['supplierId']; - attachmentName = json['attachmentName']; - attachmentURL = json['attachmentURL']; - } - - num? id; - num? supplierId; - String? attachmentName; - String? attachmentURL; - - Attachments copyWith({ - num? id, - num? supplierId, - String? attachmentName, - String? attachmentURL, - }) => - Attachments( - id: id ?? this.id, - supplierId: supplierId ?? this.supplierId, - attachmentName: attachmentName ?? this.attachmentName, - attachmentURL: attachmentURL ?? this.attachmentURL, - ); - - Map toJson() { - final map = {}; - map['id'] = id; - map['supplierId'] = supplierId; - map['attachmentName'] = attachmentName; - map['attachmentURL'] = attachmentURL; - return map; - } -} +// class Attachments { +// Attachments({ +// this.id, +// this.supplierId, +// this.attachmentName, +// this.attachmentURL, +// }); +// +// Attachments.fromJson(dynamic json) { +// id = json['id']; +// supplierId = json['supplierId']; +// attachmentName = json['attachmentName']; +// attachmentURL = json['attachmentURL']; +// } +// +// num? id; +// num? supplierId; +// String? attachmentName; +// String? attachmentURL; +// +// Attachments copyWith({ +// num? id, +// num? supplierId, +// String? attachmentName, +// String? attachmentURL, +// }) => +// Attachments( +// id: id ?? this.id, +// supplierId: supplierId ?? this.supplierId, +// attachmentName: attachmentName ?? this.attachmentName, +// attachmentURL: attachmentURL ?? this.attachmentURL, +// ); +// +// Map toJson() { +// final map = {}; +// map['id'] = id; +// map['supplierId'] = supplierId; +// map['attachmentName'] = attachmentName; +// map['attachmentURL'] = attachmentURL; +// return map; +// } +// } class Addresses { Addresses({ diff --git a/lib/modules/asset_delivery_module/pages/attachment_view.dart b/lib/modules/asset_delivery_module/pages/attachment_view.dart index 5759ebe8..140c524b 100644 --- a/lib/modules/asset_delivery_module/pages/attachment_view.dart +++ b/lib/modules/asset_delivery_module/pages/attachment_view.dart @@ -128,6 +128,8 @@ class _AssetDeliveryAttachmentViewState extends State { @override Future getData({int? id}) async { @@ -31,3 +31,33 @@ class AttachmentTypeLookupProvider extends LoadingListNotifier { } } } + +class AttachmentTypeLookupProviderLatest extends LoadingListNotifier { + @override + Future getData({int? id}) async { + if (loading == true) return -2; + loading = true; + notifyListeners(); + try { + // OPTIMIZATION: Enable caching for demo document types lookup + Response response = await ApiManager.instance.get( + URLs.getAttachmentTypesLookup, + useCache: true, + enableToastMessage: false, + ); + stateCode = response.statusCode; + if (response.statusCode >= 200 && response.statusCode < 300) { + List categoriesListJson = json.decode(response.body)["data"]; + items = categoriesListJson.map((item) => Lookup.fromJson(item)).toList(); + } + loading = false; + notifyListeners(); + return response.statusCode; + } catch (error) { + loading = false; + stateCode = -1; + notifyListeners(); + return -1; + } + } +} diff --git a/lib/modules/asset_inventory_module/models/asset_inventory_model.dart b/lib/modules/asset_inventory_module/models/asset_inventory_model.dart index 4a4e6587..e5040ef4 100644 --- a/lib/modules/asset_inventory_module/models/asset_inventory_model.dart +++ b/lib/modules/asset_inventory_module/models/asset_inventory_model.dart @@ -1,5 +1,7 @@ import 'dart:developer'; +import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; import 'package:test_sa/models/new_models/floor.dart'; import 'package:test_sa/models/new_models/room_model.dart'; @@ -106,7 +108,7 @@ class AssetInventoryModel { Department? department; Rooms? room; SupplierDetails? supplier; - List assetInventoryDetailAssetAttachments = []; + List assetInventoryDetailAssetAttachments = []; AssetInventoryModel({ this.id, @@ -195,10 +197,10 @@ class AssetInventoryModel { photo = json['photo']; photoOriginName = json['photoOriginName']; remarks = json['remarks']; - if (json['assetTransferAttachments'] != null) { + if (json['assetInventoryDetailAssetAttachments'] != null) { assetInventoryDetailAssetAttachments = []; json['assetInventoryDetailAssetAttachments'].forEach((v) { - assetInventoryDetailAssetAttachments.add(AssetInventoryDetailAssetAttachments.fromJson(v)); + assetInventoryDetailAssetAttachments.add(GenericAttachmentModel.fromAssetJson(v)); }); } @@ -241,7 +243,7 @@ class AssetInventoryModel { 'photo': photo, 'remarks': remarks, 'assetInventoryDetailAssetAttachments': assetInventoryDetailAssetAttachments != null - ? assetInventoryDetailAssetAttachments!.map((v) => v.toJson()).toList() + ? assetInventoryDetailAssetAttachments!.map((v) => v?.toAssetJson() ?? {}).toList() : [], }; } @@ -307,39 +309,3 @@ class AssetInventoryModel { } -class AssetInventoryDetailAssetAttachments { - AssetInventoryDetailAssetAttachments({ - this.id, - this.name, - this.originalName, - }); - - AssetInventoryDetailAssetAttachments.fromJson(dynamic json) { - id = json['id']; - name = json['name']; - originalName = json['originalName']; - } - - num? id; - String? name; - String? originalName; - - AssetInventoryDetailAssetAttachments copyWith({ - num? id, // Parameter is now nullable - String? name, // Parameter is now nullable - String? originalName, // Parameter is now nullable - }) => - AssetInventoryDetailAssetAttachments( - id: id ?? this.id, - name: name??this.name, - originalName: originalName??this.originalName, - ); - - Map toJson() { - final map = {}; - map['id'] = id; - map['name'] = name; - map['originalName'] = originalName; - return map; - } -} diff --git a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart index 29c3d4d5..11785f86 100644 --- a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart +++ b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart @@ -302,6 +302,7 @@ class _AssetInventoryFormViewState extends State { AttachmentPicker( label: context.translation.attachFiles, attachment: attachments, + showAsListView: true, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), @@ -406,7 +407,7 @@ class _AssetInventoryFormViewState extends State { // try { for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _scannedAssetModel?.assetInventoryDetailAssetAttachments.add(AssetInventoryDetailAssetAttachments(id: item.id, name: fileName)); + _scannedAssetModel?.assetInventoryDetailAssetAttachments.add(GenericAttachmentModel(id: item.id, name: fileName,documentType: item.documentType)); } // // } catch (error) { // // print(error); diff --git a/lib/modules/cm_module/cm_detail_provider.dart b/lib/modules/cm_module/cm_detail_provider.dart index 9aa4aa4d..fae159c2 100644 --- a/lib/modules/cm_module/cm_detail_provider.dart +++ b/lib/modules/cm_module/cm_detail_provider.dart @@ -260,15 +260,15 @@ class CMDetailProvider extends ChangeNotifier { } //upload workorder attachment by engineer.. - Future addWorkOrderAttachment({required int woId, required List attachments, required List otherAttachment}) async { + Future addWorkOrderAttachment({required int woId, required List attachments, required List otherAttachment}) async { try { - List woAttachments = []; + List woAttachments = []; if (otherAttachment.isNotEmpty) { woAttachments.addAll(otherAttachment); } for (var file in attachments) { String fileName = CMRequestUtils.isLocalUrl(file.name ?? '') ? ("${file.name ?? ''.split("/").last}|${base64Encode(File(file.name ?? '').readAsBytesSync())}") : file.name ?? ''; - woAttachments.add(WorkOrderAttachments(id: file.id, name: fileName, createdBy: file.createdBy)); + woAttachments.add(GenericAttachmentModel(id: file.id, name: fileName, createdBy: file.createdBy, documentType: file.documentType)); } isLoading = true; diff --git a/lib/modules/cm_module/create_cm_request.dart b/lib/modules/cm_module/create_cm_request.dart index 6dcf83e0..2ddf921c 100644 --- a/lib/modules/cm_module/create_cm_request.dart +++ b/lib/modules/cm_module/create_cm_request.dart @@ -157,6 +157,7 @@ class _CreateCMRequestState extends State with TickerProviderSt 24.height, AttachmentPicker( label: context.translation.attachImage, + showAsListView: true, attachment: _deviceImages, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), @@ -350,10 +351,10 @@ class _CreateCMRequestState extends State with TickerProviderSt _serviceRequest.audio = "${file.path.split("/").last}|${base64Encode(file.readAsBytesSync())}"; } } - List attachement = []; + List attachement = []; for (var item in _deviceImages) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - attachement.add(WorkOrderAttachments(id: 0, name: fileName)); + attachement.add(GenericAttachmentModel(id: 0, name: fileName, documentType: item.documentType)); } _requestDetailProvider.workOrderHelperModel = WorkOrderHelperModel( assetId: _serviceRequest.device?.id, diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index a543651f..4c6adb41 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -7,6 +7,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/user_types.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart'; import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; import 'package:test_sa/models/new_models/assistant_employee.dart'; @@ -172,7 +173,7 @@ class _ActivitiesListViewState extends State { if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[ 2.height, const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), + FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.whereType().where((e) => e.name != null).map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index 73a7f9ea..ab0538e9 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; @@ -41,7 +43,7 @@ class ServiceRequestDetailView extends StatefulWidget { class _ServiceRequestDetailViewState extends State { List _userAttachments = []; - List _attachments = []; + List _attachments = []; @override void initState() { @@ -53,13 +55,20 @@ class _ServiceRequestDetailViewState extends State { UserProvider userProvider = Provider.of(context, listen: false); return Consumer(builder: (pContext, requestProvider, _) { if (userProvider.user?.type == UsersTypes.engineer) { - // _userAttachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments.where((e) => e.createdBy == _userProvider.user?.userID).map((e) => File(e.name ?? '')).toList() ?? []; - _userAttachments = - requestProvider.currentWorkOrder?.data?.workOrderAttachments.where((e) => e.createdBy == userProvider.user?.userID).map((e) => GenericAttachmentModel.fromJson(e.toJson())).toList() ?? []; - _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments.where((e) => e.createdBy != userProvider.user?.userID).toList() ?? []; + _userAttachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments + .whereType() + .where((e) => e.createdBy == userProvider.user?.userID) + .map((e) => GenericAttachmentModel(id: e.id, name: e.name, createdBy: e.createdBy, documentType: e.documentType)) + .toList() ?? []; + _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments + .whereType() + .where((e) => e.createdBy != userProvider.user?.userID) + .toList() ?? []; } else { - //show only nurse attachments - _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments.where((e) => e.createdBy == userProvider.user?.userID).toList() ?? []; + _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments + .whereType() + .where((e) => e.createdBy == userProvider.user?.userID) + .toList() ?? []; } bool showInitialVisitCard = requestProvider.currentWorkOrder?.data?.needAVisitDateTime != null && @@ -267,20 +276,20 @@ class _ServiceRequestDetailViewState extends State { const Divider().defaultStyle(context), AttachmentPicker( label: context.translation.attachments, + showAsListView: true, attachment: _userAttachments, buttonColor: AppColor.primary10, onlyImages: false, - // showAsGrid: true, buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), onChange: (attachment) { - requestProvider.addWorkOrderAttachment(woId: workOrder.requestId!, attachments: attachment, otherAttachment: _attachments); + requestProvider.addWorkOrderAttachment(woId: workOrder.requestId!, attachments: attachment, otherAttachment: _attachments,); }, ), ], ] else ...[ if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), + FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList(),showAsListView: true,), ], //handle nurse case.. ], diff --git a/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart b/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart index d31dbf94..a6b3f5d7 100644 --- a/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart +++ b/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart @@ -106,9 +106,10 @@ class _AssetRetiredState extends State with TickerProviderStateMix AttachmentPicker( label: context.translation.attachFiles, attachment: _attachments, + showAsListView: true, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), - buttonColor: AppColor.black10, + // buttonColor: AppColor.black10, ), ], ).paddingOnly(start: 13, end: 13, top: 14, bottom: 16), @@ -125,7 +126,8 @@ class _AssetRetiredState extends State with TickerProviderStateMix for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments?.add(ActivityAssetToBeRetiredAttachments(id: item.id, name: fileName)); + requestDetailProvider.assetRetiredHelperModel?.activityAssetToBeRetiredAttachments + ?.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType)); } int status = await requestDetailProvider.createActivityAssetToBeRetired(); if (status == 200) { diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 75140eb4..6c762356 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -83,7 +83,7 @@ class _SparePartRequestState extends State with TickerProvider activityStatus = _requestDetailProvider?.sparePartHelperModel?.activityStatus?.value; scheduleMicrotask(() async { _isLoading = true; - attachments = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.map((e) => GenericAttachmentModel(id: e.id!, name: e.name ?? '')).toList() ?? []; + attachments = _requestDetailProvider?.sparePartHelperModel?.sparePartAttachments?.where((e) => e?.id != null).map((e) => GenericAttachmentModel(id: e!.id!, name: e.name ?? '')).toList() ?? []; setState(() {}); _spareParts = await _partsProvider!.getPartsListByDisplayName(assetId: _requestDetailProvider?.currentWorkOrder?.data?.asset?.id); _isLoading = false; @@ -292,9 +292,10 @@ class _SparePartRequestState extends State with TickerProvider 12.height, AttachmentPicker( label: context.translation.attachQuotation, + showAsListView: true, attachment: attachments, buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), - buttonColor: AppColor.primary10, + // buttonColor: AppColor.primary10, ), ], ).toShadowContainer(context), @@ -334,7 +335,7 @@ class _SparePartRequestState extends State with TickerProvider for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; requestDetailProvider.sparePartHelperModel?.sparePartAttachments?.add( - SparePartAttachments(id: item.id, name: fileName), + GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType), ); } diff --git a/lib/modules/demo_module/create_demo_request_page.dart b/lib/modules/demo_module/create_demo_request_page.dart index 4ff8f3ff..f7f13be8 100644 --- a/lib/modules/demo_module/create_demo_request_page.dart +++ b/lib/modules/demo_module/create_demo_request_page.dart @@ -25,7 +25,6 @@ import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; import 'package:test_sa/models/service_request/supplier_details.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/demo_module/models/demo_attachment_model.dart'; import 'package:test_sa/modules/demo_module/provider/demo_period_lookup_provider.dart'; import 'package:test_sa/modules/demo_module/provider/demo_provider.dart'; import 'package:test_sa/modules/loan_module/models/loan_form_model.dart'; @@ -495,23 +494,23 @@ class _CreateDemoRequestPageState extends State with Tick List attachmentSection() { return [ InfoHeader16Widget('Attachments'.addTranslation), - SingleItemDropDownMenu( - context: context, - height: 56.toScreenHeight, - title: "Document Type", - initialValue: demoDocumentLookup, - showShadow: false, - validator: (value) { - if (value == null) return "Mandatory"; - return null; - }, - backgroundColor: AppColor.fieldBgColor(context), - showAsBottomSheet: true, - onSelect: (value) { - demoDocumentLookup = value; - setState(() {}); - }, - ), + // SingleItemDropDownMenu( + // context: context, + // height: 56.toScreenHeight, + // title: "Document Type", + // initialValue: demoDocumentLookup, + // showShadow: false, + // validator: (value) { + // if (value == null) return "Mandatory"; + // return null; + // }, + // backgroundColor: AppColor.fieldBgColor(context), + // showAsBottomSheet: true, + // onSelect: (value) { + // demoDocumentLookup = value; + // setState(() {}); + // }, + // ), AttachmentPicker( label: context.translation.attachments, attachment: _attachments, @@ -520,11 +519,11 @@ class _CreateDemoRequestPageState extends State with Tick enabled: demoDocumentLookup != null, documentType: demoDocumentLookup, showAsListView: true, - buttonIcon: 'image-plus'.toSvgAsset(color: (AppColor.primary10).withOpacity(demoDocumentLookup != null ? 1 : .4)), - onChange: (attachments) { - _attachments = attachments; - setState(() {}); - }, + buttonIcon: 'image-plus'.toSvgAsset(color: (AppColor.primary10)), + // onChange: (attachments) { + // _attachments = attachments; + // setState(() {}); + // }, ), ]; } @@ -537,7 +536,12 @@ class _CreateDemoRequestPageState extends State with Tick _demoFormModel.demoAttachment = []; for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _demoFormModel.demoAttachment?.add(DemoAttachments(id: 0, attachmentName: fileName, demoRequestId: 0, documentTypeId: item.documentTypeId!.id!)); + _demoFormModel.demoAttachment?.add(GenericAttachmentModel( + id: 0, + name: fileName, + moduleReferenceId: 0, + documentType: item.documentType, + )); } Utils.showLoading(context); DemoProvider demoProvider = Provider.of(context, listen: false); diff --git a/lib/modules/demo_module/demo_detail_view_page.dart b/lib/modules/demo_module/demo_detail_view_page.dart index 6d98e438..3278a6fb 100644 --- a/lib/modules/demo_module/demo_detail_view_page.dart +++ b/lib/modules/demo_module/demo_detail_view_page.dart @@ -6,6 +6,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/enums/demo_request_step.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; import 'package:test_sa/models/module_permissions_model.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; @@ -91,8 +92,8 @@ class _DemoDetailViewPageState extends State { if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center; if (snapshot.data == null) return const NoDataFound().center; - List allAttachments = snapshot.data!.demoAttachments! ?? []; - List suppAttachments = snapshot.data!.supplierDemoAttachments! ?? []; + List allAttachments = snapshot.data!.demoAttachments! ?? []; + List suppAttachments = snapshot.data!.supplierDemoAttachments! ?? []; DemoRequestModel demoData = snapshot.data!; @@ -127,7 +128,7 @@ class _DemoDetailViewPageState extends State { InfoHeader16Widget("Attachments"), FilesList( showAsListView: true, - images: allAttachments.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(), types: allAttachments.map((e) => e.documentType?.name ?? '').toList()), ], if (suppAttachments.isNotEmpty) ...[ @@ -135,8 +136,8 @@ class _DemoDetailViewPageState extends State { InfoHeader16Widget("Supplier Attachments"), FilesList( showAsListView: true, - images: suppAttachments.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList(), - types: suppAttachments.map((e) => e.documentType?.name ?? '').toList()), + images: suppAttachments.whereType().map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(), + types: suppAttachments.whereType().map((e) => e.documentType?.name ?? '').toList()), ], ], ).toShadowContainer(context, padding: 12), diff --git a/lib/modules/demo_module/demo_document_lookup_provider.dart b/lib/modules/demo_module/demo_document_lookup_provider.dart index 2078b412..d16f222b 100644 --- a/lib/modules/demo_module/demo_document_lookup_provider.dart +++ b/lib/modules/demo_module/demo_document_lookup_provider.dart @@ -6,7 +6,7 @@ import 'package:test_sa/providers/loading_list_notifier.dart'; import '../../controllers/api_routes/api_manager.dart'; import '../../controllers/api_routes/urls.dart'; import '../../models/lookup.dart'; - +///TODO need to remove this when we have real api for demo document types lookup class DemoDocumentLookupProvider extends LoadingListNotifier { @override Future getData({int? id}) async { @@ -36,3 +36,4 @@ class DemoDocumentLookupProvider extends LoadingListNotifier { } } } + diff --git a/lib/modules/demo_module/models/demo_attachment_model.dart b/lib/modules/demo_module/models/demo_attachment_model.dart index ecc6475e..37c76e8a 100644 --- a/lib/modules/demo_module/models/demo_attachment_model.dart +++ b/lib/modules/demo_module/models/demo_attachment_model.dart @@ -1,31 +1,33 @@ -import 'package:test_sa/models/lookup.dart'; +//TODO : need to remove this class -class DemoAttachments { - int? id; - num? demoRequestId; - num? documentTypeId; - Lookup? documentType; - String? attachmentName; - String? originalName; - - DemoAttachments({this.id, this.documentTypeId, this.documentType, this.attachmentName, this.demoRequestId, this.originalName}); - - DemoAttachments.fromJson(dynamic json) { - id = json['id']; - documentTypeId = json['documentTypeId']; - documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; - demoRequestId = json['demoRequestId']; - attachmentName = json['attachmentName']; - originalName = json['originalName']; - } - - Map toJson() { - final map = {}; - map['id'] = id; - map['documentTypeId'] = documentTypeId; - map['attachmentName'] = attachmentName; - map['demoRequestId'] = demoRequestId; - map['originalName'] = originalName; - return map; - } -} +// import 'package:test_sa/models/lookup.dart'; +// +// class DemoAttachments { +// int? id; +// num? demoRequestId; +// Lookup? documentType; +// String? attachmentName; +// String? originalName; +// +// DemoAttachments({this.id, this.documentType, this.attachmentName, this.demoRequestId, this.originalName}); +// +// DemoAttachments.fromJson(dynamic json) { +// id = json['id']; +// documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; +// demoRequestId = json['demoRequestId']; +// attachmentName = json['attachmentName']; +// originalName = json['originalName']; +// } +// +// Map toJson() { +// final map = {}; +// map['id'] = id; +// if(documentType!=null){ +// map['documentTypeId'] = documentType?.id; +// } +// map['attachmentName'] = attachmentName; +// map['demoRequestId'] = demoRequestId; +// map['originalName'] = originalName; +// return map; +// } +// } diff --git a/lib/modules/demo_module/models/demo_form_model.dart b/lib/modules/demo_module/models/demo_form_model.dart index c591dd98..4adc1970 100644 --- a/lib/modules/demo_module/models/demo_form_model.dart +++ b/lib/modules/demo_module/models/demo_form_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; import 'package:test_sa/models/new_models/floor.dart'; @@ -32,7 +33,7 @@ class DemoFormModel { Rooms? room; SuppEngineerWorkOrders? supEngineer; SupplierDetails? vendor; - List? demoAttachment; + List? demoAttachment; bool demoEaluationAcknowledge; bool acknowledgeNotEquipment; @@ -87,34 +88,7 @@ class DemoFormModel { "demoEaluationAcknowledge": demoEaluationAcknowledge, "acknowledgeNotEquipment": acknowledgeNotEquipment, "demoAttachments": - // [ - // { - // "id": 3, - // // "documentType": { - // // "id": 7748, - // // "name": "February", - // // "value": 2 - // // }, - // "documentTypeId": 7748, - // "attachmentName": "6c9f50b0-1c92-4ae9-ae64-7c284c61ea72.jpg", - // "originalName": "scaled_d245df97-1289-4d0c-92a0-569abedfb0db8154518103327960943.jpg", - // "demoRequestId": 3 - // }, - // { - // "id": 4, - // // "documentType": { - // // "id": 7748, - // // "name": "February", - // // "value": 2 - // // }, - // "documentTypeId": 7748, - // "attachmentName": "346e04f6-0f9b-4004-ad85-4cdbf8318f7c.jpg", - // "originalName": "scaled_85790b6c-7b16-46e6-891c-11c316d5897a2973693360957767376.jpg", - // "demoRequestId": 3 - // } - // ] - - demoAttachment != null ? demoAttachment!.map((v) => v.toJson()).toList() : [], + demoAttachment != null ? demoAttachment!.map((v) => v.toDemoJson()).toList() : [], }; } @@ -123,7 +97,7 @@ class DemoFormModel { "id": id, "supplierId": vendor?.id, "suppPersonId": supEngineer?.id, - "demoAttachments": demoAttachment != null ? demoAttachment!.map((v) => v.toJson()).toList() : [], + "demoAttachments": demoAttachment != null ? demoAttachment!.whereType().map((v) => v.toDemoJson()).toList() : [], }; } } diff --git a/lib/modules/demo_module/models/demo_request_model.dart b/lib/modules/demo_module/models/demo_request_model.dart index 2c07f111..856ede80 100644 --- a/lib/modules/demo_module/models/demo_request_model.dart +++ b/lib/modules/demo_module/models/demo_request_model.dart @@ -1,8 +1,8 @@ import 'package:test_sa/models/device/asset_by_id_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; import 'package:test_sa/models/service_request/supplier_details.dart'; -import 'package:test_sa/modules/demo_module/models/demo_attachment_model.dart'; import 'package:test_sa/modules/loan_module/models/medical_department_model.dart'; class DemoRequestModel { @@ -29,8 +29,8 @@ class DemoRequestModel { SuppEngineerWorkOrders? suppPerson; Lookup? status; Lookup? endUserStatus; - List? demoAttachments; - List? supplierDemoAttachments; + List? demoAttachments; + List? supplierDemoAttachments; dynamic demoAsset; dynamic demoInstallationTaskJob; dynamic demoPullOutTaskJob; @@ -96,8 +96,8 @@ class DemoRequestModel { suppPerson = json['suppPerson'] != null ? (SuppEngineerWorkOrders.fromJson(json['suppPerson'])) : null; status = json['status'] != null ? (Lookup.fromJson(json['status'])) : null; endUserStatus = json['endUserStatus'] != null ? (Lookup.fromJson(json['endUserStatus'])) : null; - demoAttachments = json['demoAttachments'] != null ? (json['demoAttachments'] as List).map((e) => DemoAttachments.fromJson(e)).toList() : null; - supplierDemoAttachments = json['supplierDemoAttachments'] != null ? (json['supplierDemoAttachments'] as List).map((e) => DemoAttachments.fromJson(e)).toList() : null; + demoAttachments = json['demoAttachments'] != null ? (json['demoAttachments'] as List).map((e) => GenericAttachmentModel.fromDemoJson(e)).toList() : null; + supplierDemoAttachments = json['supplierDemoAttachments'] != null ? (json['supplierDemoAttachments'] as List).map((e) => GenericAttachmentModel.fromDemoJson(e)).toList() : null; demoAsset = json['demoAsset']; demoInstallationTaskJob = json['demoInstallationTaskJob']; demoPullOutTaskJob = json['demoPullOutTaskJob']; @@ -124,8 +124,8 @@ class DemoRequestModel { "demoPeriodId": demoPeriod?.id, "supplierId": supplier?.id, "suppPersonId": suppPerson?.id, - "demoAttachments": demoAttachments != null ? demoAttachments!.map((v) => v.toJson()).toList() : [], - "supplierDemoAttachments": supplierDemoAttachments != null ? supplierDemoAttachments!.map((v) => v.toJson()).toList() : [], + "demoAttachments": demoAttachments != null ? demoAttachments!.whereType().map((v) => v.toDemoJson()).toList() : [], + "supplierDemoAttachments": supplierDemoAttachments != null ? supplierDemoAttachments!.whereType().map((v) => v.toDemoJson()).toList() : [], }; } } diff --git a/lib/modules/demo_module/update_demo-request_view.dart b/lib/modules/demo_module/update_demo-request_view.dart index 02dae2d2..0e7c3913 100644 --- a/lib/modules/demo_module/update_demo-request_view.dart +++ b/lib/modules/demo_module/update_demo-request_view.dart @@ -20,7 +20,6 @@ import 'package:test_sa/models/service_request/supp_engineer_work_orders.dart'; import 'package:test_sa/models/service_request/supplier_details.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/demo_module/models/demo_attachment_model.dart'; import 'package:test_sa/modules/demo_module/models/demo_request_model.dart'; import 'package:test_sa/modules/demo_module/provider/demo_period_lookup_provider.dart'; import 'package:test_sa/modules/demo_module/provider/demo_provider.dart'; @@ -161,9 +160,9 @@ class _UpdateDemoRequestViewState extends State with Tick attachments.clear(); if (widget.dataModel.demoAttachments?.isNotEmpty ?? false) { for (final item in widget.dataModel.demoAttachments!) { - if ((item.attachmentName ?? '').isNotEmpty) { + if ((item.name ?? '').isNotEmpty) { attachments.add( - GenericAttachmentModel(name: item.attachmentName, id: item.id ?? 0, originalName: item.originalName, documentTypeId: item.documentType), + GenericAttachmentModel(name: item.name, id: item.id ?? 0, originalName: item.originalName, documentType: item.documentType), ); } } @@ -201,33 +200,35 @@ class _UpdateDemoRequestViewState extends State with Tick 16.height, "Attachments".bodyText(context).custom(color: AppColor.black10), 8.height, - SingleItemDropDownMenu( - context: context, - height: 56.toScreenHeight, - title: "Document Type", - initialValue: demoDocumentLookup, - showShadow: false, - validator: (value) { - if (value == null) return "Mandatory"; - return null; - }, - backgroundColor: AppColor.fieldBgColor(context), - showAsBottomSheet: true, - onSelect: (value) { - demoDocumentLookup = value; - setState(() {}); - }, - ), - 16.height, + + ///Need to confirm we can use same lookup.. + // SingleItemDropDownMenu( + // context: context, + // height: 56.toScreenHeight, + // title: "Document Type", + // initialValue: demoDocumentLookup, + // showShadow: false, + // validator: (value) { + // if (value == null) return "Mandatory"; + // return null; + // }, + // backgroundColor: AppColor.fieldBgColor(context), + // showAsBottomSheet: true, + // onSelect: (value) { + // demoDocumentLookup = value; + // setState(() {}); + // }, + // ), + // 16.height, AttachmentPicker( label: context.translation.attachments, attachment: attachments, buttonColor: AppColor.black10.withOpacity(demoDocumentLookup != null ? 1 : .4), onlyImages: false, - documentType: demoDocumentLookup, - enabled: demoDocumentLookup != null, + // documentType: demoDocumentLookup, + // enabled: demoDocumentLookup != null, showAsListView: true, - buttonIcon: 'image-plus'.toSvgAsset(color: (AppColor.primary10).withOpacity(demoDocumentLookup != null ? 1 : .4)), + buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), ), ], ).toShadowContainer(context, borderRadius: 20), @@ -615,7 +616,13 @@ class _UpdateDemoRequestViewState extends State with Tick for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; //Todo need to pass attachmentType id as well. - _demoFormModel.demoAttachment?.add(DemoAttachments(id: item.id, demoRequestId: _demoFormModel.id ?? 0, attachmentName: fileName,originalName: fileName, documentTypeId: item.documentTypeId!.id)); + _demoFormModel.demoAttachment?.add(GenericAttachmentModel( + id: item.id, + name: fileName, + originalName: fileName, + moduleReferenceId: _demoFormModel.id ?? 0, + documentType: item.documentType, + )); } Utils.showLoading(context); DemoProvider demoProvider = Provider.of(context, listen: false); diff --git a/lib/modules/incident_module/create_incident_request_page.dart b/lib/modules/incident_module/create_incident_request_page.dart index d1535400..562bedfb 100644 --- a/lib/modules/incident_module/create_incident_request_page.dart +++ b/lib/modules/incident_module/create_incident_request_page.dart @@ -41,7 +41,6 @@ import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; import '../../models/new_models/department.dart'; import '../../new_views/swipe_module/dialoge/info_dialog.dart'; import 'flow_medical_department_provider.dart'; -import 'incident_attachment_model.dart'; class CreateIncidentRequestPage extends StatefulWidget { static const String id = "/create-incident"; @@ -694,16 +693,16 @@ class _CreateIncidentRequestPageState extends State { payload["occurrenceDate"] = occurrenceDate!.toIso8601String(); _formKey.currentState!.save(); - List attachmentList = []; + List attachmentList = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - attachmentList.add(IncidentAttachments(id: 0, attachmentName: fileName, incidentId: 0)); + attachmentList.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: 0,documentType: item.documentType)); } Utils.showLoading(context); IncidentProvider incidentProvider = Provider.of(context, listen: false); - payload["incidentAttachments"] = attachmentList.map((v) => v.toJson()).toList(); + payload["incidentAttachments"] = attachmentList.map((v) => v.toIncidentJson()).toList(); bool isSuccess = await incidentProvider.addIncidentRequest(payload); Utils.hideLoading(context); if (isSuccess) { diff --git a/lib/modules/incident_module/incident_attachment_model.dart b/lib/modules/incident_module/incident_attachment_model.dart index bf1eabc9..2edd8811 100644 --- a/lib/modules/incident_module/incident_attachment_model.dart +++ b/lib/modules/incident_module/incident_attachment_model.dart @@ -1,24 +1,26 @@ -class IncidentAttachments { - num? id; - num? incidentId; - String? attachmentName; - String? attachmentDescription; +//TODO : need to delete this - IncidentAttachments({this.id, this.attachmentName, this.incidentId, this.attachmentDescription}); - - IncidentAttachments.fromJson(dynamic json) { - id = json['id']; - incidentId = json['incidentId']; - attachmentName = json['attachmentName']; - attachmentDescription = json['attachmentDescription']; - } - - Map toJson() { - final map = {}; - map['id'] = id; - map['attachmentName'] = attachmentName; - map['incidentId'] = incidentId; - map['attachmentDescription'] = attachmentDescription; - return map; - } -} +// class IncidentAttachments { +// num? id; +// num? incidentId; +// String? attachmentName; +// String? attachmentDescription; +// +// IncidentAttachments({this.id, this.attachmentName, this.incidentId, this.attachmentDescription}); +// +// IncidentAttachments.fromJson(dynamic json) { +// id = json['id']; +// incidentId = json['incidentId']; +// attachmentName = json['attachmentName']; +// attachmentDescription = json['attachmentDescription']; +// } +// +// Map toJson() { +// final map = {}; +// map['id'] = id; +// map['attachmentName'] = attachmentName; +// map['incidentId'] = incidentId; +// map['attachmentDescription'] = attachmentDescription; +// return map; +// } +// } diff --git a/lib/modules/incident_module/incident_data_model.dart b/lib/modules/incident_module/incident_data_model.dart index 7c9f3ba7..82ae1306 100644 --- a/lib/modules/incident_module/incident_data_model.dart +++ b/lib/modules/incident_module/incident_data_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/incident_module/incident_attachment_model.dart'; class IncidentDataModel { @@ -73,7 +74,7 @@ class IncidentDataModel { String? approvalSignature; String? occurrenceDate; String? createdDate; - List? incidentAttachments; + List? incidentAttachments; int? workOrderId; String? workOrderNo; @@ -230,9 +231,9 @@ class IncidentDataModel { workOrderId = json['workOrderId']; workOrderNo = json['workOrderNo']; if (json['incidentAttachments'] != null) { - incidentAttachments = []; + incidentAttachments = []; json['incidentAttachments'].forEach((v) { - incidentAttachments!.add(IncidentAttachments.fromJson(v)); + incidentAttachments!.add(GenericAttachmentModel.fromIncidentJson(v)); }); } } @@ -314,7 +315,7 @@ class IncidentDataModel { data['workOrderId'] = this.workOrderId; data['workOrderNo'] = this.workOrderNo; if (this.incidentAttachments != null) { - data['incidentAttachments'] = this.incidentAttachments!.map((v) => v.toJson()).toList(); + data['incidentAttachments'] = this.incidentAttachments!.map((v) => v.toIncidentJson()).toList(); } return data; } diff --git a/lib/modules/incident_module/incident_detail_page.dart b/lib/modules/incident_module/incident_detail_page.dart index 4f9ade6e..88ebd029 100644 --- a/lib/modules/incident_module/incident_detail_page.dart +++ b/lib/modules/incident_module/incident_detail_page.dart @@ -9,6 +9,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/cm_module/cm_detail_page.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/incident_module/incident_attachment_model.dart'; @@ -39,7 +40,7 @@ class IncidentDetailPage extends StatelessWidget { if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center; if (snapshot.data == null) return const NoDataFound().center; - List allAttachments = snapshot.data!.incidentAttachments!; + List allAttachments = (snapshot.data!.incidentAttachments ?? []).whereType().toList(); return SingleChildScrollView( padding: const EdgeInsets.all(16), @@ -70,7 +71,7 @@ class IncidentDetailPage extends StatelessWidget { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []), + FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context), diff --git a/lib/modules/internal_audit_module/models/engineer_data_model.dart b/lib/modules/internal_audit_module/models/engineer_data_model.dart index dbb34d24..b21ec833 100644 --- a/lib/modules/internal_audit_module/models/engineer_data_model.dart +++ b/lib/modules/internal_audit_module/models/engineer_data_model.dart @@ -1,4 +1,4 @@ -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; class EngineerData { int? id; @@ -9,7 +9,7 @@ class EngineerData { bool? isComplete; int? statusId; int? requestId; - List? attachments; + List? attachments; EngineerData({ this.id, @@ -32,7 +32,7 @@ class EngineerData { isComplete = json['isComplete']; statusId = json['statusId']; requestId = json['requestId']; - attachments = json['attachments'] != null ? (json['attachments'] as List).map((e) => InternalAuditAttachments.fromJson(e)).toList() : []; + attachments = json['attachments'] != null ? (json['attachments'] as List).map((e) => GenericAttachmentModel.fromInternalAuditJson(e)).toList() : []; } Map toJson() { @@ -46,7 +46,7 @@ class EngineerData { data['statusId'] = statusId; data['requestId'] = requestId; if (attachments != null) { - data['attachments'] = attachments!.map((e) => e.toJson()).toList(); + data['attachments'] = attachments!.whereType().map((e) => e.toInternalAuditJson()).toList(); } return data; } diff --git a/lib/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart b/lib/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart index 1e62dd1d..32dc2a08 100644 --- a/lib/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart +++ b/lib/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart @@ -1,6 +1,5 @@ - import 'package:test_sa/models/timer_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/engineer_data_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/internal_audit_timer_model.dart'; class EquipmentInternalAuditDataModel { @@ -15,7 +14,7 @@ class EquipmentInternalAuditDataModel { dynamic manufacture; String? remarks; List? equipmentsFindings; - List? attachments; + List? attachments; EngineerData? engineerData; @@ -54,7 +53,7 @@ class EquipmentInternalAuditDataModel { } attachments = json['attachments'] != null ? (json['attachments'] as List) - .map((e) => InternalAuditAttachments.fromJson(e)) + .map((e) => GenericAttachmentModel.fromInternalAuditJson(e)) .where((e) => e.name != null) // optional filter if you want to skip null names .toList() : []; @@ -86,7 +85,9 @@ class EquipmentInternalAuditDataModel { data['equipmentsFindings'] = equipmentsFindings!.map((v) => v.toJson()).toList(); } - data['attachments'] = attachments; + if (attachments != null) { + data['attachments'] = attachments!.whereType().map((v) => v.toInternalAuditJson()).toList(); + } if (engineerData != null) data['engineerData'] = engineerData!.toJson(); return data; } diff --git a/lib/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart b/lib/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart index e6a79e91..c23d9724 100644 --- a/lib/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart +++ b/lib/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart @@ -5,7 +5,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/models/device/asset.dart'; import 'package:test_sa/models/fault_description.dart'; import 'package:test_sa/models/lookup.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; class EquipmentInternalAuditFormModel { int? id=0; @@ -14,7 +14,7 @@ class EquipmentInternalAuditFormModel { String? woOrderNo; List? devicePhotos; List findings =[]; - List attachments = []; + List attachments = []; String? remarks; Asset? device; EquipmentInternalAuditFormModel({ @@ -32,7 +32,7 @@ class EquipmentInternalAuditFormModel { 'assetId': device?.id, 'auditorId': auditorId, 'findings': findings.map((e) => {'findingId': e.value}).toList(), - 'attachments': attachments.map((e) => e.toJson()).toList(), + 'attachments': attachments.whereType().map((e) => e.toInternalAuditJson()).toList(), 'remarks': remarks, }; } diff --git a/lib/modules/internal_audit_module/models/internal_audit_attachment_model.dart b/lib/modules/internal_audit_module/models/internal_audit_attachment_model.dart index f2b14df1..12adfa2d 100644 --- a/lib/modules/internal_audit_module/models/internal_audit_attachment_model.dart +++ b/lib/modules/internal_audit_module/models/internal_audit_attachment_model.dart @@ -1,26 +1,32 @@ -import 'dart:developer'; - -class InternalAuditAttachments { - InternalAuditAttachments({this.id, this.originalName, this.name, this.createdBy}); - - int? id; - String? name; - String? originalName; - String? createdBy; - - InternalAuditAttachments.fromJson(Map json) { - id = json['id']; - name = (json['name'] != null && !json['name'].toString().startsWith('data:image/jpeg')) ? json['name'] : null; - originalName = json['originalName']; - createdBy = json['createdBy']; - } - - Map toJson() { - final Map data = {}; - data['id'] = id; - data['name'] = name; - data['originalName'] = originalName; - // data['createdBy'] = createdBy; - return data; - } -} +//TODO : need to remove this class. +// import 'dart:developer'; +// +// import 'package:test_sa/models/lookup.dart'; +// +// class InternalAuditAttachments { +// InternalAuditAttachments({this.id, this.originalName, this.name, this.createdBy,this.documentType}); +// +// int? id; +// String? name; +// String? originalName; +// String? createdBy; +// Lookup ? documentType; +// +// InternalAuditAttachments.fromJson(Map json) { +// id = json['id']; +// name = (json['name'] != null && !json['name'].toString().startsWith('data:image/jpeg')) ? json['name'] : null; +// originalName = json['originalName']; +// createdBy = json['createdBy']; +// documentType =json['documentType']; +// } +// +// Map toJson() { +// final Map data = {}; +// data['id'] = id; +// data['name'] = name; +// data['originalName'] = originalName; +// data['documentTypeId'] = documentType?.id; +// // data['createdBy'] = createdBy; +// return data; +// } +// } diff --git a/lib/modules/internal_audit_module/models/system_internal_audit_data_model.dart b/lib/modules/internal_audit_module/models/system_internal_audit_data_model.dart index 0546ccdc..32d66d87 100644 --- a/lib/modules/internal_audit_module/models/system_internal_audit_data_model.dart +++ b/lib/modules/internal_audit_module/models/system_internal_audit_data_model.dart @@ -1,6 +1,6 @@ import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/internal_audit_module/models/engineer_data_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_form_model.dart'; class SystemInternalAuditDataModel { @@ -19,7 +19,7 @@ class SystemInternalAuditDataModel { String? createdDate; String? modifiedBy; String? modifiedDate; - List? attachments; + List? attachments; EngineerData? engineerData; SystemInternalAuditDataModel({ @@ -60,7 +60,7 @@ class SystemInternalAuditDataModel { modifiedDate = json['modifiedDate']; attachments = json['attachments'] != null ? (json['attachments'] as List) - .map((e) => InternalAuditAttachments.fromJson(e)) + .map((e) => GenericAttachmentModel.fromInternalAuditJson(e)) .where((e) => e.name != null) // optional filter if you want to skip null names .toList() : []; @@ -84,6 +84,9 @@ class SystemInternalAuditDataModel { data['createdDate'] = createdDate; data['modifiedBy'] = modifiedBy; data['modifiedDate'] = modifiedDate; + if (attachments != null) { + data['attachments'] = attachments!.whereType().map((v) => v.toInternalAuditJson()).toList(); + } if (engineerData != null) data['engineerData'] = engineerData!.toJson(); return data; } diff --git a/lib/modules/internal_audit_module/models/system_internal_audit_form_model.dart b/lib/modules/internal_audit_module/models/system_internal_audit_form_model.dart index 3fda34d0..f3de4f53 100644 --- a/lib/modules/internal_audit_module/models/system_internal_audit_form_model.dart +++ b/lib/modules/internal_audit_module/models/system_internal_audit_form_model.dart @@ -1,7 +1,7 @@ import 'dart:developer'; import 'package:test_sa/models/lookup.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; class SystemInternalAuditFormModel { int? id; @@ -13,7 +13,7 @@ class SystemInternalAuditFormModel { int? correctiveMaintenanceId; int? planPreventiveVisitId; int? assetTransferId; - List? attachments = []; + List? attachments = []; int? taskJobId; int? taskAlertJobId; int? gasRefillId; @@ -56,7 +56,7 @@ class SystemInternalAuditFormModel { 'gasRefillId': gasRefillId, 'planRecurrentTaskId': planRecurrentTaskId, 'statusId': statusId, - 'attachments': attachments?.map((e) => e.toJson()).toList(), + 'attachments': attachments?.whereType().map((e) => e.toInternalAuditJson()).toList(), }; } } diff --git a/lib/modules/internal_audit_module/models/update_audit_form_model.dart b/lib/modules/internal_audit_module/models/update_audit_form_model.dart index 6942d51f..bdf9ec00 100644 --- a/lib/modules/internal_audit_module/models/update_audit_form_model.dart +++ b/lib/modules/internal_audit_module/models/update_audit_form_model.dart @@ -1,5 +1,5 @@ import 'package:test_sa/models/timer_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/internal_audit_timer_model.dart'; class AuditFormModel { @@ -10,7 +10,7 @@ class AuditFormModel { DateTime? startTime; DateTime? endTime; double? totalHours; - List? attachments; + List? attachments; bool? isComplete; TimerModel? auditTimerModel = TimerModel(); List? auditTimers = []; @@ -40,7 +40,7 @@ class AuditFormModel { endTime = json['endTime'] != null ? DateTime.tryParse(json['endTime']) : null; totalHours = json['totalHours']?.toDouble(); if (json['attachments'] != null) { - attachments = (json['attachments'] as List).map((e) => InternalAuditAttachments.fromJson(e)).toList(); + attachments = (json['attachments'] as List).map((e) => GenericAttachmentModel.fromInternalAuditJson(e)).toList(); } isComplete = json['isComplete']; } @@ -54,7 +54,7 @@ class AuditFormModel { 'endTime': endTime?.toIso8601String(), // 'auditTimer': auditTimers, 'totalHours': totalHours, - 'attachments': attachments?.map((e) => e.toJson()).toList(), + 'attachments': attachments?.whereType().map((e) => e.toInternalAuditJson()).toList(), 'isComplete': isComplete, }; } diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart index 99889178..7d75c9ef 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart @@ -12,8 +12,8 @@ import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_form_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_checklist_provider.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; @@ -119,6 +119,7 @@ class _CreateEquipmentInternalAuditFormState extends State const AppLazyLoading()); _equipmentinternalAuditModel.auditorId = context.userProvider.user?.userID; diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart index b617db05..5e0a8a9b 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart @@ -10,7 +10,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; @@ -41,7 +41,7 @@ class _EquipmentInternalAuditDetailPageState extends State allAttachments = []; + List allAttachments = []; @override void initState() { @@ -56,8 +56,8 @@ class _EquipmentInternalAuditDetailPageState extends State() ?? []), + ...(model?.engineerData?.attachments?.whereType() ?? []), ]; } diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart index 9c5be1d2..b25e0aef 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart @@ -14,10 +14,9 @@ import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/timer_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_timer_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/update_audit_form_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/equipment_internal_audit_data_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/modules/internal_audit_module/models/update_audit_form_model.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; @@ -62,7 +61,7 @@ class _UpdateEquipmentInternalAuditPageState extends State GenericAttachmentModel(id: e.id?.toInt() ?? 0, name: e.name!)).toList() ?? []; + _attachments = widget.model?.engineerData?.attachments?.whereType().map((e) => GenericAttachmentModel(id: e.id?.toInt() ?? 0, name: e.name ?? '')).toList() ?? []; calculateWorkingTime(); } @@ -129,9 +128,10 @@ class _UpdateEquipmentInternalAuditPageState extends State(context, listen: false); if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); - _model.attachments=[]; + _model.attachments = []; for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _model.attachments?.add(InternalAuditAttachments(id: item.id, name: fileName)); + _model.attachments?.add(GenericAttachmentModel( + id: item.id, + name: fileName, + documentType: item.documentType, + )); } showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); _model.auditorId = context.userProvider.user?.userID; diff --git a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart index 7e52f0cf..a473a75a 100644 --- a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart @@ -9,7 +9,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart'; import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart'; @@ -39,7 +39,7 @@ class _SystemInternalAuditDetailPageState extends State allAttachments = []; + List allAttachments = []; @override void initState() { @@ -54,8 +54,8 @@ class _SystemInternalAuditDetailPageState extends State() ?? []), + ...(model?.engineerData?.attachments?.whereType() ?? []), ]; } diff --git a/lib/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart b/lib/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart index 2c8541e0..3e68d28b 100644 --- a/lib/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart +++ b/lib/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart @@ -14,10 +14,8 @@ import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/timer_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_timer_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/update_audit_form_model.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/provider/internal_audit_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; @@ -62,7 +60,7 @@ class _UpdateSystemInternalAuditPageState extends State GenericAttachmentModel(id: e.id?.toInt() ?? 0, name: e.name!)).toList() ?? []; + _attachments = widget.model?.engineerData?.attachments?.whereType().map((e) => GenericAttachmentModel(id: e.id?.toInt() ?? 0, name: e.name ?? '')).toList() ?? []; calculateWorkingTime(); } @@ -130,8 +128,9 @@ class _UpdateSystemInternalAuditPageState extends State json) { - loanId = json['loanId']; - attachmentName = json['attachmentName']; - loanAttachmentTypeId = json['loanAttachmentTypeId']; - attachmentDescription = json['attachmentDescription']; - id = json['id']; - createdBy = json['createdBy']; - createdDate = json['createdDate']; - modifiedBy = json['modifiedBy']; - modifiedDate = json['modifiedDate']; - } - - Map toJson() { - final Map data = new Map(); - data['loanId'] = this.loanId; - data['attachmentName'] = this.attachmentName; - data['loanAttachmentTypeId'] = this.loanAttachmentTypeId; - data['attachmentDescription'] = this.attachmentDescription; - data['id'] = this.id; - data['createdBy'] = this.createdBy; - data['createdDate'] = this.createdDate; - data['modifiedBy'] = this.modifiedBy; - data['modifiedDate'] = this.modifiedDate; - return data; - } -} +//TODO need to delete this . +// class LoanAttachmentModel { +// int? loanId; +// String? attachmentName; +// int? loanAttachmentTypeId; +// String? attachmentDescription; +// int? id; +// String? createdBy; +// String? createdDate; +// String? modifiedBy; +// String? modifiedDate; +// +// LoanAttachmentModel({this.loanId, this.attachmentName, this.loanAttachmentTypeId, this.attachmentDescription, this.id, this.createdBy, this.createdDate, this.modifiedBy, this.modifiedDate}); +// +// LoanAttachmentModel.fromJson(Map json) { +// loanId = json['loanId']; +// attachmentName = json['attachmentName']; +// loanAttachmentTypeId = json['loanAttachmentTypeId']; +// attachmentDescription = json['attachmentDescription']; +// id = json['id']; +// createdBy = json['createdBy']; +// createdDate = json['createdDate']; +// modifiedBy = json['modifiedBy']; +// modifiedDate = json['modifiedDate']; +// } +// +// Map toJson() { +// final Map data = new Map(); +// data['loanId'] = this.loanId; +// data['attachmentName'] = this.attachmentName; +// data['loanAttachmentTypeId'] = this.loanAttachmentTypeId; +// data['attachmentDescription'] = this.attachmentDescription; +// data['id'] = this.id; +// data['createdBy'] = this.createdBy; +// data['createdDate'] = this.createdDate; +// data['modifiedBy'] = this.modifiedBy; +// data['modifiedDate'] = this.modifiedDate; +// return data; +// } +// } diff --git a/lib/modules/loan_module/models/loan_form_model.dart b/lib/modules/loan_module/models/loan_form_model.dart index e1722ba7..b8211caa 100644 --- a/lib/modules/loan_module/models/loan_form_model.dart +++ b/lib/modules/loan_module/models/loan_form_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/mapped_sites.dart'; import 'package:test_sa/models/new_models/site.dart'; @@ -24,7 +25,7 @@ class LoanFormModel { SupplierDetails? supplier; SuppEngineerWorkOrders? supEngineer; MedicalDepartmentModel? department; - List? loanAttachment; + List? loanAttachment; MappedSite? mappedSite; TrafDepartment? mappedDepartment; @@ -51,40 +52,6 @@ class LoanFormModel { this.mappedDepartment, }); - //{ - // "id": 0, - // "employeeId": "fa29a9de-1337-4729-b823-68c6ecffdd33", - // "requestorUserID": "fa29a9de-1337-4729-b823-68c6ecffdd33", - // "employeeName": "engineer-dev", - // "employeeEmail": "Engineer_Dev@yahoo.com", - // "positionName": "High", - // "requesterExtensionNumber": "7726", - // "requesterContactNumber": "72132197", - // "siteId": 1, - // "departmentId": 5, - // "loanTypeId": 6448, - // "doctorName": "Doctor A", - // "doctorContact": "0561432451", - // "doctorEmail": "doctor@test.com", - // "itemDescription": "Test item", - // "requestDescription": "Test request", - // "loanPeriodId": 6453, - // "assetId": null, - // "assetNumber": "", - // "assetName": "", - // "assetSerialNumber": "", - // "model": "Model A", - // "manufacturer": "Siemens", - // "vendorName": "Vendor A", - // "vendorRepName": "Vendor Rep A", - // "vendorContact": "0561432455", - // "vendorEmail": "vendor@test.com", - // "loanStatusId": 1, - // "loanAttachments": [], - // "submittedAt": "2025-11-13T12:11:12.673Z", - // "updatedAt": null, - // "cMWOItemId": null - // } Map toJson() { return { @@ -103,50 +70,10 @@ class LoanFormModel { "vendorContact": vendorNumber, "vendorEmail": vendorEmail, "isNewVendor": isNewVendor, - // 'siteId': site?.id, 'siteId': mappedSite?.id, - // 'departmentId': department?.id, 'departmentId': mappedDepartment?.id, - "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toJson()).toList() : [], + "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toLoanJson()).toList() : [], }; } } -class LoanAttachments { - num? id; - num? loanAttachmentTypeId; - num? loanId; - String? attachmentName; - String? attachmentDescription; - - LoanAttachments({this.id, this.loanAttachmentTypeId, this.attachmentName, this.loanId, this.attachmentDescription}); - - LoanAttachments.fromJson(dynamic json) { - id = json['id']; - loanAttachmentTypeId = json['loanAttachmentTypeId']; - loanId = json['loanId']; - attachmentName = json['attachmentName']; - attachmentDescription = json['attachmentDescription']; - } - - // LoanAttachments copyWith({ - // num? id, // Parameter is now nullable - // String? name, // Parameter is now nullable - // String? originalName, // Parameter is now nullable - // }) => - // LoanAttachments( - // id: id ?? this.id, - // name: name ?? this.name, - // originalName: originalName ?? this.originalName, - // ); - - Map toJson() { - final map = {}; - map['id'] = id; - map['loanAttachmentTypeId'] = loanAttachmentTypeId; - map['attachmentName'] = attachmentName; - map['loanId'] = loanId; - map['attachmentDescription'] = attachmentDescription; - return map; - } -} diff --git a/lib/modules/loan_module/models/loan_installation_pullout_form_model.dart b/lib/modules/loan_module/models/loan_installation_pullout_form_model.dart index ff2129db..e4d37276 100644 --- a/lib/modules/loan_module/models/loan_installation_pullout_form_model.dart +++ b/lib/modules/loan_module/models/loan_installation_pullout_form_model.dart @@ -1,14 +1,14 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/timer_model.dart'; -import 'package:test_sa/modules/loan_module/models/loan_form_model.dart'; class LoanInstallationPullOutFormModel { String? snNo; DateTime? date; Uint8List? signature; - List? loanAttachment; + List? loanAttachment; TimerModel? timerModel = TimerModel(); DateTime? startTime; DateTime? endTime; @@ -32,13 +32,11 @@ class LoanInstallationPullOutFormModel { }); Map toJson() { - //Need to check payload parm they need return { - // 'snNo': snNo, 'serialNumber': snNo, 'installationDate': date?.toIso8601String(), 'pulloutDate': date?.toIso8601String(), - "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toJson()).toList() : [], + "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toLoanJson()).toList() : [], "installationSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, "signature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, "pulloutSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, @@ -53,16 +51,11 @@ class LoanInstallationPullOutFormModel { } Map toInstallationJson() { - //Need to check payload parm they need return { - // 'snNo': snNo, 'serialNumber': snNo, 'installationDate': date?.toIso8601String(), - // 'pulloutDate': date?.toIso8601String(), - "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toJson()).toList() : [], + "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toLoanJson()).toList() : [], "installationSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, - // "signature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, - // "pulloutSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, 'startTime': startTime?.toIso8601String(), 'endTime': endTime?.toIso8601String(), 'totalHours': totalHours, @@ -74,15 +67,10 @@ class LoanInstallationPullOutFormModel { } Map toPulloutJson() { - //Need to check payload parm they need return { - // 'snNo': snNo, 'serialNumber': snNo, - // 'installationDate': date?.toIso8601String(), 'pulloutDate': date?.toIso8601String(), - "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toJson()).toList() : [], - // "installationSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, - // "signature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, + "loanAttachments": loanAttachment != null ? loanAttachment!.map((v) => v.toLoanJson()).toList() : [], "pulloutSignature": signature != null ? "${DateTime.now().toIso8601String()}.png|${base64Encode(signature!)}" : null, 'startTime': startTime?.toIso8601String(), 'endTime': endTime?.toIso8601String(), diff --git a/lib/modules/loan_module/models/loan_request_model.dart b/lib/modules/loan_module/models/loan_request_model.dart index 1f76cda8..04b097e9 100644 --- a/lib/modules/loan_module/models/loan_request_model.dart +++ b/lib/modules/loan_module/models/loan_request_model.dart @@ -1,3 +1,4 @@ +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'loan_attachment_model.dart'; @@ -34,7 +35,7 @@ class LoanRequestModel { String? vendorRepName; String? vendorContact; String? vendorEmail; - List? loanAttachments; + List? loanAttachments; int? loanStatusId; String? loanStatusName; int? loanStatusValue; @@ -154,11 +155,11 @@ class LoanRequestModel { vendorRepName = json['vendorRepName']; vendorContact = json['vendorContact']; vendorEmail = json['vendorEmail']; - loanAttachments = []; + loanAttachments = []; if (json['loanAttachments'] != null) { - loanAttachments = []; + loanAttachments = []; json['loanAttachments'].forEach((v) { - loanAttachments!.add(new LoanAttachmentModel.fromJson(v)); + loanAttachments!.add(GenericAttachmentModel.fromLoanDetailJson(v)); }); } loanStatusId = json['loanStatusId']; @@ -222,8 +223,8 @@ class LoanRequestModel { data['vendorRepName'] = this.vendorRepName; data['vendorContact'] = this.vendorContact; data['vendorEmail'] = this.vendorEmail; - if (this.loanAttachments != null) { - data['loanAttachments'] = this.loanAttachments!.map((v) => v.toJson()).toList(); + if (loanAttachments != null) { + data['loanAttachments'] = loanAttachments!.map((v) => v.toLoanDetailJson()).toList(); } data['loanStatusId'] = this.loanStatusId; data['loanStatusName'] = this.loanStatusName; diff --git a/lib/modules/loan_module/pages/create_loan_request_page.dart b/lib/modules/loan_module/pages/create_loan_request_page.dart index 6e068eb9..51a7193d 100644 --- a/lib/modules/loan_module/pages/create_loan_request_page.dart +++ b/lib/modules/loan_module/pages/create_loan_request_page.dart @@ -627,7 +627,7 @@ class _CreateLoanRequestPageState extends State with Tick _loanFormModel.loanAttachment = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _loanFormModel.loanAttachment?.add(LoanAttachments(id: 0, attachmentName: fileName, loanId: 0)); + _loanFormModel.loanAttachment?.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: 0)); } Utils.showLoading(context); LoanProvider loanProvider = Provider.of(context, listen: false); diff --git a/lib/modules/loan_module/pages/installation_form_view.dart b/lib/modules/loan_module/pages/installation_form_view.dart index 5ad7e3c4..fa54d82d 100644 --- a/lib/modules/loan_module/pages/installation_form_view.dart +++ b/lib/modules/loan_module/pages/installation_form_view.dart @@ -209,7 +209,7 @@ class _InstallationFormViewState extends State { for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _formData.loanAttachment!.add(LoanAttachments(id: 0, attachmentName: fileName, loanId: widget.loanData?.id)); + _formData.loanAttachment!.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: widget.loanData?.id, documentType: item.documentType)); } Utils.showLoading(context); _formData.loanStatusId = widget.loanData?.loanStatusValue; diff --git a/lib/modules/loan_module/pages/installation_pullout_form_view.dart b/lib/modules/loan_module/pages/installation_pullout_form_view.dart index f94163cc..2bb85358 100644 --- a/lib/modules/loan_module/pages/installation_pullout_form_view.dart +++ b/lib/modules/loan_module/pages/installation_pullout_form_view.dart @@ -217,7 +217,7 @@ class _InstallationPullOutFormViewState extends State(context, listen: false); diff --git a/lib/modules/loan_module/pages/intallation_details_view.dart b/lib/modules/loan_module/pages/intallation_details_view.dart index 8bfd6e8b..3168b679 100644 --- a/lib/modules/loan_module/pages/intallation_details_view.dart +++ b/lib/modules/loan_module/pages/intallation_details_view.dart @@ -84,7 +84,7 @@ class InstallationDetailsView extends StatelessWidget { style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50), ), 8.height, - FilesList(showAsListView: true, images: loanData.loanAttachments?.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []), + FilesList(showAsListView: true, images: loanData.loanAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context, borderRadius: 20), diff --git a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart index 57126edf..8a043dbd 100644 --- a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart +++ b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart @@ -6,6 +6,8 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/modules/loan_module/provider/loan_provider.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/loan_module/models/loan_attachment_model.dart'; @@ -59,7 +61,7 @@ class _LoanEquipmentDetailPageState extends State { if (snapshot.connectionState == ConnectionState.waiting) return CircularProgressIndicator(color: AppColor.loadingColor(context)).center; if (snapshot.data == null) return const NoDataFound().center; - List allAttachments = snapshot.data!.loanAttachments!; + List allAttachments = (snapshot.data!.loanAttachments ?? []).whereType().toList(); return Column(children: [ ListView( @@ -95,7 +97,7 @@ class _LoanEquipmentDetailPageState extends State { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []), + FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context) diff --git a/lib/modules/medical_gas_inspection/update_delivery_notes_page.dart b/lib/modules/medical_gas_inspection/update_delivery_notes_page.dart index 47c77c39..e128002d 100644 --- a/lib/modules/medical_gas_inspection/update_delivery_notes_page.dart +++ b/lib/modules/medical_gas_inspection/update_delivery_notes_page.dart @@ -72,7 +72,7 @@ class _UpdateDeliveryNotesState extends State { deliveryNoteNumber: dataModel.deliveryNote); if (dataModel.deliveryNoteAttachmentDto.isNotEmpty) { - _attachments.addAll(dataModel.deliveryNoteAttachmentDto.map((e) => GenericAttachmentModel(id: e.id, name: e.name)).toList()); + _attachments.addAll(dataModel.deliveryNoteAttachmentDto.map((e) => GenericAttachmentModel(id: e.id, documentType: e.documentType, name: e.name)).toList()); } //Need to Confirm this condition // selectedItemList = dataModel.requestDetailDtos.where((item) => item.deliveredQuantity != null && item.deliveredQuantity! > 0).toList(); @@ -211,8 +211,8 @@ class _UpdateDeliveryNotesState extends State { AttachmentPicker( label: 'Upload Attachment', attachment: _attachments, + showAsListView: true, buttonColor: AppColor.primary10, - // showAsListView: true, onlyImages: false, buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10), ), @@ -331,7 +331,7 @@ class _UpdateDeliveryNotesState extends State { try { for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - formModel.attachments.add(GenericAttachmentModel(id: item.id, name: fileName)); + formModel.attachments.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType)); } } catch (error) { print(error); diff --git a/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart b/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart index b11a0a92..ef50b0df 100644 --- a/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart +++ b/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart @@ -11,7 +11,6 @@ import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/modules/internal_audit_module/models/internal_audit_attachment_model.dart'; import 'package:test_sa/modules/internal_audit_module/models/system_internal_audit_data_model.dart'; import 'package:test_sa/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart'; import 'package:test_sa/modules/internal_audit_module/pages/system_internal_audit/update_system_internal_audit_page.dart'; diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart index a61a8efd..e6301bf6 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/models/ppm/ppm.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -51,7 +52,11 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { ppmProvider.planPreventiveVisit?.preventiveVisitAttachments = []; for (var item in ppmProvider.ppmPlanAttachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - ppmProvider.planPreventiveVisit?.preventiveVisitAttachments?.add(PreventiveVisitAttachments(id: item.id, attachmentName: fileName)); + ppmProvider.planPreventiveVisit?.preventiveVisitAttachments?.add(GenericAttachmentModel( + id: item.id, + name: fileName, + documentType: item.documentType, + )); } ppmProvider.planPreventiveVisit?.preventiveVisitTimers = ppmProvider.planPreventiveVisit?.preventiveVisitTimers ?? []; diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart index 55170e3b..c206bef0 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart @@ -61,7 +61,7 @@ class _WoInfoFormState extends State { calculateWorkingTime(); if (widget.planPreventiveVisit.preventiveVisitAttachments != null && widget.planPreventiveVisit.preventiveVisitAttachments!.isNotEmpty) { ppmProvider.ppmPlanAttachments = []; - ppmProvider.ppmPlanAttachments.addAll(widget.planPreventiveVisit.preventiveVisitAttachments!.map((e) => GenericAttachmentModel(id: e.id, name: e.attachmentName!)).toList()); + ppmProvider.ppmPlanAttachments.addAll(widget.planPreventiveVisit.preventiveVisitAttachments!.whereType().map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '',documentType: e.documentType)).toList()); } }); @@ -350,6 +350,7 @@ class _WoInfoFormState extends State { 16.height, AttachmentPicker( label: context.translation.attachments, + showAsListView: true, attachment: ppmProvider.ppmPlanAttachments, buttonColor: AppColor.black10, onlyImages: false, diff --git a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart index 89c92bc1..8304293f 100644 --- a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart +++ b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart @@ -74,10 +74,10 @@ class _CreateDeviceTransferRequestState extends State attachement = []; + List attachement = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - attachement.add(AssetTransferAttachment(id: item.id, attachmentName: fileName)); + attachement.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType)); } _transferModel.attachments = attachement; @@ -245,6 +245,7 @@ class _CreateDeviceTransferRequestState extends State { if (snapshot.connectionState == ConnectionState.waiting) { return const ALoading(); } else { - _model = snapshot.data as DeviceTransfer?; - _attachments = _model?.assetTransferAttachments?.map((e) => File(e.attachmentName ?? '')).toList() ?? []; + _model = snapshot.data; + _attachments = _model?.assetTransferAttachments?.map((e) => File(e.name ?? '')).toList() ?? []; return _model != null ? Form( key: _formKey, @@ -121,7 +121,7 @@ class _DeviceTransferDetailsState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []), + FilesList(images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ] ], ), diff --git a/lib/modules/tm_module/device_transfer/update_device_transfer.dart b/lib/modules/tm_module/device_transfer/update_device_transfer.dart index fab25250..022c0a53 100644 --- a/lib/modules/tm_module/device_transfer/update_device_transfer.dart +++ b/lib/modules/tm_module/device_transfer/update_device_transfer.dart @@ -116,11 +116,14 @@ class _UpdateDeviceTransferState extends State { _formModel.assetTransferEngineerTimers = _formModel.receiverVisitTimers; } try { + _formModel.assetTransferAttachments ??= []; + List newAttachments = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _formModel.assetTransferAttachments!.add(AssetTransferAttachment(id: item.id, attachmentName: fileName)); - _formModel.attachments = _formModel.assetTransferAttachments; + newAttachments.add(GenericAttachmentModel(id: item.id, documentType: item.documentType, name: fileName)); } + _formModel.assetTransferAttachments = [...?_formModel.assetTransferAttachments, ...newAttachments]; + _formModel.attachments = _formModel.assetTransferAttachments; } catch (error) { print(error); } @@ -204,7 +207,7 @@ class _UpdateDeviceTransferState extends State { @override void initState() { _formModel.fromDetails(widget.model); - attachments = widget.model.assetTransferAttachments?.map((e) => GenericAttachmentModel(id: e.id?.toInt()??0, name: e.attachmentName!)).toList() ?? []; + attachments = widget.model.assetTransferAttachments?.map((e) => GenericAttachmentModel(id: e.id?.toInt()??0, name: e.name!)).toList() ?? []; calculateWorkingTime(); super.initState(); } @@ -293,6 +296,7 @@ class _UpdateDeviceTransferState extends State { 8.height, AttachmentPicker( label: context.translation.attachFiles, + showAsListView: true, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, diff --git a/lib/modules/tm_module/gas_refill/gas_refill_details.dart b/lib/modules/tm_module/gas_refill/gas_refill_details.dart index bbeee78a..3dc4fb3b 100644 --- a/lib/modules/tm_module/gas_refill/gas_refill_details.dart +++ b/lib/modules/tm_module/gas_refill/gas_refill_details.dart @@ -3,14 +3,19 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/controllers/providers/api/gas_refill_provider.dart'; import 'package:test_sa/controllers/providers/api/gas_refill_comments.dart'; import 'package:test_sa/controllers/providers/api/gas_refill_provider.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/new_models/gas_refill_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/cx_module/chat/chat_widget.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; @@ -92,7 +97,7 @@ class _GasRefillDetailsPageState extends State { return const ALoading(); } else if (snap.hasData) { _model = snap.data as GasRefillModel; - _attachments = _model.gasRefillAttachments?.map((e) => File(e.attachmentName ?? '')).toList() ?? []; + _attachments = _model.gasRefillAttachments?.whereType().map((e) => File(e.name ?? '')).toList() ?? []; isDataUpdated = false; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -233,7 +238,7 @@ class _GasRefillDetailsPageState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: _model.gasRefillAttachments?.map((e) => URLs.getFileUrl(e.attachmentName ?? '') ?? '').toList() ?? []), + FilesList(images: _model.gasRefillAttachments?.whereType().where((e) => e.name != null).map((e) => URLs.getFileUrl(e.name!) ?? '').toList() ?? []), ], ], ).expanded, diff --git a/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart b/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart index 6e6e46d3..cb030a1d 100644 --- a/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart +++ b/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart @@ -216,6 +216,7 @@ class _GasRefillRequestFormState extends State { 8.height, AttachmentPicker( label: context.translation.attachFiles, + showAsListView: true, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, @@ -238,7 +239,7 @@ class _GasRefillRequestFormState extends State { _gasModel.gasRefillAttachments = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _gasModel.gasRefillAttachments?.add(GasRefillAttachments(id: item.id, gasRefillId: _gasModel.id ?? 0, attachmentName: fileName)); + _gasModel.gasRefillAttachments?.add(GenericAttachmentModel(id: item.id, moduleReferenceId: _gasModel.id ?? 0, name: fileName, documentType: item.documentType)); } await _gasRefillProvider?.addGasRefillRequest( context: context, diff --git a/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart b/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart index b254dd79..35593f56 100644 --- a/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart +++ b/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart @@ -86,7 +86,7 @@ class _UpdateGasRefillRequestState extends State { } catch (ex) {} } if (_formModel.gasRefillAttachments != null && _formModel.gasRefillAttachments!.isNotEmpty) { - _attachments.addAll(_formModel.gasRefillAttachments!.map((e) => GenericAttachmentModel(id: e.id, name: e.attachmentName!)).toList()); + _attachments.addAll(_formModel.gasRefillAttachments!.whereType().where((e) => e.id != null && e.name != null).map((e) => GenericAttachmentModel(id: e.id, name: e.name, documentType: e.documentType)).toList()); } } @@ -182,7 +182,7 @@ class _UpdateGasRefillRequestState extends State { _formModel.gasRefillAttachments = []; for (var item in _attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _formModel.gasRefillAttachments?.add(GasRefillAttachments(id: item.id, gasRefillId: _formModel.id ?? 0, attachmentName: fileName)); + _formModel.gasRefillAttachments?.add(GenericAttachmentModel(id: item.id, moduleReferenceId: _formModel.id ?? 0, name: fileName, documentType: item.documentType)); } await _gasRefillProvider?.updateGasRefill(status: status, model: _formModel).then((success) { @@ -292,6 +292,7 @@ class _UpdateGasRefillRequestState extends State { AttachmentPicker( label: context.translation.attachFiles, attachment: _attachments, + showAsListView: true, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/tm_module/tasks/create_task_view.dart b/lib/modules/tm_module/tasks/create_task_view.dart index f3aab34c..931c5e68 100644 --- a/lib/modules/tm_module/tasks/create_task_view.dart +++ b/lib/modules/tm_module/tasks/create_task_view.dart @@ -44,7 +44,7 @@ class CreateTaskView extends StatefulWidget { } class _CreateTaskViewState extends State with TickerProviderStateMixin { - final List attachments = []; + List attachments = []; final GlobalKey _formKey = GlobalKey(); final GlobalKey _scaffoldKey = GlobalKey(); List _deviceList = []; @@ -117,13 +117,9 @@ class _CreateTaskViewState extends State with TickerProviderStat label: context.translation.attachImage, attachment: attachments, buttonColor: AppColor.black10, + showAsListView: true, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), - //verify this if not required delete this .. - onChange: (attachments) { - attachments = attachments; - setState(() {}); - }, ), ], ).toShadowContainer(context).paddingAll(16), @@ -457,7 +453,7 @@ class _CreateTaskViewState extends State with TickerProviderStat } for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _addTaskModel?.attachments?.add(TaskJobAttachment(id: item.id, name: fileName)); + _addTaskModel?.attachments?.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType)); } TaskRequestProvider taskRequestProvider = Provider.of(context, listen: false); await taskRequestProvider.addTask(context: context, task: _addTaskModel!); diff --git a/lib/modules/tm_module/tasks/task_request_detail_view.dart b/lib/modules/tm_module/tasks/task_request_detail_view.dart index a382bddb..1102c9b7 100644 --- a/lib/modules/tm_module/tasks/task_request_detail_view.dart +++ b/lib/modules/tm_module/tasks/task_request_detail_view.dart @@ -9,6 +9,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/all_requests_and_count_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/new_models/task_request/task_request_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; @@ -159,7 +160,7 @@ class _TaskRequestDetailsViewState extends State { if (taskProvider.taskRequestModel?.taskJobAttachments?.isNotEmpty ?? false) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: taskProvider.taskRequestModel!.taskJobAttachments!.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), + FilesList(images: taskProvider.taskRequestModel!.taskJobAttachments!.whereType().where((e) => e.name != null).map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), ], buildTechnicalComments(taskModel: taskModel), ], diff --git a/lib/modules/tm_module/tasks/update_task_request_view.dart b/lib/modules/tm_module/tasks/update_task_request_view.dart index d5cfd48c..d0c102e9 100644 --- a/lib/modules/tm_module/tasks/update_task_request_view.dart +++ b/lib/modules/tm_module/tasks/update_task_request_view.dart @@ -63,7 +63,7 @@ class _UpdateTaskRequestState extends State { final GlobalKey _formKey = GlobalKey(); final GlobalKey _scaffoldKey = GlobalKey(); List attachments = []; - List otherAttachments = []; + List otherAttachments = []; bool installationType = true; String comments = ''; List timerList = []; @@ -87,8 +87,8 @@ class _UpdateTaskRequestState extends State { _taskProvider?.refresh(); calculateWorkingTime(helperModel: taskModel!); if (taskModel.taskJobAttachments != null) { - attachments = taskModel.taskJobAttachments!.where((e) => e.createdBy == _userProvider.user?.userID).map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '')).toList(); - otherAttachments = taskModel.taskJobAttachments?.where((e) => e.createdBy != _userProvider.user?.userID).toList() ?? []; + attachments = taskModel.taskJobAttachments!.whereType().where((e) => e.createdBy == _userProvider.user?.userID && e.id != null).map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '',documentType: e.documentType)).toList(); + otherAttachments = taskModel.taskJobAttachments!.whereType().where((e) => e.createdBy != _userProvider.user?.userID).toList(); } } @@ -191,6 +191,7 @@ class _UpdateTaskRequestState extends State { 20.height, AttachmentPicker( label: context.translation.attachFiles, + showAsListView: true, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, @@ -254,13 +255,13 @@ class _UpdateTaskRequestState extends State { if (validate(model: taskModel)) { showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); - List taskAttachment = []; + List taskAttachment = []; if (otherAttachments.isNotEmpty) { taskAttachment.addAll(otherAttachments); } for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - taskAttachment.add(TaskJobAttachment(id: item.id, name: fileName)); + taskAttachment.add(GenericAttachmentModel(id: item.id, name: fileName,documentType: item.documentType)); } taskModel.taskJobAttachments = taskAttachment; taskModel.taskJobActivityEngineerTimers = []; diff --git a/lib/modules/traf_module/create_traf_request_page.dart b/lib/modules/traf_module/create_traf_request_page.dart index 4d552cf1..78c98e5f 100644 --- a/lib/modules/traf_module/create_traf_request_page.dart +++ b/lib/modules/traf_module/create_traf_request_page.dart @@ -516,6 +516,7 @@ class _CreateTRAFRequestPageState extends State { 12.height, AttachmentPicker( label: context.translation.attachFiles, + showAsListView: true, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, @@ -622,7 +623,7 @@ class _CreateTRAFRequestPageState extends State { for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; trafRequest?.attachments!.add( - Attachments(id: 0, trafId: 0, attachmentName: fileName), + GenericAttachmentModel(id: 0, moduleReferenceId: 0, name: fileName, documentType: item.documentType), ); } diff --git a/lib/modules/traf_module/traf_request_detail_page.dart b/lib/modules/traf_module/traf_request_detail_page.dart index 00673a35..32c839f7 100644 --- a/lib/modules/traf_module/traf_request_detail_page.dart +++ b/lib/modules/traf_module/traf_request_detail_page.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/user_types.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/traf_module/traf_request_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; @@ -63,7 +64,7 @@ class _TrafRequestDetailPageState extends State { if (isLoading) return const ALoading(); TrafRequestProvider trafProvider = Provider.of(context, listen: false); if (trafProvider.trafRequestDataModel?.attachments != null) { - _attachments = trafProvider.trafRequestDataModel!.attachments!.map((e) => File(URLs.getFileUrl(e.attachmentName ?? '') ?? '')).toList(); + _attachments = trafProvider.trafRequestDataModel!.attachments!.whereType().map((e) => File(URLs.getFileUrl(e.name ?? '') ?? '')).toList(); } return trafProvider.trafRequestDataModel == null ? const NoDataFound().center diff --git a/lib/modules/traf_module/traf_request_model.dart b/lib/modules/traf_module/traf_request_model.dart index a9d7c40e..2b177cda 100644 --- a/lib/modules/traf_module/traf_request_model.dart +++ b/lib/modules/traf_module/traf_request_model.dart @@ -1,3 +1,6 @@ +import 'package:test_sa/models/lookup.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; + class TrafRequestModel { List? trafRequestDataModel; int? totalRows; @@ -92,7 +95,7 @@ class TrafRequestDataModel { String? isCombinationName; String? usedWithCombination; String? comment; - List? attachments; + List? attachments; bool? isFromMobile; int? isBudgetId; String? isBudgetName; @@ -309,9 +312,9 @@ class TrafRequestDataModel { comment = json['comment']; isFromMobile = json['isFromMobile']; if (json['attachments'] != null) { - attachments = []; + attachments = []; json['attachments'].forEach((v) { - attachments!.add(new Attachments.fromJson(v)); + attachments!.add(GenericAttachmentModel.fromTrafJson(v)); }); } isBudgetId = json['isBudgetId']; @@ -426,8 +429,8 @@ class TrafRequestDataModel { data['usedWithCombination'] = this.usedWithCombination; data['comment'] = this.comment; data['isFromMobile'] = this.isFromMobile; - if (this.attachments != null) { - data['attachments'] = this.attachments!.map((v) => v.toJson()).toList(); + if (attachments != null) { + data['attachments'] = attachments!.map((v) => v.toTrafJson()).toList(); } else { data['attachments'] = []; } @@ -536,7 +539,7 @@ class TrafRequestDataModel { data['isBudgetId'] = isBudgetId; data['attachments'] = - attachments?.map((v) => v.toJson()).toList() ?? []; + attachments?.map((v) => v.toTrafJson() ?? {}).toList() ?? []; return data; } @@ -632,25 +635,28 @@ class Departments { return data; } } - -class Attachments { - int? id; - int? trafId; - String? attachmentName; - - Attachments({this.id, this.trafId, this.attachmentName}); - - Attachments.fromJson(Map json) { - id = json['id']; - trafId = json['trafId']; - attachmentName = json['attachmentName']; - } - - Map toJson() { - final Map data = new Map(); - data['id'] = this.id; - data['trafId'] = this.trafId; - data['attachmentName'] = this.attachmentName; - return data; - } -} +//TODO need to remove this +// class Attachments { +// int? id; +// int? trafId; +// String? attachmentName; +// Lookup ? documentType; +// +// Attachments({this.id, this.trafId, this.attachmentName,this.documentType}); +// +// Attachments.fromJson(Map json) { +// id = json['id']; +// trafId = json['trafId']; +// attachmentName = json['attachmentName']; +// documentType = json['documentType']; +// } +// +// Map toJson() { +// final Map data = new Map(); +// data['id'] = this.id; +// data['trafId'] = this.trafId; +// data['attachmentName'] = this.attachmentName; +// data['documentTypeId'] = this.documentType?.id; +// return data; +// } +// } diff --git a/lib/modules/traf_module/update_traf_request_page.dart b/lib/modules/traf_module/update_traf_request_page.dart index 3e62c5cb..e9b042d8 100644 --- a/lib/modules/traf_module/update_traf_request_page.dart +++ b/lib/modules/traf_module/update_traf_request_page.dart @@ -58,7 +58,7 @@ class _UpdateTrafRequestPageState extends State { Provider.of(context, listen: false).reset(); trafRequestProvider = Provider.of(context, listen: false); trafRequest = trafRequestProvider.trafRequestDataModel!; - attachments = trafRequest.attachments?.map((item) => GenericAttachmentModel(id: item.id, name: item.attachmentName)).toList() ?? []; + attachments = trafRequest.attachments?.whereType().map((item) => GenericAttachmentModel(id: item.id, name: item.name ?? '')).toList() ?? []; } @override @@ -212,6 +212,7 @@ class _UpdateTrafRequestPageState extends State { 12.height, AttachmentPicker( label: context.translation.attachFiles, + showAsListView: true, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, @@ -233,7 +234,7 @@ class _UpdateTrafRequestPageState extends State { for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; trafRequest.attachments!.add( - Attachments(id: item.id, trafId: item.id, attachmentName: fileName), + GenericAttachmentModel(id: item.id, moduleReferenceId: item.id, name: fileName, documentType: item.documentType), ); } } diff --git a/lib/views/widgets/equipment/asset_detail_page.dart b/lib/views/widgets/equipment/asset_detail_page.dart index 0a51cc87..a2759caf 100644 --- a/lib/views/widgets/equipment/asset_detail_page.dart +++ b/lib/views/widgets/equipment/asset_detail_page.dart @@ -1,29 +1,20 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/providers/api/devices_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; -import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/asset_by_id_model.dart'; -import 'package:test_sa/models/generic_attachment_model.dart'; -import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; -import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; +import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; -import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; -import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; +import 'package:test_sa/views/widgets/equipment/asset_details_view.dart'; +import 'package:test_sa/views/widgets/equipment/asset_document_history_view.dart'; import 'package:test_sa/views/widgets/equipment/asset_image_upload_page.dart'; -import 'package:test_sa/views/widgets/images/files_list.dart'; -import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; import 'package:test_sa/views/widgets/loaders/app_loading.dart'; import 'package:test_sa/views/widgets/loaders/failed_loading.dart'; -import '../../../new_views/app_style/app_color.dart'; -import '../requests/request_status.dart'; - class AssetDetailPage extends StatefulWidget { static const String id = "/asset-details"; @@ -35,28 +26,11 @@ class AssetDetailPage extends StatefulWidget { } } -class _AssetDetailPageState extends State with SingleTickerProviderStateMixin { - late AnimationController _animationController; +class _AssetDetailPageState extends State { int? assetId; AssetProvider? _assetProvider; AssetByIdModel? assetModel; - @override - void initState() { - super.initState(); - _animationController = AnimationController( - duration: const Duration(milliseconds: 1400), - vsync: this, - ); - } - - @override - void dispose() { - _animationController.dispose(); - super.dispose(); - } - - List attachments = []; @override Widget build(BuildContext context) { @@ -81,311 +55,53 @@ class _AssetDetailPageState extends State with SingleTickerProv } else if (snapshot.hasData) {} if (snapshot.hasData) { assetModel = snapshot.data!; - attachments = assetModel?.assetAttachments - ?.map((attachment) => GenericAttachmentModel( - id: attachment.id, - name: attachment.attachmentName, - originalName: attachment.originalName, - )) - .toList() ?? - []; - - if (!_animationController.isCompleted) { - _animationController.forward(from: 0.0); - } - - // Image animation - fade in with scale - final imageAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.0, 0.4, curve: Curves.easeOut), - ), - ); - - final imageScaleAnimation = Tween(begin: 0.92, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.0, 0.4, curve: Curves.easeOutCubic), - ), - ); - - // Status label animation - final statusAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.15, 0.5, curve: Curves.easeOut), - ), - ); - - final statusSlideAnimation = Tween( - begin: const Offset(0.0, 0.2), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.15, 0.5, curve: Curves.easeOutCubic), - ), - ); - - // Header animation - final headerAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.25, 0.6, curve: Curves.easeOut), - ), - ); - - final headerSlideAnimation = Tween( - begin: const Offset(0.0, 0.2), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.25, 0.6, curve: Curves.easeOutCubic), - ), - ); - - // Details row animation - final detailsAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.35, 0.75, curve: Curves.easeOut), - ), - ); - - final detailsSlideAnimation = Tween( - begin: const Offset(0.0, 0.15), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.35, 0.75, curve: Curves.easeOutCubic), - ), - ); - - // Dates section animation - final datesAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.50, 0.9, curve: Curves.easeOut), - ), - ); - - final datesSlideAnimation = Tween( - begin: const Offset(0.0, 0.15), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.50, 0.9, curve: Curves.easeOutCubic), - ), - ); - - // Description animation (if exists) - final descAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.65, 1.0, curve: Curves.easeOut), - ), - ); - - final descSlideAnimation = Tween( - begin: const Offset(0.0, 0.1), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.65, 1.0, curve: Curves.easeOutCubic), - ), - ); - - final attachmentAnimation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.80, 1.0, curve: Curves.easeOut), - ), - ); - - final attachmentSlideAnimation = Tween( - begin: const Offset(0.0, 0.1), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: const Interval(0.80, 1.0, curve: Curves.easeOutCubic), - ), - ); - - return Column( - children: [ - SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + return DefaultTabController( + length: 2, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: EdgeInsets.only(left: 16.toScreenWidth, right: 16.toScreenWidth, top: 12.toScreenHeight), + decoration: BoxDecoration( + color: AppColor.tabBarBackground(context), + border: Border.all(color: AppColor.tabBarBorder(context)), + borderRadius: BorderRadius.circular(20), + ), + child: TabBar( + padding: EdgeInsets.symmetric(vertical: 6.toScreenHeight, horizontal: 6.toScreenWidth), + labelColor: context.isDark ? AppColor.neutral30 : AppColor.black20, + unselectedLabelColor: context.isDark ? AppColor.neutral30 : AppColor.black20, + unselectedLabelStyle: AppTextStyles.bodyText, + labelStyle: AppTextStyles.bodyText, + indicatorPadding: EdgeInsets.zero, + indicatorSize: TabBarIndicatorSize.tab, + dividerColor: Colors.transparent, + overlayColor: WidgetStateProperty.all(Colors.transparent), + indicator: BoxDecoration( + color: AppColor.background(context), + borderRadius: BorderRadius.circular(15), + boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 5, offset: const Offset(0, 0), spreadRadius: 0)]), + onTap: (index) { + // setState(() {}); + }, + tabs: [ + Tab(text: context.translation.assetDetails, height: 57.toScreenHeight), + Tab(text: 'Document history'.addTranslation, height: 57.toScreenHeight), + ], + ), + ), + 12.height, + TabBarView( children: [ - // Animated image - FadeTransition( - opacity: imageAnimation, - child: ScaleTransition( - scale: imageScaleAnimation, - child: AspectRatio( - aspectRatio: 159 / 94, - child: Container( - width: 95, - height: 95, - decoration: ShapeDecoration( - color: AppColor.neutral30, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(16), - ), - image: DecorationImage( - fit: BoxFit.cover, - image: NetworkImage(assetModel?.assetPhoto != null ? URLs.getFileUrl(assetModel!.assetPhoto!)! : "https://www.lasteelcraft.com/images/no-image-available.png"), - )), - ), - ), - ), - ), - 6.height, - // Animated content column - Column( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Status label with animation - if (assetModel?.commissioningStatus != null) - FadeTransition( - opacity: statusAnimation, - child: SlideTransition( - position: statusSlideAnimation, - child: StatusLabel( - label: assetModel!.commissioningStatus!.name, - textColor: AppColor.getRequestStatusTextColorByName(context, assetModel!.commissioningStatus!.name!), - backgroundColor: AppColor.getRequestStatusColorByName(context, assetModel!.commissioningStatus!.name!), - ), - ), - ), - if (assetModel?.commissioningStatus != null) 8.height, - - // Header with animation - FadeTransition( - opacity: headerAnimation, - child: SlideTransition( - position: headerSlideAnimation, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - spacing: 2, - children: [ - InfoHeader16Widget(assetModel?.modelDefinition?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"), - if (context.userProvider.isEngineer && !(assetModel?.hasTrainingImageData ?? true)) - const InfoTextLabelWidget(label: '*Upload Images for this asset', color: AppColor.red30), - ], - ), - ), - ), - 8.height, - // Details row with animation - FadeTransition( - opacity: detailsAnimation, - child: SlideTransition( - position: detailsSlideAnimation, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - spacing: 8, - children: [ - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - InfoTextWidget(label: context.translation.assetNo, value: assetModel!.multiAssets!.first.assetNumber, showEmptyValue: true, copyValue: true), - InfoTextWidget(label: context.translation.modelName, value: assetModel!.modelDefinition!.modelName, showEmptyValue: true), - InfoTextWidget(label: context.translation.supplier, value: assetModel!.supplier?.suppliername, showEmptyValue: true), - InfoTextWidget(label: context.translation.manufacture, value: assetModel!.modelDefinition!.manufacturerName, showEmptyValue: true), - ], - ).expanded, - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - InfoTextWidget(label: context.translation.snNo, value: assetModel!.multiAssets!.first.assetSerialNo, showEmptyValue: true), - InfoTextWidget(label: context.translation.site, value: assetModel!.site?.custName?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), - InfoTextWidget(label: context.translation.building, value: assetModel!.building?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), - InfoTextWidget(label: context.translation.floor, value: assetModel!.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), - InfoTextWidget(label: context.translation.md, value: assetModel!.department?.departmentName?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), - InfoTextWidget(label: context.translation.room, value: assetModel!.room?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), - ], - ).expanded, - ], - ), - ), - ), - // 8.height, - // Divider with animation - FadeTransition( - opacity: datesAnimation, - child: const Divider().defaultStyle(context), - ), - // 8.height, - // Dates section with animation - FadeTransition( - opacity: datesAnimation, - child: SlideTransition( - position: datesSlideAnimation, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - InfoTextWidget(label: context.translation.installationDate, value: assetModel?.installationDate?.toAssetDetailsFormat, showEmptyValue: true), - InfoTextWidget(label: context.translation.nextPmDate, value: assetModel?.nextPMDate?.toAssetDetailsFormat, showEmptyValue: true), - InfoTextWidget(label: context.translation.lastPmDate, value: assetModel?.lastPMDate?.toAssetDetailsFormat, showEmptyValue: true), - ], - ), - ), - ), - - // Description with animation (if exists) - if ((assetModel?.modelDefinition?.assetDescription ?? "").isNotEmpty) ...[ - // 8.height, - FadeTransition( - opacity: descAnimation, - child: const Divider().defaultStyle(context), - ), - FadeTransition( - opacity: descAnimation, - child: SlideTransition( - position: descSlideAnimation, - child: InfoTextWidget(label: assetModel!.modelDefinition!.assetDescription!, showEmptyValue: true, isMsg: true), - ), - ), - ], - - if (attachments.isNotEmpty) ...[ - // 8.height, - FadeTransition( - opacity: attachmentAnimation, - child: const Divider().defaultStyle(context), - ), - FadeTransition( - opacity: attachmentAnimation, - child: SlideTransition( - position: attachmentSlideAnimation, - child: FilesList(images: attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), - ), - ), - ] - ], + AssetDetailsView( + assetModel: assetModel!, + onUpload: _upload, ), + const AssetDocumentHistoryView(), ], - ).toShadowContainer(context), - ).expanded, - if (context.userProvider.isEngineer && !(assetModel!.hasTrainingImageData ?? true)) - FooterActionButton.footerContainer( - context: context, - child: AppFilledButton( - buttonColor: AppColor.primary10, - label: "Upload Images", - onPressed: _upload, - ), - ), - ], + ).expanded, + ], + ), ); } return const Center(child: ALoading()); diff --git a/lib/views/widgets/equipment/asset_details_view.dart b/lib/views/widgets/equipment/asset_details_view.dart new file mode 100644 index 00000000..8b86fcd5 --- /dev/null +++ b/lib/views/widgets/equipment/asset_details_view.dart @@ -0,0 +1,346 @@ +import 'package:flutter/material.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/extensions/int_extensions.dart'; +import 'package:test_sa/extensions/string_extensions.dart'; +import 'package:test_sa/extensions/text_extensions.dart'; +import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/device/asset_by_id_model.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/new_views/app_style/app_color.dart'; +import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; +import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; +import 'package:test_sa/views/widgets/images/files_list.dart'; +import 'package:test_sa/views/widgets/requests/request_status.dart'; + +class AssetDetailsView extends StatefulWidget { + final AssetByIdModel assetModel; + final VoidCallback onUpload; + + const AssetDetailsView({ + Key? key, + required this.assetModel, + required this.onUpload, + }) : super(key: key); + + @override + State createState() => _AssetDetailsViewState(); +} + +class _AssetDetailsViewState extends State with SingleTickerProviderStateMixin { + late AnimationController _animationController; + List attachments = []; + + @override + void initState() { + super.initState(); + _animationController = AnimationController( + duration: const Duration(milliseconds: 1400), + vsync: this, + ); + attachments = widget.assetModel.assetAttachments?.whereType().toList() ?? []; + _animationController.forward(from: 0.0); + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + // Image animation - fade in with scale + final imageAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.0, 0.4, curve: Curves.easeOut), + ), + ); + + final imageScaleAnimation = Tween(begin: 0.92, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.0, 0.4, curve: Curves.easeOutCubic), + ), + ); + + // Status label animation + final statusAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.15, 0.5, curve: Curves.easeOut), + ), + ); + + final statusSlideAnimation = Tween( + begin: const Offset(0.0, 0.2), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.15, 0.5, curve: Curves.easeOutCubic), + ), + ); + + // Header animation + final headerAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.25, 0.6, curve: Curves.easeOut), + ), + ); + + final headerSlideAnimation = Tween( + begin: const Offset(0.0, 0.2), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.25, 0.6, curve: Curves.easeOutCubic), + ), + ); + + // Details row animation + final detailsAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.35, 0.75, curve: Curves.easeOut), + ), + ); + + final detailsSlideAnimation = Tween( + begin: const Offset(0.0, 0.15), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.35, 0.75, curve: Curves.easeOutCubic), + ), + ); + + // Dates section animation + final datesAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.50, 0.9, curve: Curves.easeOut), + ), + ); + + final datesSlideAnimation = Tween( + begin: const Offset(0.0, 0.15), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.50, 0.9, curve: Curves.easeOutCubic), + ), + ); + + // Description animation (if exists) + final descAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.65, 1.0, curve: Curves.easeOut), + ), + ); + + final descSlideAnimation = Tween( + begin: const Offset(0.0, 0.1), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.65, 1.0, curve: Curves.easeOutCubic), + ), + ); + + final attachmentAnimation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.80, 1.0, curve: Curves.easeOut), + ), + ); + + final attachmentSlideAnimation = Tween( + begin: const Offset(0.0, 0.1), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: const Interval(0.80, 1.0, curve: Curves.easeOutCubic), + ), + ); + + return Column( + children: [ + SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Animated image + FadeTransition( + opacity: imageAnimation, + child: ScaleTransition( + scale: imageScaleAnimation, + child: AspectRatio( + aspectRatio: 159 / 94, + child: Container( + width: 95, + height: 95, + decoration: ShapeDecoration( + color: AppColor.neutral30, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + image: DecorationImage( + fit: BoxFit.cover, + image: NetworkImage(widget.assetModel.assetPhoto != null ? URLs.getFileUrl(widget.assetModel.assetPhoto!)! : "https://www.lasteelcraft.com/images/no-image-available.png"), + )), + ), + ), + ), + ), + 6.height, + // Animated content column + Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Status label with animation + if (widget.assetModel.commissioningStatus != null) + FadeTransition( + opacity: statusAnimation, + child: SlideTransition( + position: statusSlideAnimation, + child: StatusLabel( + label: widget.assetModel.commissioningStatus!.name, + textColor: AppColor.getRequestStatusTextColorByName(context, widget.assetModel.commissioningStatus!.name!), + backgroundColor: AppColor.getRequestStatusColorByName(context, widget.assetModel.commissioningStatus!.name!), + ), + ), + ), + if (widget.assetModel.commissioningStatus != null) 8.height, + + // Header with animation + FadeTransition( + opacity: headerAnimation, + child: SlideTransition( + position: headerSlideAnimation, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 2, + children: [ + InfoHeader16Widget(widget.assetModel.modelDefinition?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? "-"), + if (context.userProvider.isEngineer && !(widget.assetModel.hasTrainingImageData ?? true)) + const InfoTextLabelWidget(label: '*Upload Images for this asset', color: AppColor.red30), + ], + ), + ), + ), + 8.height, + // Details row with animation + FadeTransition( + opacity: detailsAnimation, + child: SlideTransition( + position: detailsSlideAnimation, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: 8, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InfoTextWidget(label: context.translation.assetNo, value: widget.assetModel.multiAssets!.first.assetNumber, showEmptyValue: true, copyValue: true), + InfoTextWidget(label: context.translation.modelName, value: widget.assetModel.modelDefinition!.modelName, showEmptyValue: true), + InfoTextWidget(label: context.translation.supplier, value: widget.assetModel.supplier?.suppliername, showEmptyValue: true), + InfoTextWidget(label: context.translation.manufacture, value: widget.assetModel.modelDefinition!.manufacturerName, showEmptyValue: true), + ], + ).expanded, + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InfoTextWidget(label: context.translation.snNo, value: widget.assetModel.multiAssets!.first.assetSerialNo, showEmptyValue: true), + InfoTextWidget(label: context.translation.site, value: widget.assetModel.site?.custName?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), + InfoTextWidget(label: context.translation.building, value: widget.assetModel.building?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), + InfoTextWidget(label: context.translation.floor, value: widget.assetModel.floor?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), + InfoTextWidget(label: context.translation.md, value: widget.assetModel.department?.departmentName?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), + InfoTextWidget(label: context.translation.room, value: widget.assetModel.room?.name?.cleanupWhitespace.capitalizeFirstOfEach, showEmptyValue: true), + ], + ).expanded, + ], + ), + ), + ), + // Divider with animation + FadeTransition( + opacity: datesAnimation, + child: const Divider().defaultStyle(context), + ), + // Dates section with animation + FadeTransition( + opacity: datesAnimation, + child: SlideTransition( + position: datesSlideAnimation, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + InfoTextWidget(label: context.translation.installationDate, value: widget.assetModel.installationDate?.toAssetDetailsFormat, showEmptyValue: true), + InfoTextWidget(label: context.translation.nextPmDate, value: widget.assetModel.nextPMDate?.toAssetDetailsFormat, showEmptyValue: true), + InfoTextWidget(label: context.translation.lastPmDate, value: widget.assetModel.lastPMDate?.toAssetDetailsFormat, showEmptyValue: true), + ], + ), + ), + ), + + // Description with animation (if exists) + if ((widget.assetModel.modelDefinition?.assetDescription ?? "").isNotEmpty) ...[ + FadeTransition( + opacity: descAnimation, + child: const Divider().defaultStyle(context), + ), + FadeTransition( + opacity: descAnimation, + child: SlideTransition( + position: descSlideAnimation, + child: InfoTextWidget(label: widget.assetModel.modelDefinition!.assetDescription!, showEmptyValue: true, isMsg: true), + ), + ), + ], + + if (attachments.isNotEmpty) ...[ + FadeTransition( + opacity: attachmentAnimation, + child: const Divider().defaultStyle(context), + ), + FadeTransition( + opacity: attachmentAnimation, + child: SlideTransition( + position: attachmentSlideAnimation, + child: FilesList(images: attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), + ), + ), + ] + ], + ), + ], + ).toShadowContainer(context), + ).expanded, + if (context.userProvider.isEngineer && !(widget.assetModel.hasTrainingImageData ?? true)) + FooterActionButton.footerContainer( + context: context, + child: AppFilledButton( + buttonColor: AppColor.primary10, + label: "Upload Images", + onPressed: widget.onUpload, + ), + ), + ], + ); + } + +} diff --git a/lib/views/widgets/equipment/asset_document_history_view.dart b/lib/views/widgets/equipment/asset_document_history_view.dart new file mode 100644 index 00000000..986dafb9 --- /dev/null +++ b/lib/views/widgets/equipment/asset_document_history_view.dart @@ -0,0 +1,29 @@ +import 'package:flutter/material.dart'; +import 'package:test_sa/extensions/int_extensions.dart'; +import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/views/widgets/images/files_list.dart'; + +class AssetDocumentHistoryView extends StatelessWidget { + const AssetDocumentHistoryView({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final List dummyDocuments = [ + 'https://picsum.photos/200/300?random=1', + 'https://picsum.photos/200/300?random=2', + 'https://picsum.photos/200/300?random=3', + 'https://picsum.photos/200/300?random=4', + 'https://picsum.photos/200/300?random=5', + ]; + + return SingleChildScrollView( + padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), + child: FilesList( + showAsListView: true, + // itemGap: 12.toScreenHeight, + showDownloadButton: true, + images: dummyDocuments, + ).toShadowContainer(context), + ); + } +} diff --git a/lib/views/widgets/equipment/asset_image_upload_page.dart b/lib/views/widgets/equipment/asset_image_upload_page.dart index 33d48a62..8c2eaddf 100644 --- a/lib/views/widgets/equipment/asset_image_upload_page.dart +++ b/lib/views/widgets/equipment/asset_image_upload_page.dart @@ -112,6 +112,7 @@ class _AssetImageUploadPageState extends State { attachment: trainingImageData.additionalImages!, buttonColor: AppColor.black10, onlyImages: true, + showAsListView: true, pickMultiple: true, // showAsGrid: true, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), @@ -164,6 +165,7 @@ class _AssetImageUploadPageState extends State { child: AttachmentPicker( label: "", pickerTitle: title, + showAsListView:true, onlyImages: true, checkQuality: true, enabled: attachment == null, diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 9ca23d8a..892e0709 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -10,8 +10,8 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; -import 'package:test_sa/views/widgets/buttons/app_back_button.dart'; import 'package:test_sa/views/widgets/loaders/image_loader.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -20,15 +20,18 @@ class FilesList extends StatelessWidget { final List types; final EdgeInsets? padding; final bool showAsListView; + final bool showDownloadButton; + final double? itemGap; - const FilesList({Key? key, this.images = const [], this.types = const [], this.padding, this.showAsListView = false}) : super(key: key); + const FilesList({Key? key, this.images = const [], this.types = const [], this.padding, this.showAsListView = false, this.showDownloadButton = false, this.itemGap}) + : super(key: key); @override Widget build(BuildContext context) { return showAsListView ? ListView.separated( shrinkWrap: true, - padding: const EdgeInsets.only(top: 8), + padding: padding ?? const EdgeInsets.only(top: 8), physics: const NeverScrollableScrollPhysics(), itemBuilder: (cxt, itemIndex) { if (!images[itemIndex].contains(".")) { @@ -105,14 +108,25 @@ class FilesList extends StatelessWidget { ), ), ], - ).expanded + ).expanded, + showDownloadButton + ? 'download'.toSvgAsset().onPress(() async { + if (Utils.isLocalFile(images[itemIndex])) { + await OpenFile.open(images[itemIndex]); + } else { + await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true); + } + }) + : const SizedBox.shrink() ], ); }, - separatorBuilder: (cxt, index) => 8.height, + separatorBuilder: (cxt, index) => SizedBox( + height: itemGap ?? 8.toScreenHeight, + ), itemCount: images.length) : GridView.builder( - padding: const EdgeInsets.only(top: 8, bottom: 8), + padding: padding ?? const EdgeInsets.only(top: 8, bottom: 8), physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 6, mainAxisSpacing: 8, crossAxisSpacing: 8), diff --git a/lib/views/widgets/images/multi_image_picker.dart b/lib/views/widgets/images/multi_image_picker.dart index a0533210..762e00e2 100644 --- a/lib/views/widgets/images/multi_image_picker.dart +++ b/lib/views/widgets/images/multi_image_picker.dart @@ -1,18 +1,19 @@ import 'dart:io'; - import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; -import 'package:fluttertoast/fluttertoast.dart'; import 'package:image_blur_detection/image_blur_detection.dart'; import 'package:image_picker/image_picker.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; -import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; +import 'package:test_sa/modules/asset_delivery_module/provider/attachment_type_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; +import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; +import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; import '../../../new_views/common_widgets/app_dashed_button.dart'; import 'multi_image_picker_item.dart'; @@ -62,12 +63,13 @@ class AttachmentPicker extends StatefulWidget { this.pickerTitle = "Attach File", this.error = false, this.buttonHeight, + required this.showAsListView, this.buttonIcon, this.enabled = true, this.onlyImages = false, this.onChange, this.documentType, - this.showAsListView = false, + // this.showAsListView = false, this.pickMultiple = false, this.checkQuality = false, this.child, @@ -80,6 +82,7 @@ class AttachmentPicker extends StatefulWidget { class _AttachmentPickerState extends State with SingleTickerProviderStateMixin { late AnimationController _animationController; + Lookup? documentLookup; @override void initState() { @@ -123,7 +126,7 @@ class _AttachmentPickerState extends State with SingleTickerPr file: image, showAsListView: widget.showAsListView, enabled: widget.enabled, - documentType: widget.attachment[index].documentTypeId?.name, + documentType: widget.attachment[index].documentType?.name, onRemoveTap: (image) { if (!widget.enabled) { return; @@ -173,7 +176,7 @@ class _AttachmentPickerState extends State with SingleTickerPr ); if (result != null) { for (var path in result.paths) { - widget.attachment.add(GenericAttachmentModel(id: 0, name: File(path!).path, documentTypeId: widget.documentType)); + widget.attachment.add(GenericAttachmentModel(id: 0, name: File(path!).path, documentType: documentLookup)); } if (widget.onChange != null) { widget.onChange!(widget.attachment); @@ -206,111 +209,151 @@ class _AttachmentPickerState extends State with SingleTickerPr } onFilePicker(bool checkQuality) async { - // Reset and restart animation for bottom sheet _animationController.reset(); _animationController.forward(); + documentLookup = null; ImageSource? source = await showModalBottomSheet( context: context, builder: (BuildContext context) { - Widget listCard({required String icon, required String label, required VoidCallback onTap}) { - return Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: AppColor.background(context), - borderRadius: BorderRadius.circular(16), - border: Border.all(color: AppColor.borderColor(context), width: 2), - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - icon.toSvgAsset(width: 24, height: 24, color: AppColor.icon2Color(context)), - label.bodyText2(context).custom(color: AppColor.labelTextStyleColor(context), fontSize: context.isTablet() ? 10.toScreenWidth : null), - ], - ), - ).onPress(onTap); - } + return StatefulBuilder( + builder: (BuildContext context, StateSetter setModalState) { + Widget listCard({required String icon, required String label, required VoidCallback onTap}) { + bool isEnabled = documentLookup != null; + return Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isEnabled ? AppColor.background(context) : AppColor.tabBarBackground(context), + borderRadius: BorderRadius.circular(16), + border: Border.all(color: AppColor.borderColor(context), width: 2), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + icon.toSvgAsset(width: 24, height: 24, color: isEnabled ? AppColor.icon2Color(context) : AppColor.icon2Color(context).withOpacity(0.4)), + label.bodyText2(context).custom( + color: isEnabled ? AppColor.labelTextStyleColor(context) : AppColor.labelTextStyleColor(context).withOpacity(0.4), fontSize: context.isTablet() ? 10.toScreenWidth : null), + ], + ), + ).onPress(() { + if (!isEnabled) return; + onTap(); + }); + } - List listItems = [ - listCard( - icon: 'camera_icon', - label: '${context.translation.open}\n${context.translation.camera}', - onTap: () { - Navigator.of(context).pop(ImageSource.camera); - }, - ), - listCard( - icon: 'gallery_icon', - label: '${context.translation.open}\n${context.translation.gallery}', - onTap: () { - Navigator.of(context).pop(ImageSource.gallery); - }, - ), - listCard( - icon: 'file_icon', - label: '${context.translation.open}\n${context.translation.files}', - onTap: () async { - await fromFilePicker(); - Navigator.pop(context); - }, - ), - ]; + List listItems = [ + listCard( + icon: 'camera_icon', + label: '${context.translation.open}\n${context.translation.camera}', + onTap: () { + Navigator.of(context).pop(ImageSource.camera); + }, + ), + listCard( + icon: 'gallery_icon', + label: '${context.translation.open}\n${context.translation.gallery}', + onTap: () { + Navigator.of(context).pop(ImageSource.gallery); + }, + ), + listCard( + icon: 'file_icon', + label: '${context.translation.open}\n${context.translation.files}', + onTap: () async { + await fromFilePicker(); + Navigator.pop(context); + }, + ), + ]; - return SafeArea( - top: false, - child: Container( - width: double.infinity, - color: AppColor.bottomSheetColor(context), - padding: const EdgeInsets.all(16.0), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - widget.pickerTitle.heading4(context), - GridView.builder( - padding: const EdgeInsets.only(top: 16, bottom: 0), - shrinkWrap: true, - physics: const NeverScrollableScrollPhysics(), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 16, mainAxisSpacing: 16), - itemCount: listItems.length, - itemBuilder: (context, index) { - // Calculate staggered animation delay - final delay = index * 0.08; - final animation = Tween(begin: 0.0, end: 1.0).animate( - CurvedAnimation( - parent: _animationController, - curve: Interval( - delay.clamp(0.0, 0.8), - (delay + 0.3).clamp(0.0, 1.0), - curve: Curves.easeOut, - ), + return SafeArea( + top: false, + child: Container( + width: double.infinity, + decoration: BoxDecoration( + color: AppColor.bottomSheetColor(context), + borderRadius: const BorderRadius.only( + topRight: Radius.circular(30), + topLeft: Radius.circular(30), + ), + ), + padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth, vertical: 8.toScreenHeight), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Align(alignment: AlignmentDirectional.center, + child: Container( + width: 40.toScreenWidth, + height: 5.toScreenHeight, + decoration: BoxDecoration(color: AppColor.neutral40, borderRadius: BorderRadius.circular(30)), ), - ); + ), + 8.height, + InfoHeader16Widget(widget.pickerTitle), + 8.height, + SingleItemDropDownMenu( + context: context, + height: 56.toScreenHeight, + title: "Document Type", + initialValue: documentLookup, + showShadow: false, + backgroundColor: AppColor.fieldBgColor(context), + showAsBottomSheet: true, + onSelect: (value) { + documentLookup = value; + setModalState(() {}); + }, + ), + if (documentLookup == null) ...[ + 4.height, + const InfoTextLabelWidget(label: 'Please Select Document Type before picking file', color: AppColor.red30), + ], + GridView.builder( + padding: const EdgeInsets.only(top: 16, bottom: 0), + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3, childAspectRatio: 1, crossAxisSpacing: 16, mainAxisSpacing: 16), + itemCount: listItems.length, + itemBuilder: (context, index) { + final delay = index * 0.08; + final animation = Tween(begin: 0.0, end: 1.0).animate( + CurvedAnimation( + parent: _animationController, + curve: Interval( + delay.clamp(0.0, 0.8), + (delay + 0.3).clamp(0.0, 1.0), + curve: Curves.easeOut, + ), + ), + ); - final slideAnimation = Tween( - begin: const Offset(0.0, 0.3), - end: Offset.zero, - ).animate( - CurvedAnimation( - parent: _animationController, - curve: Interval( - delay.clamp(0.0, 0.8), - (delay + 0.3).clamp(0.0, 1.0), - curve: Curves.easeOutCubic, - ), - ), - ); + final slideAnimation = Tween( + begin: const Offset(0.0, 0.3), + end: Offset.zero, + ).animate( + CurvedAnimation( + parent: _animationController, + curve: Interval( + delay.clamp(0.0, 0.8), + (delay + 0.3).clamp(0.0, 1.0), + curve: Curves.easeOutCubic, + ), + ), + ); - return FadeTransition( - opacity: animation, - child: SlideTransition(position: slideAnimation, child: listItems[index]), - ); - }, + return FadeTransition( + opacity: animation, + child: SlideTransition(position: slideAnimation, child: listItems[index]), + ); + }, + ), + ], ), - ], - ), - ), + ), + ); + }, ); }, ); @@ -321,7 +364,8 @@ class _AttachmentPickerState extends State with SingleTickerPr if (pickedFiles.isNotEmpty) { pickedFiles.forEach((pickedFile) { File fileImage = File(pickedFile.path); - widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentTypeId: widget.documentType)); + + widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: documentLookup)); }); if (widget.onChange != null) { widget.onChange!(widget.attachment); @@ -348,13 +392,11 @@ class _AttachmentPickerState extends State with SingleTickerPr } } - widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentTypeId: widget.documentType)); + widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: documentLookup)); if (widget.onChange != null) { widget.onChange!(widget.attachment); } setState(() {}); } - - // setState(() {}); } } From 3412345a4aca954442b45c0e2a8697d3346d54a1 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 17 Aug 2026 15:50:56 +0300 Subject: [PATCH 08/47] improvements --- .../widgets/equipment/asset_detail_page.dart | 6 +-- .../asset_document_history_view.dart | 4 +- lib/views/widgets/images/files_list.dart | 38 ++++++++++--------- .../widgets/images/multi_image_picker.dart | 2 +- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/lib/views/widgets/equipment/asset_detail_page.dart b/lib/views/widgets/equipment/asset_detail_page.dart index a2759caf..2d0e25b1 100644 --- a/lib/views/widgets/equipment/asset_detail_page.dart +++ b/lib/views/widgets/equipment/asset_detail_page.dart @@ -31,7 +31,6 @@ class _AssetDetailPageState extends State { AssetProvider? _assetProvider; AssetByIdModel? assetModel; - @override Widget build(BuildContext context) { assetId ??= ModalRoute.of(context)?.settings.arguments as int; @@ -93,10 +92,7 @@ class _AssetDetailPageState extends State { 12.height, TabBarView( children: [ - AssetDetailsView( - assetModel: assetModel!, - onUpload: _upload, - ), + AssetDetailsView(assetModel: assetModel!, onUpload: _upload), const AssetDocumentHistoryView(), ], ).expanded, diff --git a/lib/views/widgets/equipment/asset_document_history_view.dart b/lib/views/widgets/equipment/asset_document_history_view.dart index 986dafb9..68cc3b02 100644 --- a/lib/views/widgets/equipment/asset_document_history_view.dart +++ b/lib/views/widgets/equipment/asset_document_history_view.dart @@ -17,12 +17,12 @@ class AssetDocumentHistoryView extends StatelessWidget { ]; return SingleChildScrollView( - padding: EdgeInsets.symmetric(horizontal: 16.toScreenWidth), + padding: const EdgeInsets.symmetric(horizontal: 16), child: FilesList( showAsListView: true, - // itemGap: 12.toScreenHeight, showDownloadButton: true, images: dummyDocuments, + separator: const Divider().defaultStyle(context), ).toShadowContainer(context), ); } diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 892e0709..b2625ab3 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -22,8 +22,9 @@ class FilesList extends StatelessWidget { final bool showAsListView; final bool showDownloadButton; final double? itemGap; + final Widget? separator; - const FilesList({Key? key, this.images = const [], this.types = const [], this.padding, this.showAsListView = false, this.showDownloadButton = false, this.itemGap}) + const FilesList({Key? key, this.separator, this.images = const [], this.types = const [], this.padding, this.showAsListView = false, this.showDownloadButton = false, this.itemGap}) : super(key: key); @override @@ -31,7 +32,7 @@ class FilesList extends StatelessWidget { return showAsListView ? ListView.separated( shrinkWrap: true, - padding: padding ?? const EdgeInsets.only(top: 8), + padding: padding ?? const EdgeInsets.only(top: 0), physics: const NeverScrollableScrollPhysics(), itemBuilder: (cxt, itemIndex) { if (!images[itemIndex].contains(".")) { @@ -74,14 +75,14 @@ class FilesList extends StatelessWidget { children: [ EllipsizedText( images[itemIndex].split("/").last, - style: AppTextStyles.heading6.copyWith(color: AppColor.black10), + style: AppTextStyles.bodyText.copyWith(color: AppColor.textStyleColor(context)), type: EllipsisType.start, // or EllipsisType.middle ), - 4.height, + 2.height, RichText( text: TextSpan( text: '${types.isEmpty ? "Asset Guide" : types[itemIndex]} | ', - style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral120), + style: AppTextStyles.tinyFont.copyWith(color: AppColor.labelTextStyleColor(context)), children: [ TextSpan( text: 'View', @@ -109,21 +110,24 @@ class FilesList extends StatelessWidget { ), ], ).expanded, - showDownloadButton - ? 'download'.toSvgAsset().onPress(() async { - if (Utils.isLocalFile(images[itemIndex])) { - await OpenFile.open(images[itemIndex]); - } else { - await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true); - } - }) - : const SizedBox.shrink() + if (showDownloadButton) + IconButton( + icon: "download".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)), + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + tooltip: "Download", + onPressed: () async { + if (Utils.isLocalFile(images[itemIndex])) { + await OpenFile.open(images[itemIndex]); + } else { + await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true); + } + }, + ), ], ); }, - separatorBuilder: (cxt, index) => SizedBox( - height: itemGap ?? 8.toScreenHeight, - ), + separatorBuilder: (cxt, index) => separator ?? SizedBox(height: itemGap ?? 8.toScreenHeight), itemCount: images.length) : GridView.builder( padding: padding ?? const EdgeInsets.only(top: 8, bottom: 8), diff --git a/lib/views/widgets/images/multi_image_picker.dart b/lib/views/widgets/images/multi_image_picker.dart index 762e00e2..f6bffcbf 100644 --- a/lib/views/widgets/images/multi_image_picker.dart +++ b/lib/views/widgets/images/multi_image_picker.dart @@ -139,7 +139,7 @@ class _AttachmentPickerState extends State with SingleTickerPr }, ); }, - separatorBuilder: (cxt, index) => 8.height, + separatorBuilder: (cxt, index) => const Divider().defaultStyle(context), itemCount: widget.attachment.length) : Wrap( spacing: 8.toScreenWidth, From 30a69b1ca64c2515d1f2b1ecb626f874742f12d2 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 17 Aug 2026 17:43:12 +0300 Subject: [PATCH 09/47] improvements-cont --- .../providers/api/ppm_provider.dart | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/lib/controllers/providers/api/ppm_provider.dart b/lib/controllers/providers/api/ppm_provider.dart index 19d222cc..f56f7fdd 100644 --- a/lib/controllers/providers/api/ppm_provider.dart +++ b/lib/controllers/providers/api/ppm_provider.dart @@ -72,6 +72,7 @@ class PpmProvider extends ChangeNotifier { nextPage = true; stateCode = null; } + List _storeAvailability = []; List get storeAvailability => _storeAvailability; @@ -191,24 +192,22 @@ class PpmProvider extends ChangeNotifier { if (response.statusCode >= 200 && response.statusCode < 300) { ppmPlanAttachments = []; planPreventiveVisit = PlanPreventiveVisit.fromJson(json.decode(response.body)["data"]); - + // Set isReadOnly based on visit status (1 or 3 means closed/completed) if (planPreventiveVisit?.visitStatus?.value! == 1 || planPreventiveVisit?.visitStatus?.value == 3) { isReadOnly = true; } else { isReadOnly = false; } - + // Set isReadOnlyRequest based on visit status - same logic as CMDetailProvider //Need to confirm this with backend Status values: 3 = Closed, 5 = Completed, 6 = Cancelled (adjust based on your PM status values) - if (planPreventiveVisit?.visitStatus?.value == 3 || - planPreventiveVisit?.visitStatus?.value == 5 || - planPreventiveVisit?.visitStatus?.value == 6) { + if (planPreventiveVisit?.visitStatus?.value == 3 || planPreventiveVisit?.visitStatus?.value == 5 || planPreventiveVisit?.visitStatus?.value == 6) { isReadOnlyRequest = true; } else { isReadOnlyRequest = false; } - + isLoading = false; notifyListeners(); return planPreventiveVisit; @@ -428,22 +427,23 @@ class PpmProvider extends ChangeNotifier { } } - Future updateActivitySparePart() async { - isLoading = true; + Future updateActivitySparePart(BuildContext context) async { Response response; try { - response = await ApiManager.instance.post(URLs.updatePmActivitySparePart, body: sparePartHelperModel!.toPMJson()); - stateCode = response.statusCode; - isLoading = false; - notifyListeners(); - if (stateCode == 200) { + response = await ApiManager.instance.post(URLs.updatePmActivitySparePart, body: sparePartHelperModel!.toPMJson(), showToast: false); + + if (response.statusCode == 200) { + final responseBody = jsonDecode(response.body); + if (responseBody is Map) { + final message = responseBody["message"]; // Reuse parsed body + if (message != null && message.toString().isNotEmpty) { + Fluttertoast.showToast(msg: message, toastLength: Toast.LENGTH_LONG); + } + } return true; } return false; } catch (error) { - isLoading = false; - stateCode = -1; - notifyListeners(); return false; } } @@ -454,8 +454,7 @@ class PpmProvider extends ChangeNotifier { try { final response = await ApiManager.instance.delete('${URLs.deletePmActivitySparePart}?activitySparePartPPMId=$id', body: {}); stateCode = response.statusCode; - if (response.statusCode >= 200 && response.statusCode < 300) { - } + if (response.statusCode >= 200 && response.statusCode < 300) {} isLoading = false; notifyListeners(); return response.statusCode; @@ -476,16 +475,14 @@ class PpmProvider extends ChangeNotifier { notifyListeners(); if (stateCode == 200) { planPreventiveVisit = PlanPreventiveVisit.fromJson(json.decode(response.body)["data"]); - + // Update isReadOnlyRequest after fetching updated data - if (planPreventiveVisit?.visitStatus?.value == 3 || - planPreventiveVisit?.visitStatus?.value == 5 || - planPreventiveVisit?.visitStatus?.value == 6) { + if (planPreventiveVisit?.visitStatus?.value == 3 || planPreventiveVisit?.visitStatus?.value == 5 || planPreventiveVisit?.visitStatus?.value == 6) { isReadOnlyRequest = true; } else { isReadOnlyRequest = false; } - + notifyListeners(); return true; } From 764814171b7da78c2f755de5941b2185b270a90b Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 18 Aug 2026 11:10:30 +0300 Subject: [PATCH 10/47] improvements --- .../providers/api/ppm_provider.dart | 16 +++++++-------- .../forms/spare_part/spare_part_request.dart | 10 ++++++++-- .../activities/pm_activities_list_view.dart | 20 +++++++++++-------- .../swipe_module/dialoge/info_dialog.dart | 2 +- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/lib/controllers/providers/api/ppm_provider.dart b/lib/controllers/providers/api/ppm_provider.dart index f56f7fdd..7861b5b1 100644 --- a/lib/controllers/providers/api/ppm_provider.dart +++ b/lib/controllers/providers/api/ppm_provider.dart @@ -408,10 +408,7 @@ class PpmProvider extends ChangeNotifier { isLoading = true; Response response; try { - response = await ApiManager.instance.post( - URLs.createPmActivitySparePart, - body: sparePartHelperModel!.toPMJson(), - ); + response = await ApiManager.instance.post(URLs.createPmActivitySparePart, body: sparePartHelperModel!.toPMJson()); stateCode = response.statusCode; isLoading = false; notifyListeners(); @@ -427,24 +424,25 @@ class PpmProvider extends ChangeNotifier { } } - Future updateActivitySparePart(BuildContext context) async { + Future updateActivitySparePart() async { Response response; try { response = await ApiManager.instance.post(URLs.updatePmActivitySparePart, body: sparePartHelperModel!.toPMJson(), showToast: false); if (response.statusCode == 200) { + return ""; + } else { final responseBody = jsonDecode(response.body); if (responseBody is Map) { final message = responseBody["message"]; // Reuse parsed body if (message != null && message.toString().isNotEmpty) { - Fluttertoast.showToast(msg: message, toastLength: Toast.LENGTH_LONG); + return message; } } - return true; + return "Failed, Try Again"; } - return false; } catch (error) { - return false; + return "Failed, Try Again"; } } diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 63dcd3b7..19b58ed1 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -356,10 +356,12 @@ class _SparePartRequestState extends State { // Submit bool success = false; + String message = ""; if (model?.id == 0) { success = await provider.createActivitySparePart(); } else { - success = await provider.updateActivitySparePart(); + message = await provider.updateActivitySparePart(); + success = message.isEmpty; } if (mounted) Navigator.pop(context); // Close loading @@ -385,6 +387,10 @@ class _SparePartRequestState extends State { message: '', ); } + } else { + if(message.isNotEmpty) { + context.showInfoDialog(message, title: "Error"); + } } } } @@ -421,7 +427,7 @@ class PartDetailBottomSheetSheet extends StatelessWidget { : provider.storeAvailability.isEmpty ? const NoDataFound().center : ListView.separated( - padding: const EdgeInsets.only(top: 12,bottom: 12), + padding: const EdgeInsets.only(top: 12, bottom: 12), itemCount: provider.storeAvailability.length, separatorBuilder: (czt, index) => 12.height, itemBuilder: (context, index) { diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index bf8527e0..d9a43385 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -115,6 +115,9 @@ class _PmActivitiesListViewState extends State { pmProvider.planPreventiveVisit?.visitStatus?.value != 5 && pmProvider.planPreventiveVisit?.visitStatus?.value != 3; + bool canDelete = showActionButtons && activity.activityStatus?.value == 1; + bool canEdit = showActionButtons && (canDelete || activity.activityStatus!.value! == 3); + return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -127,15 +130,16 @@ class _PmActivitiesListViewState extends State { textColor: AppColor.white10, backgroundColor: AppColor.primary10, ), - if (showActionButtons) - Row( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + spacing: 12, + children: [ + if (canEdit) "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() { editSparePartRequest(context: context, pmProvider: pmProvider, activity: activity); }), - 12.width, + if (canDelete) "delete_icon".toSvgAsset(height: 24, width: 24).onPress(() async { showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading()); int status = await pmProvider.deleteActivitySparePart(id: activity.id!); @@ -146,8 +150,8 @@ class _PmActivitiesListViewState extends State { Navigator.pop(context); } }), - ], - ) + ], + ) ], ), 6.height, diff --git a/lib/new_views/swipe_module/dialoge/info_dialog.dart b/lib/new_views/swipe_module/dialoge/info_dialog.dart index 5809ab6d..8dcc0cb7 100644 --- a/lib/new_views/swipe_module/dialoge/info_dialog.dart +++ b/lib/new_views/swipe_module/dialoge/info_dialog.dart @@ -41,7 +41,7 @@ class InfoDialog extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( - child: InfoHeader16Widget("Information").paddingOnly(top: 16), + child: InfoHeader16Widget(title ?? "Information").paddingOnly(top: 16), // Text( // title ?? "Information", // style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: AppColor.headingTextColor(context), height: 35 / 24, letterSpacing: -0.96), From 9fbb2efa555f4e34727fc1e447ae8502043510b0 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 18 Aug 2026 11:25:27 +0300 Subject: [PATCH 11/47] improvements --- lib/views/widgets/images/files_list.dart | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index b2625ab3..8bfba4da 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -32,7 +32,7 @@ class FilesList extends StatelessWidget { return showAsListView ? ListView.separated( shrinkWrap: true, - padding: padding ?? const EdgeInsets.only(top: 0), + padding: padding ?? EdgeInsets.zero, physics: const NeverScrollableScrollPhysics(), itemBuilder: (cxt, itemIndex) { if (!images[itemIndex].contains(".")) { @@ -44,6 +44,7 @@ class FilesList extends StatelessWidget { var isExcel = images[itemIndex].split(".").last.toLowerCase() == "xlsx"; return Row( + spacing: 8, children: [ Container( width: 48.toScreenWidth, @@ -69,7 +70,6 @@ class FilesList extends StatelessWidget { : Image.asset("assets/images/${isPdf ? "pdf" : isExcel ? "excel" : "doc"}.png")), ), ), - 8.width, Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -117,11 +117,19 @@ class FilesList extends StatelessWidget { visualDensity: VisualDensity.compact, tooltip: "Download", onPressed: () async { - if (Utils.isLocalFile(images[itemIndex])) { - await OpenFile.open(images[itemIndex]); - } else { - await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true); + try { + if (!await launchUrl(Uri.parse(images[itemIndex]), mode: LaunchMode.externalApplication)) { + Fluttertoast.showToast(msg: "UnExpected Error with file."); + throw Exception('Could not launch '); + } + } catch (ex) { + Fluttertoast.showToast(msg: "No Viewer found."); } + // if (Utils.isLocalFile(images[itemIndex])) { + // await OpenFile.open(images[itemIndex]); + // } else { + // await Utils.downloadFile(images[itemIndex], autoOpen: true, showToast: true); + // } }, ), ], From 1d4ed83a4b792b8a6c6f6baa63145809d4c4c292 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 18 Aug 2026 11:50:18 +0300 Subject: [PATCH 12/47] asset open to details screen --- .../ppm_wo/update_ppm/wo_info_form.dart | 26 ++++++------------- lib/views/widgets/equipment/asset_picker.dart | 15 +++-------- 2 files changed, 12 insertions(+), 29 deletions(-) diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart index c206bef0..ce4e2de4 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart @@ -32,6 +32,7 @@ import 'package:test_sa/providers/ppm_task_status_provider.dart'; import 'package:test_sa/views/widgets/bottom_sheets/asset_detail_bottom_sheet.dart'; import 'package:test_sa/views/widgets/date_and_time/date_picker.dart'; import 'package:test_sa/views/widgets/date_and_time/time_picker.dart'; +import 'package:test_sa/views/widgets/equipment/asset_detail_page.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; @@ -61,7 +62,10 @@ class _WoInfoFormState extends State { calculateWorkingTime(); if (widget.planPreventiveVisit.preventiveVisitAttachments != null && widget.planPreventiveVisit.preventiveVisitAttachments!.isNotEmpty) { ppmProvider.ppmPlanAttachments = []; - ppmProvider.ppmPlanAttachments.addAll(widget.planPreventiveVisit.preventiveVisitAttachments!.whereType().map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '',documentType: e.documentType)).toList()); + ppmProvider.ppmPlanAttachments.addAll(widget.planPreventiveVisit.preventiveVisitAttachments! + .whereType() + .map((e) => GenericAttachmentModel(id: e.id, name: e.name ?? '', documentType: e.documentType)) + .toList()); } }); @@ -156,23 +160,9 @@ class _WoInfoFormState extends State { children: [ InfoHeader16Widget(widget.planPreventiveVisit.assetName ?? '').expanded, // widget.planPreventiveVisit.assetName!.bodyText(context).custom(color: AppColor.headingTextColor(context)).expanded, - "info_icon".toSvgAsset(height: 17, width: 17).onPress( - () { - // There is only limited information for asset is returned from backend to show all info need to return the whole model from backend... - showModalBottomSheet( - context: context, - backgroundColor: AppColor.bottomSheetColor(context), - isScrollControlled: true, - // shape: const RoundedRectangleBorder( - // borderRadius: BorderRadius.vertical( - // top: Radius.circular(20), - // ), - // ), - clipBehavior: Clip.antiAliasWithSaveLayer, - builder: (BuildContext context) => _buildAssetDetailBottomSheet(context), - ); - }, - ) + const Icon(Icons.open_in_new_rounded, color: AppColor.primary10, size: 20).onPress(() { + Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: widget.planPreventiveVisit.asset!.id); + }), ], ), // 2.height, diff --git a/lib/views/widgets/equipment/asset_picker.dart b/lib/views/widgets/equipment/asset_picker.dart index 9088ad37..762adac9 100644 --- a/lib/views/widgets/equipment/asset_picker.dart +++ b/lib/views/widgets/equipment/asset_picker.dart @@ -10,6 +10,7 @@ import 'package:test_sa/views/widgets/qr/asset_scan_qr.dart'; import '../../../models/device/asset.dart'; import '../../../new_views/app_style/app_color.dart'; +import 'asset_detail_page.dart'; class AssetPicker extends StatelessWidget { final Function(Asset)? onPick; @@ -185,21 +186,13 @@ class AssetPicker extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Row( + crossAxisAlignment: CrossAxisAlignment.start, children: [ InfoHeaderWidget( device.modelDefinition?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? "", ).toShimmer(isShow: showLoading, context: context).expanded, - Icon(Icons.info, color: AppColor.icon2Color(context), size: 20).onPress(() { - showModalBottomSheet( - context: context, - isScrollControlled: true, - backgroundColor: AppColor.bottomSheetColor(context), - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(top: Radius.circular(20)), - ), - clipBehavior: Clip.antiAliasWithSaveLayer, - builder: (BuildContext context) => AssetDetailBottomSheet(device), - ); + const Icon(Icons.open_in_new_rounded, color: AppColor.primary10, size: 20).onPress(() { + Navigator.of(context).pushNamed(AssetDetailPage.id, arguments: device.id); }), if (multiSelection) ...[ 4.width, From fb6716f3dfe000682fe0739075e2a54132b98631 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 18 Aug 2026 15:03:57 +0300 Subject: [PATCH 13/47] improvement. --- lib/views/widgets/loaders/image_loader.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/views/widgets/loaders/image_loader.dart b/lib/views/widgets/loaders/image_loader.dart index eed5d473..6197e620 100644 --- a/lib/views/widgets/loaders/image_loader.dart +++ b/lib/views/widgets/loaders/image_loader.dart @@ -1,5 +1,6 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; +import 'package:test_sa/new_views/app_style/app_color.dart'; class ImageLoader extends StatelessWidget { final String? url; @@ -20,7 +21,7 @@ class ImageLoader extends StatelessWidget { alignment: Alignment.center, width: width, height: height, - placeholder: (context, url) => const Center(child: CircularProgressIndicator()), + placeholder: (context, url) => Center(child: CircularProgressIndicator(color: AppColor.loadingColor(context))), errorWidget: (context, url, error) => Icon(showDefaultIcon ? Icons.image_outlined : Icons.broken_image_rounded), ); } From 392136dbe4523d41d6213578301d77624d2e9703 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:17:01 +0300 Subject: [PATCH 14/47] Document library CR completed ready for test --- lib/controllers/api_routes/urls.dart | 10 +- .../providers/api/devices_provider.dart | 36 ++++ lib/models/generic_attachment_model.dart | 48 +++++- .../pages/attachment_view.dart | 7 +- .../components/activities_list_view.dart | 15 +- .../service_request_detail_view.dart | 10 +- .../demo_module/demo_activities_page.dart | 12 +- .../incident_module/incident_detail_page.dart | 9 +- .../equipment_internal_audit_detail_page.dart | 14 +- .../system_internal_audit_detail_page.dart | 9 +- .../pages/loan_equipment_detail_page.dart | 9 +- .../medical_gas_inspection_detail_page.dart | 10 +- .../device_transfer_details.dart | 10 +- .../gas_refill/gas_refill_details.dart | 5 +- .../tasks/task_request_detail_view.dart | 5 +- .../traf_module/traf_request_detail_page.dart | 9 +- .../widgets/equipment/asset_detail_page.dart | 2 +- .../widgets/equipment/asset_details_view.dart | 9 +- .../asset_document_history_view.dart | 162 ++++++++++++++++-- lib/views/widgets/images/files_list.dart | 9 +- 20 files changed, 345 insertions(+), 55 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 0dd6626e..620d367f 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -4,11 +4,11 @@ class URLs { static const String appReleaseBuildNumber = "50"; // static const host1 = "https://atomsm.hmg.com"; // production url - // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + static const host1 = "https://atomsmdev.hmg.com"; // local DEV url + // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url - // static final String _baseUrl = "$_host/mobile"; // host local UAT - static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis + static final String _baseUrl = "$_host/mobile"; // host local UAT + // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation @@ -374,6 +374,8 @@ class URLs { static get updateDeviceTransfer => "$_baseUrl/AssetTransfer/UpdateEngineerAssetTransferNew"; // get static get assetTransferAssignEngineerToHimself => "$_baseUrl/AssetTransfer/AssignEngineerToHimself"; // get static get assetTransferEngineerReject => "$_baseUrl/AssetTransfer/EngineerReject"; // get + static get assetDocumentHistory => "$_baseUrl/DocumentLibrary/SearchDocuments"; + // employee static get getEmployees => "$_baseUrl/Lookups/GetLookup?lookupEnum=33"; // get diff --git a/lib/controllers/providers/api/devices_provider.dart b/lib/controllers/providers/api/devices_provider.dart index 66c95d7b..c8b5b9c7 100644 --- a/lib/controllers/providers/api/devices_provider.dart +++ b/lib/controllers/providers/api/devices_provider.dart @@ -31,6 +31,7 @@ class AssetProvider extends ChangeNotifier { final pageItemNumber = 10; final searchPageItemNumber = 10; + final documentPageItemNumber = 20; bool nextPage = true; @@ -257,4 +258,39 @@ class AssetProvider extends ChangeNotifier { return false; } } + + Future<({List documents, int totalRows})> getAssetDocumentHistory({ + required int assetId, + int pageNumber = 1, + }) async { + Response response; + List documents = []; + try { + var body = { + "pageSize": documentPageItemNumber, + "pageNumber": pageNumber, + "assetIds": [assetId] + }; + response = await ApiManager.instance.post(URLs.assetDocumentHistory, body: body); + stateCode = response.statusCode; + if (response.statusCode >= 200 && response.statusCode < 300) { + final jsonData = json.decode(response.body); + List attachmentJson = jsonData["data"] ?? []; + int totalRows = jsonData["totalRows"] ?? 0; + + documents = attachmentJson + .map((request) => + GenericAttachmentModel.fromAssetDocumentJson(request)) + .toList(); + + nextPage = documents.length < totalRows; + + return (documents: documents, totalRows: totalRows); + } + return (documents: documents, totalRows: 0); + } catch (e) { + log('Error in getAssetDocumentHistory: $e'); + return (documents: documents, totalRows: 0); + } + } } diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 6a6d552b..a59e5b0f 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -1,10 +1,14 @@ import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/models/lookup.dart'; + class GenericAttachmentModel { GenericAttachmentModel({ this.id, this.name, + this.module, + this.subModule, + this.uploadedBy, this.originalName, this.createdBy, this.documentType, @@ -20,6 +24,9 @@ class GenericAttachmentModel { int? id; String? name; + String ? module; + String ? subModule; + String ? uploadedBy; String? createdBy; String? originalName; Lookup? documentType; @@ -36,17 +43,32 @@ class GenericAttachmentModel { id = json['id']; name = json['name'] ?? json['attachmentName'] ?? json['imageName']; createdBy = json['createdBy']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; originalName = json['originalName'] ?? json['imageOriginalName']; - if (convertToLink) { name = URLs.getFileUrl(name); } } + GenericAttachmentModel.fromAssetDocumentJson(Map json, {bool convertToLink = false}) { + id = json['id']; + name = json['attachmentName'] ?? json['name'] ?? json['imageName']; + module = json['module']; + subModule = json['subModule']; + createdBy = json['createdBy']; + createdDate = json['createdDate']; + uploadedBy = json['uploadedBy']; + originalName = json['originalName'] ?? json['imageOriginalName']; + documentType = json['attachmentType'] != null ? Lookup(name: json['attachmentType'], id: 0) : null; + if (convertToLink && name != null) { + name = URLs.getFileUrl(name); + } + } + GenericAttachmentModel.fromWorkOrderJson(Map json) { id = json['id']; name = json['name']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; createdBy = json['createdBy']; } @@ -54,7 +76,7 @@ class GenericAttachmentModel { id = json['id']?.toInt(); name = json['attachmentName']; attachmentDescription = json['attachmentDescription']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; moduleReferenceId = json['loanId']; attachmentTypeId = json['loanAttachmentTypeId']; } @@ -64,6 +86,7 @@ class GenericAttachmentModel { name = json['attachmentName']; attachmentDescription = json['attachmentDescription']; moduleReferenceId = json['loanId']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; attachmentTypeId = json['loanAttachmentTypeId']; createdBy = json['createdBy']; createdDate = json['createdDate']; @@ -75,13 +98,16 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName'] ?? json['name']; moduleReferenceId = json['visitId']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; attachmentURL = json['attachmentURL']; } + GenericAttachmentModel.fromSupplierJson(Map json) { id = json['id']; name = json['attachmentName'] ?? json['name']; supplierId = json['supplierId']; moduleReferenceId = json['visitId']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; attachmentURL = json['attachmentURL']; } @@ -89,7 +115,7 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName']; moduleReferenceId = json['gasRefillId']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } GenericAttachmentModel.fromIncidentJson(Map json) { @@ -97,19 +123,21 @@ class GenericAttachmentModel { name = json['attachmentName']; moduleReferenceId = json['incidentId']; attachmentDescription = json['attachmentDescription']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } GenericAttachmentModel.fromAssetTransferJson(Map json) { id = json['id']; name = json['attachmentName']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } GenericAttachmentModel.fromDemoJson(Map json) { id = json['id']; name = json['attachmentName']; originalName = json['originalName']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; moduleReferenceId = json['demoRequestId']; - documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; } GenericAttachmentModel.fromInternalAuditJson(Map json) { @@ -117,19 +145,20 @@ class GenericAttachmentModel { name = (json['name'] != null && !json['name'].toString().startsWith('data:image/jpeg')) ? json['name'] : null; originalName = json['originalName']; createdBy = json['createdBy']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } GenericAttachmentModel.fromPreventiveVisitJson(Map json) { id = json['id']; name = json['attachmentName']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } GenericAttachmentModel.fromAssetJson(Map json) { id = json['id']; name = json['attachmentName']; attachmentURL = json['attachmentURL']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; originalName = json['originalName']; } @@ -137,10 +166,9 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName']; moduleReferenceId = json['trafId']; - documentType = json['documentType']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } - Map toJson() { final Map data = {}; data['id'] = id; @@ -156,6 +184,7 @@ class GenericAttachmentModel { data['id'] = id; data['name'] = name; data['createdBy'] = createdBy; + ///TODO need to keep same variable for document type in backend for all modules, currently it is different for different modules if (documentType != null) { data['attachmentTypeId'] = documentType?.id; @@ -189,6 +218,7 @@ class GenericAttachmentModel { data['modifiedDate'] = modifiedDate; return data; } + //TODO need to check where to use this need to verify with backend team. Map toPpmJson() { final Map data = {}; diff --git a/lib/modules/asset_delivery_module/pages/attachment_view.dart b/lib/modules/asset_delivery_module/pages/attachment_view.dart index 140c524b..ebcba992 100644 --- a/lib/modules/asset_delivery_module/pages/attachment_view.dart +++ b/lib/modules/asset_delivery_module/pages/attachment_view.dart @@ -97,7 +97,12 @@ class _AssetDeliveryAttachmentViewState extends State URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []).toShadowContainer( + : FilesList( showAsListView: true, + types: _attachments.map((doc) { + final attachmentType = doc.documentType?.name ?? ''; + return attachmentType.isNotEmpty ? attachmentType : 'Asset Guide'; + }).toList(), + images: _attachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '',).toList() ?? []).toShadowContainer( context, borderRadius: 20, padding: 12, diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index 4c6adb41..a4126d32 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -173,7 +173,18 @@ class _ActivitiesListViewState extends State { if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[ 2.height, const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePart!.acitiySparePartAttachments!.whereType().where((e) => e.name != null).map((toElement) => URLs.getFileUrl(toElement.name!)!).toList()), + FilesList( + showAsListView: true, + types: activity.activitySparePart!.acitiySparePartAttachments! + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: activity.activitySparePart!.acitiySparePartAttachments! + .whereType() + .where((e) => e.name != null) + .map((toElement) => URLs.getFileUrl(toElement.name!)!) + .toList()), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { @@ -217,7 +228,6 @@ class _ActivitiesListViewState extends State { ), ], ), - if (showActionButtons) Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -252,7 +262,6 @@ class _ActivitiesListViewState extends State { label: context.translation.assistantEmployee, value: activity.activityMaintenance?.assistantEmployees?.first.user?.userName, ), - ] else ...[ InfoTextWidget( label: context.translation.assignedEmployee, diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index ab0538e9..008bbe4a 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -270,7 +270,15 @@ class _ServiceRequestDetailViewState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), + FilesList( + showAsListView: true, + images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList(), + types: _attachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + ), ], if (!requestProvider.isReadOnlyRequest && workOrder.nextStep?.workOrderNextStepEnum == WorkOrderNextStepEnum.activity) ...[ const Divider().defaultStyle(context), diff --git a/lib/modules/demo_module/demo_activities_page.dart b/lib/modules/demo_module/demo_activities_page.dart index f9a7dc2c..a7baf9ef 100644 --- a/lib/modules/demo_module/demo_activities_page.dart +++ b/lib/modules/demo_module/demo_activities_page.dart @@ -3,6 +3,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/views/widgets/images/files_list.dart'; import '../../controllers/api_routes/urls.dart'; @@ -57,10 +58,17 @@ class DemoActivitiesPage extends StatelessWidget { "Attachments".addTranslation, style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50), ), - FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: allAttachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e ?? '') ?? '').toList()), ], ], - ).toShadowContainer(context, borderRadius: 14, backgroundColor: Color(0xffF4F8FC), showShadow: false), + ).toShadowContainer(context, borderRadius: 14, backgroundColor: const Color(0xffF4F8FC), showShadow: false), 16.height, Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/modules/incident_module/incident_detail_page.dart b/lib/modules/incident_module/incident_detail_page.dart index 88ebd029..d54f4b4d 100644 --- a/lib/modules/incident_module/incident_detail_page.dart +++ b/lib/modules/incident_module/incident_detail_page.dart @@ -71,7 +71,14 @@ class IncidentDetailPage extends StatelessWidget { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: allAttachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context), diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart index 5e0a8a9b..94a52200 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart @@ -118,7 +118,10 @@ class _EquipmentInternalAuditDetailPageState extends State URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: allAttachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).paddingAll(0).toShadowContainer(context), diff --git a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart index a473a75a..dda1f510 100644 --- a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart @@ -117,7 +117,14 @@ class _SystemInternalAuditDetailPageState extends State URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: allAttachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).paddingAll(0).toShadowContainer(context), diff --git a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart index 8a043dbd..49800d56 100644 --- a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart +++ b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart @@ -97,7 +97,14 @@ class _LoanEquipmentDetailPageState extends State { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: allAttachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context) diff --git a/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart b/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart index b499f20b..29eb131f 100644 --- a/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart +++ b/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart @@ -6,6 +6,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; import 'package:test_sa/modules/medical_gas_inspection/create_medical_gas_request_page.dart'; import 'package:test_sa/modules/medical_gas_inspection/models/medical_gas_data_model.dart'; @@ -103,7 +104,14 @@ class _MedicalGasInspectionDetailPageState extends State URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: model!.deliveryNoteAttachmentDto + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: model!.deliveryNoteAttachmentDto.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context,), diff --git a/lib/modules/tm_module/device_transfer/device_transfer_details.dart b/lib/modules/tm_module/device_transfer/device_transfer_details.dart index 82d36af0..6e683453 100644 --- a/lib/modules/tm_module/device_transfer/device_transfer_details.dart +++ b/lib/modules/tm_module/device_transfer/device_transfer_details.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/device_transfer.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/cx_module/chat/chat_widget.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/views/widgets/bottom_sheets/rejection_reason_bottom_sheet.dart'; @@ -121,7 +122,14 @@ class _DeviceTransferDetailsState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: _model?.assetTransferAttachments!=null? + _model!.assetTransferAttachments!.whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList():[], + images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ] ], ), diff --git a/lib/modules/tm_module/gas_refill/gas_refill_details.dart b/lib/modules/tm_module/gas_refill/gas_refill_details.dart index 3dc4fb3b..cfd42605 100644 --- a/lib/modules/tm_module/gas_refill/gas_refill_details.dart +++ b/lib/modules/tm_module/gas_refill/gas_refill_details.dart @@ -238,7 +238,10 @@ class _GasRefillDetailsPageState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: _model.gasRefillAttachments?.whereType().where((e) => e.name != null).map((e) => URLs.getFileUrl(e.name!) ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: _model.gasRefillAttachments?.whereType().where((e) => e.documentType != null && e.documentType!.name != null).map((toElement) => toElement.documentType!.name!).toList() ?? [], + images: _model.gasRefillAttachments?.whereType().where((e) => e.name != null).map((e) => URLs.getFileUrl(e.name!) ?? '').toList() ?? []), ], ], ).expanded, diff --git a/lib/modules/tm_module/tasks/task_request_detail_view.dart b/lib/modules/tm_module/tasks/task_request_detail_view.dart index 1102c9b7..13ad69f8 100644 --- a/lib/modules/tm_module/tasks/task_request_detail_view.dart +++ b/lib/modules/tm_module/tasks/task_request_detail_view.dart @@ -160,7 +160,10 @@ class _TaskRequestDetailsViewState extends State { if (taskProvider.taskRequestModel?.taskJobAttachments?.isNotEmpty ?? false) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), - FilesList(images: taskProvider.taskRequestModel!.taskJobAttachments!.whereType().where((e) => e.name != null).map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), + FilesList( + showAsListView: true, + types: taskProvider.taskRequestModel!.taskJobAttachments!.whereType().where((e) => e.name != null).map((toElement) => toElement.documentType?.name ?? '').toList(), + images: taskProvider.taskRequestModel!.taskJobAttachments!.whereType().where((e) => e.name != null).map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), ], buildTechnicalComments(taskModel: taskModel), ], diff --git a/lib/modules/traf_module/traf_request_detail_page.dart b/lib/modules/traf_module/traf_request_detail_page.dart index 32c839f7..16796bdb 100644 --- a/lib/modules/traf_module/traf_request_detail_page.dart +++ b/lib/modules/traf_module/traf_request_detail_page.dart @@ -155,7 +155,14 @@ class _TrafRequestDetailPageState extends State { style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50), ), // 8.height, - FilesList(images: _attachments.map((e) => URLs.getFileUrl(e.path ?? '') ?? '').toList() ?? []), + FilesList( + showAsListView: true, + types: _attachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: _attachments.map((e) => URLs.getFileUrl(e.path ?? '') ?? '').toList() ?? []), ], ], ).toShadowContainer(context); diff --git a/lib/views/widgets/equipment/asset_detail_page.dart b/lib/views/widgets/equipment/asset_detail_page.dart index 2d0e25b1..8144eb46 100644 --- a/lib/views/widgets/equipment/asset_detail_page.dart +++ b/lib/views/widgets/equipment/asset_detail_page.dart @@ -93,7 +93,7 @@ class _AssetDetailPageState extends State { TabBarView( children: [ AssetDetailsView(assetModel: assetModel!, onUpload: _upload), - const AssetDocumentHistoryView(), + AssetDocumentHistoryView(assetId: assetId!), ], ).expanded, ], diff --git a/lib/views/widgets/equipment/asset_details_view.dart b/lib/views/widgets/equipment/asset_details_view.dart index 8b86fcd5..a00ac9d9 100644 --- a/lib/views/widgets/equipment/asset_details_view.dart +++ b/lib/views/widgets/equipment/asset_details_view.dart @@ -321,7 +321,14 @@ class _AssetDetailsViewState extends State with SingleTickerPr opacity: attachmentAnimation, child: SlideTransition( position: attachmentSlideAnimation, - child: FilesList(images: attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), + child: FilesList( + showAsListView: true, + types: attachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), ), ), ] diff --git a/lib/views/widgets/equipment/asset_document_history_view.dart b/lib/views/widgets/equipment/asset_document_history_view.dart index 68cc3b02..701824a2 100644 --- a/lib/views/widgets/equipment/asset_document_history_view.dart +++ b/lib/views/widgets/equipment/asset_document_history_view.dart @@ -1,29 +1,155 @@ +import 'dart:developer'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/controllers/providers/api/devices_provider.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/views/widgets/images/files_list.dart'; +import 'package:test_sa/views/widgets/item_views/info_text_widget.dart'; +import 'package:test_sa/views/widgets/loaders/app_loading.dart'; +import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; -class AssetDocumentHistoryView extends StatelessWidget { - const AssetDocumentHistoryView({Key? key}) : super(key: key); +class AssetDocumentHistoryView extends StatefulWidget { + final int assetId; + + const AssetDocumentHistoryView({ + Key? key, + required this.assetId, + }) : super(key: key); + + @override + State createState() => _AssetDocumentHistoryViewState(); +} + +class _AssetDocumentHistoryViewState extends State { + late AssetProvider _assetProvider; + final ScrollController _scrollController = ScrollController(); + List _documents = []; + bool _isLoading = false; + int _currentPage = 1; + int _totalRows = 0; + + @override + void initState() { + super.initState(); + _assetProvider = context.read(); + _scrollController.addListener(_onScroll); + _loadDocuments(); + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + void _onScroll() { + final pixels = _scrollController.position.pixels; + final maxScroll = _scrollController.position.maxScrollExtent; + if (pixels >= maxScroll * 0.8) { + if (!_isLoading && _hasMore) { + _loadMore(); + } + } + } + + bool get _hasMore => _documents.length < _totalRows; + + Future _loadDocuments({bool refresh = false, bool loadMore = false}) async { + if (_isLoading) return; + setState(() { + _isLoading = true; + if (refresh) { + _documents.clear(); + _currentPage = 1; + } + if (loadMore) { + _currentPage++; + } + }); + try { + final result = await _assetProvider.getAssetDocumentHistory( + assetId: widget.assetId, + pageNumber: _currentPage, + ); + if (mounted) { + setState(() { + if (refresh) { + _documents = result.documents; + } else { + _documents.addAll(result.documents); + } + _totalRows = result.totalRows; + _isLoading = false; + }); + } + } catch (e) { + log('Error loading documents: $e'); + if (mounted) { + setState(() { + _isLoading = false; + }); + } + } + } + + Future _loadMore() async { + await _loadDocuments(loadMore: true); + } + + Future _onRefresh() async { + await _loadDocuments(refresh: true); + } @override Widget build(BuildContext context) { - final List dummyDocuments = [ - 'https://picsum.photos/200/300?random=1', - 'https://picsum.photos/200/300?random=2', - 'https://picsum.photos/200/300?random=3', - 'https://picsum.photos/200/300?random=4', - 'https://picsum.photos/200/300?random=5', - ]; - - return SingleChildScrollView( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: FilesList( - showAsListView: true, - showDownloadButton: true, - images: dummyDocuments, - separator: const Divider().defaultStyle(context), - ).toShadowContainer(context), + if (_isLoading && _documents.isEmpty) { + return const Center(child: ALoading()); + } + if (_documents.isEmpty && !_isLoading) { + return const Center(child: NoDataFound()); + } + return RefreshIndicator( + onRefresh: _onRefresh, + child: ListView( + controller: _scrollController, + padding: EdgeInsets.symmetric( + horizontal: 16.toScreenWidth, + ), + children: [ + FilesList( + showAsListView: true, + showDownloadButton: true, + itemGap: 12.toScreenHeight, + images: _documents + .map((doc) { + return URLs.getFileUrl(doc.name) ?? ''; + }).where((url) => url.isNotEmpty).toList(), + types: _documents.map((doc) { + final attachmentType = doc.documentType?.name ?? ''; + return attachmentType.isNotEmpty ? attachmentType : 'Asset Guide'; + }).toList(), + ).toShadowContainer(context), + if (_isLoading && _documents.isNotEmpty&&_hasMore) ...[ + 16.height, + Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const ALoading(), + 8.height, + const InfoTextLabelWidget(label: 'Loading more...'), + ], + ), + ), + ), + ], + ], + ), ); } } diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 8bfba4da..f1af8d30 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -1,5 +1,4 @@ import 'dart:io'; - import 'package:ellipsized_text/ellipsized_text.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; @@ -10,7 +9,6 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; -import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/views/widgets/loaders/image_loader.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -24,7 +22,7 @@ class FilesList extends StatelessWidget { final double? itemGap; final Widget? separator; - const FilesList({Key? key, this.separator, this.images = const [], this.types = const [], this.padding, this.showAsListView = false, this.showDownloadButton = false, this.itemGap}) + const FilesList({Key? key, this.separator, this.images = const [], this.types = const [], this.padding, required this.showAsListView, this.showDownloadButton = false, this.itemGap}) : super(key: key); @override @@ -75,8 +73,9 @@ class FilesList extends StatelessWidget { children: [ EllipsizedText( images[itemIndex].split("/").last, - style: AppTextStyles.bodyText.copyWith(color: AppColor.textStyleColor(context)), - type: EllipsisType.start, // or EllipsisType.middle + style: AppTextStyles.bodyText2.copyWith(color: AppColor.labelTextStyleColor(context)), + // style: AppTextStyles.bodyText.copyWith(color: AppColor.textStyleColor(context)), + type: EllipsisType.start, ), 2.height, RichText( From d7c8d9f3cf97e985071dce9ede3ec1d44bc5ecc2 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Wed, 19 Aug 2026 15:50:31 +0300 Subject: [PATCH 15/47] rename changes, apk provided to FM. --- .../ppm_wo/activities/pm_activities_list_view.dart | 7 ++----- lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index d9a43385..a9a1542f 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -52,10 +52,7 @@ class _PmActivitiesListViewState extends State { Widget build(BuildContext context) { UserProvider userProvider = Provider.of(context); return Scaffold( - appBar: DefaultAppBar( - showHomeActionButton: true, - title: context.translation.activities, - ), + appBar: const DefaultAppBar(title: "Spare Part Requests"), body: Consumer(builder: (context, PpmProvider pmProvider, child) { activities = pmProvider.planPreventiveVisit?.activities ?? []; if (activities.isNotEmpty && (activities.last.activityStatus!.value == 14 || activities.last.activityStatus!.value == 19)) { @@ -80,7 +77,7 @@ class _PmActivitiesListViewState extends State { FooterActionButton.footerContainer( context: context, child: AppFilledButton( - label: context.translation.createNewActivity, + label: "Create Spare Part Request", maxWidth: true, buttonColor: AppColor.primary10, loading: pmProvider.isLoading, diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart index 0e5a39ab..0060c4e9 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/update_ppm.dart @@ -288,7 +288,7 @@ class _UpdatePpmState extends State with TickerProviderStateMixin { Navigator.of(context).push(MaterialPageRoute(builder: (_) => const PmActivitiesListView())); }, buttonColor: context.isDark ? AppColor.primary10 : AppColor.neutral50, - label: "View Spare Parts", + label: "Spare Parts", ), ], ), From 5f91a195f4590a51352752e0f758594f5f760925 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Thu, 20 Aug 2026 16:04:45 +0300 Subject: [PATCH 16/47] improvement --- lib/modules/demo_module/demo_request_item_view.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/modules/demo_module/demo_request_item_view.dart b/lib/modules/demo_module/demo_request_item_view.dart index 6abc6d58..6d8dd30c 100644 --- a/lib/modules/demo_module/demo_request_item_view.dart +++ b/lib/modules/demo_module/demo_request_item_view.dart @@ -28,7 +28,7 @@ class DemoRequestItemView extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ StatusLabel( - label: requestData!.statusName!, + label: requestData!.statusName, textColor: AppColor.demoRequestStatusTextColor(context, requestData?.statusValue ?? 0), backgroundColor: AppColor.demoRequestStatus(context, requestData?.statusValue ?? 0), ), @@ -54,7 +54,7 @@ class DemoRequestItemView extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ StatusLabel( - label: requestDetails!.status!, + label: requestDetails!.status, textColor: AppColor.demoRequestStatusTextColor(context, requestDetails?.statusValue ?? 0), backgroundColor: AppColor.demoRequestStatus(context, requestDetails?.statusValue ?? 0), ), From 56322d8db35c3c2f1c2257688f4d4e6956a2120a Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Tue, 25 Aug 2026 09:39:58 +0300 Subject: [PATCH 17/47] Add Document Type Lookup for each module --- lib/controllers/api_routes/urls.dart | 3 +- lib/dashboard_latest/dashboard_provider.dart | 82 +++---- lib/dashboard_latest/dashboard_view.dart | 20 +- .../widgets/request_category_fragment.dart | 2 +- .../widgets/requests_fragment.dart | 22 +- lib/extensions/enum_extensions.dart | 2 +- .../enums/request_attachment_type_enum.dart | 206 ++++++++++++++++++ lib/models/generic_attachment_model.dart | 11 + .../task_request/task_request_model.dart | 6 +- .../pages/attachment_view.dart | 30 ++- .../provider/attachment_type_provider.dart | 15 +- .../pages/asset_inventory_form_view.dart | 4 +- lib/modules/cm_module/create_cm_request.dart | 2 + .../components/activities_list_view.dart | 2 + .../service_request_detail_view.dart | 38 ++-- .../forms/asset_retired/asset_retired.dart | 2 + .../forms/spare_part/spare_part_request.dart | 2 + .../demo_module/create_demo_request_page.dart | 6 +- .../demo_module/demo_activities_page.dart | 6 +- .../demo_module/update_demo-request_view.dart | 4 +- .../create_incident_request_page.dart | 2 + .../create_equipment_internal_audit_form.dart | 2 + .../equipment_internal_audit_detail_page.dart | 6 +- .../update_equipment_internal_audit_page.dart | 2 + .../create_system_internal_audit_form.dart | 2 + .../update_system_internal_audit_page.dart | 2 + .../pages/create_loan_request_page.dart | 2 + .../pages/installation_form_view.dart | 2 + .../pages/installation_pullout_form_view.dart | 2 + .../update_delivery_notes_page.dart | 2 + .../update_medical_gas_inspection_page.dart | 2 + .../ppm_wo/update_ppm/wo_info_form.dart | 2 + .../create_device_transfer_request.dart | 2 + .../update_device_transfer.dart | 2 + .../gas_refill/gas_refill_request_form.dart | 2 + .../gas_refill/update_gas_refill_request.dart | 2 + .../tm_module/tasks/create_task_view.dart | 7 +- .../tasks/update_task_request_view.dart | 2 + .../traf_module/create_traf_request_page.dart | 2 + .../traf_module/traf_request_detail_page.dart | 7 +- .../traf_module/update_traf_request_page.dart | 2 + .../task_job_provider.dart | 2 - .../widgets/equipment/asset_details_view.dart | 1 + .../equipment/asset_image_upload_page.dart | 4 +- .../widgets/images/multi_image_picker.dart | 18 +- 45 files changed, 423 insertions(+), 123 deletions(-) create mode 100644 lib/models/enums/request_attachment_type_enum.dart diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 620d367f..d2204b85 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -309,7 +309,8 @@ class URLs { static get genderLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=3065"; static get getDemoDocumentTypes => "$_baseUrl/Lookups/GetLookup?lookupEnum=4106"; - static get getAttachmentTypesLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=4021"; + // static get getAttachmentTypesLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=4021"; + static get getAttachmentTypesLookup => "$_baseUrl/Lookups/GetLookup"; static get getClassificationTypeLookup => "$_baseUrl/Lookups/GetLookup?lookupEnum=450"; diff --git a/lib/dashboard_latest/dashboard_provider.dart b/lib/dashboard_latest/dashboard_provider.dart index a25a10fe..68524413 100644 --- a/lib/dashboard_latest/dashboard_provider.dart +++ b/lib/dashboard_latest/dashboard_provider.dart @@ -56,7 +56,7 @@ class DashBoardProvider extends ChangeNotifier { // Helper method to check if a tab index is UnAssigned bool isUnassignedTab(int index) { if (index >= 0 && index < tabs.length) { - return tabs[index].requestType == RequestTypeEnum.unassigned; + return tabs[index].requestType == RequestStatusEnum.unassigned; } return false; } @@ -64,7 +64,7 @@ class DashBoardProvider extends ChangeNotifier { // Helper method to get the UnAssigned tab index (returns -1 if not found) int getUnassignedTabIndex() { for (int i = 0; i < tabs.length; i++) { - if (tabs[i].requestType == RequestTypeEnum.unassigned) { + if (tabs[i].requestType == RequestStatusEnum.unassigned) { return i; } } @@ -111,25 +111,25 @@ class DashBoardProvider extends ChangeNotifier { DD.DashboardDetail? get requestDetailList => _requestDetailList; - int getStatusCount(RequestTypeEnum requestType) { + int getStatusCount(RequestStatusEnum requestType) { switch (requestType) { - case RequestTypeEnum.unassigned: + case RequestStatusEnum.unassigned: return dashboardCount?.data?.countUnAssigned ?? 0; - case RequestTypeEnum.open: + case RequestStatusEnum.open: return dashboardCount?.data?.countOpen ?? 0; - case RequestTypeEnum.inProgress: + case RequestStatusEnum.inProgress: return dashboardCount?.data?.countInprogress ?? 0; - case RequestTypeEnum.completed: + case RequestStatusEnum.completed: return dashboardCount?.data?.countComplete ?? 0; - case RequestTypeEnum.pendingAcknowledgment: + case RequestStatusEnum.pendingAcknowledgment: return dashboardCount?.data?.countAcknowledge ?? 0; - case RequestTypeEnum.canceled: + case RequestStatusEnum.canceled: return dashboardCount?.data?.countCanceled ?? 0; - case RequestTypeEnum.closed: + case RequestStatusEnum.closed: return dashboardCount?.data?.countClose ?? 0; - case RequestTypeEnum.overdue: + case RequestStatusEnum.overdue: return dashboardCount?.data?.countOverdue ?? 0; - case RequestTypeEnum.highPriority: + case RequestStatusEnum.highPriority: return dashboardCount?.data?.countHighPriority ?? 0; default: return 0; @@ -310,30 +310,30 @@ class DashBoardProvider extends ChangeNotifier { } // Status categories (Open, InProgress, Completed, Closed) - if (!tab.isHighPriority && !tab.isOverDue && tab.requestType != RequestTypeEnum.unassigned) { + if (!tab.isHighPriority && !tab.isOverDue && tab.requestType != RequestStatusEnum.unassigned) { // Map requestType to status value switch (tab.requestType) { - case RequestTypeEnum.open: + case RequestStatusEnum.open: if (!statusTransaction.contains(1)) statusTransaction.add(1); break; - case RequestTypeEnum.inProgress: + case RequestStatusEnum.inProgress: if (!statusTransaction.contains(2)) statusTransaction.add(2); break; - case RequestTypeEnum.completed: + case RequestStatusEnum.completed: if (!statusTransaction.contains(4)) statusTransaction.add(4); break; - case RequestTypeEnum.closed: + case RequestStatusEnum.closed: if (!statusTransaction.contains(4)) statusTransaction.add(4); break; - case RequestTypeEnum.canceled: + case RequestStatusEnum.canceled: if (!statusTransaction.contains(5)) statusTransaction.add(5); break; - case RequestTypeEnum.pendingAcknowledgment: + case RequestStatusEnum.pendingAcknowledgment: if (!statusTransaction.contains(4)) statusTransaction.add(4); break; - case RequestTypeEnum.unassigned: - case RequestTypeEnum.highPriority: - case RequestTypeEnum.overdue: + case RequestStatusEnum.unassigned: + case RequestStatusEnum.highPriority: + case RequestStatusEnum.overdue: // These are handled separately above break; } @@ -556,7 +556,7 @@ class CategoryTabs { String label; int tag; int id; - RequestTypeEnum requestType; + RequestStatusEnum requestType; String icon; Color iconColor; bool isHighPriority; @@ -568,12 +568,12 @@ class CategoryTabs { List tabs = []; if (userType == UsersTypes.engineer) { // Order: 1-UnAssigned, 2-HighPriority, 3-Overdue, 4-Open, 5-InProgress, 6-Completed - tabs.add(CategoryTabs(label: 'UnAssigned', tag: 1, id: 1, requestType: RequestTypeEnum.unassigned, icon: "dashboard/unassigned", iconColor: AppColor.unassignedStatus(context))); - tabs.add(CategoryTabs(label: context.translation.highPriority, tag: 3, id: 4, requestType: RequestTypeEnum.highPriority, icon: "high_priority", iconColor: AppColor.red30, isHighPriority: true)); - tabs.add(CategoryTabs(label: context.translation.overdue, tag: 3, id: 4, requestType: RequestTypeEnum.overdue, icon: "overdue", iconColor: AppColor.yellowIcon(context), isOverDue: true)); - tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestTypeEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); - tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestTypeEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); - tabs.add(CategoryTabs(label: 'Completed', tag: 3, id: 4, requestType: RequestTypeEnum.completed, icon: "complete_request", iconColor: AppColor.completedColor)); + tabs.add(CategoryTabs(label: 'UnAssigned', tag: 1, id: 1, requestType: RequestStatusEnum.unassigned, icon: "dashboard/unassigned", iconColor: AppColor.unassignedStatus(context))); + tabs.add(CategoryTabs(label: context.translation.highPriority, tag: 3, id: 4, requestType: RequestStatusEnum.highPriority, icon: "high_priority", iconColor: AppColor.red30, isHighPriority: true)); + tabs.add(CategoryTabs(label: context.translation.overdue, tag: 3, id: 4, requestType: RequestStatusEnum.overdue, icon: "overdue", iconColor: AppColor.yellowIcon(context), isOverDue: true)); + tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestStatusEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); + tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestStatusEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); + tabs.add(CategoryTabs(label: 'Completed', tag: 3, id: 4, requestType: RequestStatusEnum.completed, icon: "complete_request", iconColor: AppColor.completedColor)); return tabs; } @@ -584,29 +584,29 @@ class CategoryTabs { // tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 2)); // tabs.add(CategoryTabs(label: 'Completed', tag: 4, id: 3)); - tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 2, requestType: RequestTypeEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); - tabs.add(CategoryTabs(label: 'Completed', tag: 4, id: 3, requestType: RequestTypeEnum.completed, icon: "complete_request", iconColor: AppColor.completedColor)); + tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 2, requestType: RequestStatusEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); + tabs.add(CategoryTabs(label: 'Completed', tag: 4, id: 3, requestType: RequestStatusEnum.completed, icon: "complete_request", iconColor: AppColor.completedColor)); return tabs; } if (userType == UsersTypes.qualityUser) { - tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestTypeEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); - tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestTypeEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); - tabs.add(CategoryTabs(label: 'Closed', tag: 3, id: 4, requestType: RequestTypeEnum.closed, icon: "complete_request", iconColor: AppColor.completedColor)); + tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestStatusEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); + tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestStatusEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); + tabs.add(CategoryTabs(label: 'Closed', tag: 3, id: 4, requestType: RequestStatusEnum.closed, icon: "complete_request", iconColor: AppColor.completedColor)); return tabs; } if (userType == UsersTypes.commissioningEngineer) { - tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestTypeEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); - tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestTypeEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); - tabs.add(CategoryTabs(label: 'Closed', tag: 3, id: 4, requestType: RequestTypeEnum.closed, icon: "complete_request", iconColor: AppColor.completedColor)); + tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestStatusEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); + tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestStatusEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); + tabs.add(CategoryTabs(label: 'Closed', tag: 3, id: 4, requestType: RequestStatusEnum.closed, icon: "complete_request", iconColor: AppColor.completedColor)); return tabs; } - tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestTypeEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); - tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestTypeEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); + tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2, requestType: RequestStatusEnum.open, icon: "dashboard/open_icon", iconColor: AppColor.openColor)); + tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3, requestType: RequestStatusEnum.inProgress, icon: "dashboard/inprogress_icon", iconColor: AppColor.primary10)); // tabs.add(CategoryTabs(label: 'Pending Acknowledgement', tag: 3, id: 1, requestType: RequestTypeEnum.pendingAcknowledgment, icon: "complete_request", iconColor: AppColor.overdueColor)); - tabs.add(CategoryTabs(label: 'Acknowledgement', tag: 4, id: 1, requestType: RequestTypeEnum.pendingAcknowledgment, icon: "complete_request", iconColor: AppColor.overdueColor)); - tabs.add(CategoryTabs(label: 'Canceled', tag: 6, id: 4, requestType: RequestTypeEnum.canceled, icon: "dashboard/unassigned", iconColor: AppColor.red30)); + tabs.add(CategoryTabs(label: 'Acknowledgement', tag: 4, id: 1, requestType: RequestStatusEnum.pendingAcknowledgment, icon: "complete_request", iconColor: AppColor.overdueColor)); + tabs.add(CategoryTabs(label: 'Canceled', tag: 6, id: 4, requestType: RequestStatusEnum.canceled, icon: "dashboard/unassigned", iconColor: AppColor.red30)); return tabs; } } diff --git a/lib/dashboard_latest/dashboard_view.dart b/lib/dashboard_latest/dashboard_view.dart index 6de6e88b..70d1ffb9 100644 --- a/lib/dashboard_latest/dashboard_view.dart +++ b/lib/dashboard_latest/dashboard_view.dart @@ -147,29 +147,29 @@ class _DashboardViewState extends State { } // Status categories - if (!tab.isHighPriority && !tab.isOverDue && tab.requestType != RequestTypeEnum.unassigned) { + if (!tab.isHighPriority && !tab.isOverDue && tab.requestType != RequestStatusEnum.unassigned) { switch (tab.requestType) { - case RequestTypeEnum.open: + case RequestStatusEnum.open: if (!statusTransaction.contains(1)) statusTransaction.add(1); break; - case RequestTypeEnum.inProgress: + case RequestStatusEnum.inProgress: if (!statusTransaction.contains(2)) statusTransaction.add(2); break; - case RequestTypeEnum.completed: + case RequestStatusEnum.completed: if (!statusTransaction.contains(4)) statusTransaction.add(4); break; - case RequestTypeEnum.closed: + case RequestStatusEnum.closed: if (!statusTransaction.contains(4)) statusTransaction.add(4); break; - case RequestTypeEnum.canceled: + case RequestStatusEnum.canceled: if (!statusTransaction.contains(5)) statusTransaction.add(5); break; - case RequestTypeEnum.pendingAcknowledgment: + case RequestStatusEnum.pendingAcknowledgment: if (!statusTransaction.contains(3)) statusTransaction.add(3); break; - case RequestTypeEnum.unassigned: - case RequestTypeEnum.highPriority: - case RequestTypeEnum.overdue: + case RequestStatusEnum.unassigned: + case RequestStatusEnum.highPriority: + case RequestStatusEnum.overdue: break; } } diff --git a/lib/dashboard_latest/widgets/request_category_fragment.dart b/lib/dashboard_latest/widgets/request_category_fragment.dart index c6f80cad..2ebaf87e 100644 --- a/lib/dashboard_latest/widgets/request_category_fragment.dart +++ b/lib/dashboard_latest/widgets/request_category_fragment.dart @@ -380,7 +380,7 @@ class _RequestCategoryFragmentState extends State with }); // Check if this is UnAssigned tab (index 0 for engineer) - bool isUnassignedTab = tabs[index].requestType == RequestTypeEnum.unassigned; + bool isUnassignedTab = tabs[index].requestType == RequestStatusEnum.unassigned; // Update selection state requestsProvider.currentListIndex = index; diff --git a/lib/dashboard_latest/widgets/requests_fragment.dart b/lib/dashboard_latest/widgets/requests_fragment.dart index e613d0eb..2be44381 100644 --- a/lib/dashboard_latest/widgets/requests_fragment.dart +++ b/lib/dashboard_latest/widgets/requests_fragment.dart @@ -46,24 +46,24 @@ class RequestsFragment extends StatelessWidget { List listItems = []; if (context.userProvider.isNurse) { listItems = [ - requestType(data.dashboardCount?.data?.countOpen ?? 0, "dashboard/open_icon", context.translation.open, context, data.isLoading, RequestTypeEnum.open, AppColor.openColor), - requestType(data.dashboardCount?.data?.countInprogress ?? 0, "dashboard/inprogress_icon", context.translation.inProgress, context, data.isLoading, RequestTypeEnum.inProgress, + requestType(data.dashboardCount?.data?.countOpen ?? 0, "dashboard/open_icon", context.translation.open, context, data.isLoading, RequestStatusEnum.open, AppColor.openColor), + requestType(data.dashboardCount?.data?.countInprogress ?? 0, "dashboard/inprogress_icon", context.translation.inProgress, context, data.isLoading, RequestStatusEnum.inProgress, AppColor.primary10), requestType( - data.dashboardCount?.data?.countAcknowledge ?? 0, "complete_request", "Acknowledgement", context, data.isLoading, RequestTypeEnum.pendingAcknowledgment, AppColor.overdueColor), - requestType(data.dashboardCount?.data?.countCanceled ?? 0, "dashboard/unassigned", "Canceled", context, data.isLoading, RequestTypeEnum.canceled, AppColor.red30), + data.dashboardCount?.data?.countAcknowledge ?? 0, "complete_request", "Acknowledgement", context, data.isLoading, RequestStatusEnum.pendingAcknowledgment, AppColor.overdueColor), + requestType(data.dashboardCount?.data?.countCanceled ?? 0, "dashboard/unassigned", "Canceled", context, data.isLoading, RequestStatusEnum.canceled, AppColor.red30), ]; } else { listItems = [ requestType( - data.dashboardCount?.data?.countUnAssigned ?? 0, "dashboard/unassigned", "UnAssigned", context, data.isLoading, RequestTypeEnum.unassigned, AppColor.unassignedStatus(context)), - requestType(data.dashboardCount?.data?.countOpen ?? 0, "dashboard/open_icon", context.translation.open, context, data.isLoading, RequestTypeEnum.open, AppColor.openColor), - requestType(data.dashboardCount?.data?.countInprogress ?? 0, "dashboard/inprogress_icon", context.translation.inProgress, context, data.isLoading, RequestTypeEnum.inProgress, + data.dashboardCount?.data?.countUnAssigned ?? 0, "dashboard/unassigned", "UnAssigned", context, data.isLoading, RequestStatusEnum.unassigned, AppColor.unassignedStatus(context)), + requestType(data.dashboardCount?.data?.countOpen ?? 0, "dashboard/open_icon", context.translation.open, context, data.isLoading, RequestStatusEnum.open, AppColor.openColor), + requestType(data.dashboardCount?.data?.countInprogress ?? 0, "dashboard/inprogress_icon", context.translation.inProgress, context, data.isLoading, RequestStatusEnum.inProgress, AppColor.primary10), requestType( - data.dashboardCount?.data?.countComplete ?? 0, "complete_request", context.translation.completed, context, data.isLoading, RequestTypeEnum.completed, AppColor.completedColor), - requestType(data.dashboardCount?.data?.countOverdue ?? 0, "overdue", context.translation.overdue, context, data.isLoading, RequestTypeEnum.overdue, AppColor.yellowIcon(context)), - requestType(data.dashboardCount?.data?.countHighPriority ?? 0, "high_priority", context.translation.highPriority, context, data.isLoading, RequestTypeEnum.highPriority, AppColor.red30), + data.dashboardCount?.data?.countComplete ?? 0, "complete_request", context.translation.completed, context, data.isLoading, RequestStatusEnum.completed, AppColor.completedColor), + requestType(data.dashboardCount?.data?.countOverdue ?? 0, "overdue", context.translation.overdue, context, data.isLoading, RequestStatusEnum.overdue, AppColor.yellowIcon(context)), + requestType(data.dashboardCount?.data?.countHighPriority ?? 0, "high_priority", context.translation.highPriority, context, data.isLoading, RequestStatusEnum.highPriority, AppColor.red30), ]; } @@ -77,7 +77,7 @@ class RequestsFragment extends StatelessWidget { }); } - Widget requestType(int value, String icon, String title, BuildContext context, bool isLoading, RequestTypeEnum requestType, Color iconColor) { + Widget requestType(int value, String icon, String title, BuildContext context, bool isLoading, RequestStatusEnum requestType, Color iconColor) { return CustomBadge( value: isLoading ? 0 : value, positionR: -4, diff --git a/lib/extensions/enum_extensions.dart b/lib/extensions/enum_extensions.dart index 5039329c..a3275466 100644 --- a/lib/extensions/enum_extensions.dart +++ b/lib/extensions/enum_extensions.dart @@ -197,7 +197,7 @@ enum AssetDeliveryStageEnum { other, } -enum RequestTypeEnum { +enum RequestStatusEnum { unassigned, open, inProgress, diff --git a/lib/models/enums/request_attachment_type_enum.dart b/lib/models/enums/request_attachment_type_enum.dart new file mode 100644 index 00000000..8bffa130 --- /dev/null +++ b/lib/models/enums/request_attachment_type_enum.dart @@ -0,0 +1,206 @@ + +enum RequestAttachmentTypeEnum { + correctiveMaintenance, // 1 + gasRefill, // 2 + transferAsset, // 3 + preventiveMaintenance, // 4 + recurrentWo, // 5 + taskRequest, // 6 + recallAndAlert, // 7 + assetInventory, // 8 + assessmentOfNeedAndTechnology, // 9 + equipmentInternalAudit, // 10 + systemInternalAudit, // 11 + loanEquipment, // 12 + assetDelivery, // 13 + medicalGasInspection, // 14 + demo, // 15 + incidents, // 16 + sparePartActivity, // 17 + updateDeliveryNotes, // 18 + traf, // 19 +} + +extension RequestAttachmentTypeEnumExtension on RequestAttachmentTypeEnum { + int get id { + switch (this) { + case RequestAttachmentTypeEnum.correctiveMaintenance: + return 1; + case RequestAttachmentTypeEnum.gasRefill: + return 2; + case RequestAttachmentTypeEnum.transferAsset: + return 3; + case RequestAttachmentTypeEnum.preventiveMaintenance: + return 4; + case RequestAttachmentTypeEnum.recurrentWo: + return 5; + case RequestAttachmentTypeEnum.taskRequest: + return 6; + case RequestAttachmentTypeEnum.recallAndAlert: + return 7; + case RequestAttachmentTypeEnum.assetInventory: + return 8; + case RequestAttachmentTypeEnum.assessmentOfNeedAndTechnology: + return 9; + case RequestAttachmentTypeEnum.equipmentInternalAudit: + return 10; + case RequestAttachmentTypeEnum.systemInternalAudit: + return 11; + case RequestAttachmentTypeEnum.loanEquipment: + return 12; + case RequestAttachmentTypeEnum.assetDelivery: + return 13; + case RequestAttachmentTypeEnum.medicalGasInspection: + return 14; + case RequestAttachmentTypeEnum.demo: + return 15; + case RequestAttachmentTypeEnum.incidents: + return 16; + case RequestAttachmentTypeEnum.sparePartActivity: + return 17; + case RequestAttachmentTypeEnum.updateDeliveryNotes: + return 18; + case RequestAttachmentTypeEnum.traf: + return 19; + } + } + int get lookupEnumId { + switch (this) { + ///values with 0 we need to check with backend team for the correct lookupEnumId + case RequestAttachmentTypeEnum.correctiveMaintenance: + return 40305; + case RequestAttachmentTypeEnum.gasRefill: + return 40307; + case RequestAttachmentTypeEnum.transferAsset: + return 40304; + case RequestAttachmentTypeEnum.preventiveMaintenance: + return 40313; + case RequestAttachmentTypeEnum.recurrentWo: + return 40314; + case RequestAttachmentTypeEnum.taskRequest: + return 40317; + case RequestAttachmentTypeEnum.recallAndAlert: + return 40316; + case RequestAttachmentTypeEnum.assetInventory: + return 40303; + case RequestAttachmentTypeEnum.assessmentOfNeedAndTechnology: + return 40319; + case RequestAttachmentTypeEnum.equipmentInternalAudit: + return 40323; + case RequestAttachmentTypeEnum.systemInternalAudit: + return 40322; + case RequestAttachmentTypeEnum.loanEquipment: + return 3053; + case RequestAttachmentTypeEnum.assetDelivery: + return 5009; + case RequestAttachmentTypeEnum.medicalGasInspection: + return 3012; + case RequestAttachmentTypeEnum.demo: + return 4106; + case RequestAttachmentTypeEnum.incidents: + return 40308; + case RequestAttachmentTypeEnum.sparePartActivity: + return 40321; + case RequestAttachmentTypeEnum.updateDeliveryNotes: + return 40309; + case RequestAttachmentTypeEnum.traf: + return 40319; + } + } + // String getName(BuildContext context) { + // switch (this) { + // case RequestTypeEnum.correctiveMaintenance: + // return context.translation.correctiveMaintenance; + // case RequestTypeEnum.gasRefill: + // return context.translation.gasRefill; + // case RequestTypeEnum.transferAsset: + // return context.translation.transferAsset; + // case RequestTypeEnum.preventiveMaintenance: + // return context.translation.preventiveMaintenance; + // case RequestTypeEnum.recurrentWo: + // return context.translation.recurrentWo; + // case RequestTypeEnum.taskRequest: + // return context.translation.taskRequest; + // case RequestTypeEnum.recallAndAlert: + // return 'Recall and Alert'; + // case RequestTypeEnum.assetInventory: + // return 'Asset Inventory'; + // case RequestTypeEnum.assessmentOfNeedAndTechnology: + // return 'Assessment of Need & Technology'; + // case RequestTypeEnum.equipmentInternalAudit: + // return 'Equipment Internal Audit'; + // case RequestTypeEnum.systemInternalAudit: + // return 'System Internal Audit'; + // case RequestTypeEnum.loanEquipment: + // return 'Loan Equipment'; + // case RequestTypeEnum.assetDelivery: + // return 'Asset Delivery'; + // case RequestTypeEnum.medicalGasInspection: + // return 'Medical Gas Inspection'; + // case RequestTypeEnum.demo: + // return 'Demo'; + // case RequestTypeEnum.incidents: + // return 'Incidents'; + // case RequestTypeEnum.sparePartActivity: + // return 'Spare Part Activity'; + // case RequestTypeEnum.updateDeliveryNotes: + // return 'Update Delivery Notes'; + // case RequestTypeEnum.traf: + // return 'Traf'; + // } + // } + + static RequestAttachmentTypeEnum? fromId(int? id) { + if (id == null) return null; + switch (id) { + case 1: + return RequestAttachmentTypeEnum.correctiveMaintenance; + case 2: + return RequestAttachmentTypeEnum.gasRefill; + case 3: + return RequestAttachmentTypeEnum.transferAsset; + case 4: + return RequestAttachmentTypeEnum.preventiveMaintenance; + case 5: + return RequestAttachmentTypeEnum.recurrentWo; + case 6: + return RequestAttachmentTypeEnum.taskRequest; + case 7: + return RequestAttachmentTypeEnum.recallAndAlert; + case 8: + return RequestAttachmentTypeEnum.assetInventory; + case 9: + return RequestAttachmentTypeEnum.assessmentOfNeedAndTechnology; + case 10: + return RequestAttachmentTypeEnum.equipmentInternalAudit; + case 11: + return RequestAttachmentTypeEnum.systemInternalAudit; + case 12: + return RequestAttachmentTypeEnum.loanEquipment; + case 13: + return RequestAttachmentTypeEnum.assetDelivery; + case 14: + return RequestAttachmentTypeEnum.medicalGasInspection; + case 15: + return RequestAttachmentTypeEnum.demo; + case 16: + return RequestAttachmentTypeEnum.incidents; + case 17: + return RequestAttachmentTypeEnum.sparePartActivity; + case 18: + return RequestAttachmentTypeEnum.updateDeliveryNotes; + case 19: + return RequestAttachmentTypeEnum.traf; + default: + return null; + } + } + // static String getNameFromId(int id, BuildContext context) { + // final requestType = fromId(id); + // return requestType?.getName(context) ?? "Type $id"; + // } + static int? getLookupEnumIdFromId(int? id) { + final requestType = fromId(id); + return requestType?.lookupEnumId; + } +} \ No newline at end of file diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index a59e5b0f..684c3c61 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/models/lookup.dart'; @@ -314,4 +316,13 @@ class GenericAttachmentModel { data['attachmentURL'] = attachmentURL; return data; } + Map toTaskJson() { + final Map data = {}; + data['id'] = id; + data['name'] = name; + data['createdBy'] = createdBy; + data['originalName'] = originalName; + data['attachmentTypeId'] = documentType?.id; + return data; + } } diff --git a/lib/models/new_models/task_request/task_request_model.dart b/lib/models/new_models/task_request/task_request_model.dart index 6bce945a..fd4dc795 100644 --- a/lib/models/new_models/task_request/task_request_model.dart +++ b/lib/models/new_models/task_request/task_request_model.dart @@ -284,7 +284,7 @@ class TaskData { data['callComment'] = callComment; if (taskJobAttachments != null) { - data['taskJobAttachments'] = taskJobAttachments!.map((e) => e?.toJson() ?? {}).toList(); + data['taskJobAttachments'] = taskJobAttachments!.map((e) => e.toTaskJson()).toList(); } if (assignedEngineer != null) { @@ -369,7 +369,7 @@ class TaskData { data['taskJobActivityEngineerTimers'] = taskJobActivityEngineerTimers!.map((v) => v.toJson()).toList(); } if (taskJobAttachments != null) { - data['attachments'] = taskJobAttachments!.map((v) => v?.toJson() ?? {}).toList(); + data['attachments'] = taskJobAttachments!.map((v) => v.toTaskJson()).toList(); } data['installationBuildingId'] = building?.id; data['installationFloorId'] = floor?.id; @@ -781,7 +781,7 @@ class AddTaskModel { 'reasonOfFSCA': reasonOfFSCA, 'correctiveActionDescription': correctiveActionDescription, 'evaluatorUserId': taskEvaluatorUser?.userId, - 'attachments': attachments?.map((x) => x.toJson() ?? {}).toList(), + 'attachments': attachments?.map((x) => x.toTaskJson()).toList(), }; } diff --git a/lib/modules/asset_delivery_module/pages/attachment_view.dart b/lib/modules/asset_delivery_module/pages/attachment_view.dart index ebcba992..70f3a956 100644 --- a/lib/modules/asset_delivery_module/pages/attachment_view.dart +++ b/lib/modules/asset_delivery_module/pages/attachment_view.dart @@ -9,6 +9,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -19,6 +20,7 @@ import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/views/widgets/images/files_list.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; class AssetDeliveryAttachmentView extends StatefulWidget { @@ -86,6 +88,7 @@ class _AssetDeliveryAttachmentViewState extends State URLs.getFileUrl(e.name ?? '') ?? '',).toList() ?? []).toShadowContainer( - context, - borderRadius: 20, - padding: 12, - margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - ), + : Column( + children: [ + InfoHeader16Widget("Attachments".addTranslation), + FilesList( showAsListView: true, + types: _attachments.map((doc) { + final attachmentType = doc.documentType?.name ?? ''; + return attachmentType.isNotEmpty ? attachmentType : 'Asset Guide'; + }).toList(), + images: _attachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '',).toList() ?? []).toShadowContainer( + context, + borderRadius: 20, + padding: 12, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + ), + ], + ), ], ), ), diff --git a/lib/modules/asset_delivery_module/provider/attachment_type_provider.dart b/lib/modules/asset_delivery_module/provider/attachment_type_provider.dart index 7d916444..becc0696 100644 --- a/lib/modules/asset_delivery_module/provider/attachment_type_provider.dart +++ b/lib/modules/asset_delivery_module/provider/attachment_type_provider.dart @@ -1,9 +1,12 @@ import 'dart:convert'; +import 'dart:developer'; import 'package:http/http.dart'; import 'package:test_sa/controllers/api_routes/api_manager.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/providers/loading_list_notifier.dart'; + ///TODO need to remove this after verifying we need to use the same for all modules .. class AttachmentTypeLookupProvider extends LoadingListNotifier { @override @@ -38,10 +41,18 @@ class AttachmentTypeLookupProviderLatest extends LoadingListNotifier { if (loading == true) return -2; loading = true; notifyListeners(); + int? lookupEnum = RequestAttachmentTypeEnumExtension.getLookupEnumIdFromId(id); + if (lookupEnum == null) { + log('Invalid request type id: $id'); + loading = false; + stateCode = -1; + notifyListeners(); + return -1; + } try { - // OPTIMIZATION: Enable caching for demo document types lookup + log('Request type id: $id, Lookup enum: $lookupEnum'); Response response = await ApiManager.instance.get( - URLs.getAttachmentTypesLookup, + '${URLs.getAttachmentTypesLookup}?lookupEnum=$lookupEnum', useCache: true, enableToastMessage: false, ); diff --git a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart index 11785f86..2fe422b4 100644 --- a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart +++ b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/asset_inventory_module/models/asset_inventory_model.dart'; import 'package:test_sa/modules/asset_inventory_module/pages/search_asset_view.dart'; @@ -298,8 +299,9 @@ class _AssetInventoryFormViewState extends State { 'Attachments'.addTranslation, style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936), ), - 12.height, + AttachmentPicker( + moduleId: RequestAttachmentTypeEnum.assetInventory.id, label: context.translation.attachFiles, attachment: attachments, showAsListView: true, diff --git a/lib/modules/cm_module/create_cm_request.dart b/lib/modules/cm_module/create_cm_request.dart index 2ddf921c..bc54fae1 100644 --- a/lib/modules/cm_module/create_cm_request.dart +++ b/lib/modules/cm_module/create_cm_request.dart @@ -12,6 +12,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart'; @@ -157,6 +158,7 @@ class _CreateCMRequestState extends State with TickerProviderSt 24.height, AttachmentPicker( label: context.translation.attachImage, + moduleId: RequestAttachmentTypeEnum.correctiveMaintenance.id, showAsListView: true, attachment: _deviceImages, onlyImages: false, diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index a4126d32..b611c3a4 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -4,6 +4,7 @@ import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; +import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/user_types.dart'; @@ -173,6 +174,7 @@ class _ActivitiesListViewState extends State { if (activity.activitySparePart?.acitiySparePartAttachments?.isNotEmpty ?? false) ...[ 2.height, const Divider().defaultStyle(context), + InfoHeader16Widget("Attachments".addTranslation), FilesList( showAsListView: true, types: activity.activitySparePart!.acitiySparePartAttachments! diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index 008bbe4a..4a081b6e 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/enums/work_order_next_step.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; @@ -56,19 +57,14 @@ class _ServiceRequestDetailViewState extends State { return Consumer(builder: (pContext, requestProvider, _) { if (userProvider.user?.type == UsersTypes.engineer) { _userAttachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments - .whereType() - .where((e) => e.createdBy == userProvider.user?.userID) - .map((e) => GenericAttachmentModel(id: e.id, name: e.name, createdBy: e.createdBy, documentType: e.documentType)) - .toList() ?? []; - _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments - .whereType() - .where((e) => e.createdBy != userProvider.user?.userID) - .toList() ?? []; + .whereType() + .where((e) => e.createdBy == userProvider.user?.userID) + .map((e) => GenericAttachmentModel(id: e.id, name: e.name, createdBy: e.createdBy, documentType: e.documentType)) + .toList() ?? + []; + _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments.whereType().where((e) => e.createdBy != userProvider.user?.userID).toList() ?? []; } else { - _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments - .whereType() - .where((e) => e.createdBy == userProvider.user?.userID) - .toList() ?? []; + _attachments = requestProvider.currentWorkOrder?.data?.workOrderAttachments.whereType().where((e) => e.createdBy == userProvider.user?.userID).toList() ?? []; } bool showInitialVisitCard = requestProvider.currentWorkOrder?.data?.needAVisitDateTime != null && @@ -286,18 +282,32 @@ class _ServiceRequestDetailViewState extends State { label: context.translation.attachments, showAsListView: true, attachment: _userAttachments, + moduleId: RequestAttachmentTypeEnum.correctiveMaintenance.id, buttonColor: AppColor.primary10, onlyImages: false, buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), onChange: (attachment) { - requestProvider.addWorkOrderAttachment(woId: workOrder.requestId!, attachments: attachment, otherAttachment: _attachments,); + requestProvider.addWorkOrderAttachment( + woId: workOrder.requestId!, + attachments: attachment, + otherAttachment: _attachments, + ); }, ), ], ] else ...[ if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - FilesList(images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList(),showAsListView: true,), + InfoHeader16Widget("Attachments".addTranslation), + FilesList( + images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList(), + showAsListView: true, + types: _attachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + ), ], //handle nurse case.. ], diff --git a/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart b/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart index a6b3f5d7..41e4bc68 100644 --- a/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart +++ b/lib/modules/cm_module/views/forms/asset_retired/asset_retired.dart @@ -7,6 +7,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/asset_retired/asset_retired_model.dart'; import 'package:test_sa/models/lookup.dart'; @@ -106,6 +107,7 @@ class _AssetRetiredState extends State with TickerProviderStateMix AttachmentPicker( label: context.translation.attachFiles, attachment: _attachments, + moduleId: RequestAttachmentTypeEnum.assetDelivery.id, showAsListView: true, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 6c762356..cac36002 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; import 'package:test_sa/models/lookup.dart'; @@ -293,6 +294,7 @@ class _SparePartRequestState extends State with TickerProvider AttachmentPicker( label: context.translation.attachQuotation, showAsListView: true, + moduleId: RequestAttachmentTypeEnum.sparePartActivity.id, attachment: attachments, buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), // buttonColor: AppColor.primary10, diff --git a/lib/modules/demo_module/create_demo_request_page.dart b/lib/modules/demo_module/create_demo_request_page.dart index f7f13be8..5f7beccf 100644 --- a/lib/modules/demo_module/create_demo_request_page.dart +++ b/lib/modules/demo_module/create_demo_request_page.dart @@ -13,6 +13,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; @@ -516,9 +517,10 @@ class _CreateDemoRequestPageState extends State with Tick attachment: _attachments, buttonColor: AppColor.primary10.withOpacity(demoDocumentLookup != null ? 1 : .4), onlyImages: false, - enabled: demoDocumentLookup != null, - documentType: demoDocumentLookup, + // enabled: demoDocumentLookup != null, + // documentType: demoDocumentLookup, showAsListView: true, + moduleId: RequestAttachmentTypeEnum.demo.id, buttonIcon: 'image-plus'.toSvgAsset(color: (AppColor.primary10)), // onChange: (attachments) { // _attachments = attachments; diff --git a/lib/modules/demo_module/demo_activities_page.dart b/lib/modules/demo_module/demo_activities_page.dart index a7baf9ef..7fa31795 100644 --- a/lib/modules/demo_module/demo_activities_page.dart +++ b/lib/modules/demo_module/demo_activities_page.dart @@ -5,6 +5,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/views/widgets/images/files_list.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import '../../controllers/api_routes/urls.dart'; import '../../extensions/text_extensions.dart'; @@ -54,10 +55,7 @@ class DemoActivitiesPage extends StatelessWidget { 12.height, if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - Text( - "Attachments".addTranslation, - style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50), - ), + InfoHeader16Widget("Attachments".addTranslation), FilesList( showAsListView: true, types: allAttachments diff --git a/lib/modules/demo_module/update_demo-request_view.dart b/lib/modules/demo_module/update_demo-request_view.dart index 0e7c3913..0fd95ef1 100644 --- a/lib/modules/demo_module/update_demo-request_view.dart +++ b/lib/modules/demo_module/update_demo-request_view.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; @@ -225,8 +226,7 @@ class _UpdateDemoRequestViewState extends State with Tick attachment: attachments, buttonColor: AppColor.black10.withOpacity(demoDocumentLookup != null ? 1 : .4), onlyImages: false, - // documentType: demoDocumentLookup, - // enabled: demoDocumentLookup != null, + moduleId: RequestAttachmentTypeEnum.demo.id, showAsListView: true, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), ), diff --git a/lib/modules/incident_module/create_incident_request_page.dart b/lib/modules/incident_module/create_incident_request_page.dart index 562bedfb..425f931d 100644 --- a/lib/modules/incident_module/create_incident_request_page.dart +++ b/lib/modules/incident_module/create_incident_request_page.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; @@ -171,6 +172,7 @@ class _CreateIncidentRequestPageState extends State { label: context.translation.attachments, attachment: attachments, buttonColor: AppColor.black10, + moduleId: RequestAttachmentTypeEnum.incidents.id, onlyImages: false, showAsListView: true, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart index 7d75c9ef..c501205e 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/create_equipment_internal_audit_form.dart @@ -8,6 +8,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -120,6 +121,7 @@ class _CreateEquipmentInternalAuditFormState extends State with Tick AttachmentPicker( label: context.translation.attachments, attachment: attachments, + moduleId: RequestAttachmentTypeEnum.loanEquipment.id, onlyImages: false, showAsListView: true, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/loan_module/pages/installation_form_view.dart b/lib/modules/loan_module/pages/installation_form_view.dart index fa54d82d..08e81686 100644 --- a/lib/modules/loan_module/pages/installation_form_view.dart +++ b/lib/modules/loan_module/pages/installation_form_view.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/timer_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -166,6 +167,7 @@ class _InstallationFormViewState extends State { attachment: _attachments, buttonColor: AppColor.primary10, onlyImages: false, + moduleId: RequestAttachmentTypeEnum.loanEquipment.id, showAsListView: true, buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10), onChange: (attachments) { diff --git a/lib/modules/loan_module/pages/installation_pullout_form_view.dart b/lib/modules/loan_module/pages/installation_pullout_form_view.dart index 2bb85358..7dc09df8 100644 --- a/lib/modules/loan_module/pages/installation_pullout_form_view.dart +++ b/lib/modules/loan_module/pages/installation_pullout_form_view.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/timer_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -169,6 +170,7 @@ class _InstallationPullOutFormViewState extends State { attachment: _attachments, showAsListView: true, buttonColor: AppColor.primary10, + moduleId: RequestAttachmentTypeEnum.updateDeliveryNotes.id, onlyImages: false, buttonIcon: 'attachment_icon'.toSvgAsset(color: AppColor.primary10), ), diff --git a/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart b/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart index ef50b0df..93b29587 100644 --- a/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart +++ b/lib/modules/medical_gas_inspection/update_medical_gas_inspection_page.dart @@ -8,6 +8,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; @@ -202,6 +203,7 @@ class _UpdateMedicalGasInspectionPageState extends State { label: context.translation.attachments, showAsListView: true, attachment: ppmProvider.ppmPlanAttachments, + moduleId: RequestAttachmentTypeEnum.preventiveMaintenance.id, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart index 8304293f..24494964 100644 --- a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart +++ b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart @@ -13,6 +13,7 @@ import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/device/asset.dart'; import 'package:test_sa/models/device/asset_transfer_attachment.dart'; import 'package:test_sa/models/device/device_transfer.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/new_models/department.dart'; @@ -247,6 +248,7 @@ class _CreateDeviceTransferRequestState extends State { AttachmentPicker( label: context.translation.attachFiles, showAsListView: true, + moduleId: RequestAttachmentTypeEnum.transferAsset.id, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, diff --git a/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart b/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart index cb030a1d..87f788c2 100644 --- a/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart +++ b/lib/modules/tm_module/gas_refill/gas_refill_request_form.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; @@ -218,6 +219,7 @@ class _GasRefillRequestFormState extends State { label: context.translation.attachFiles, showAsListView: true, attachment: attachments, + moduleId: RequestAttachmentTypeEnum.gasRefill.id, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart b/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart index 35593f56..368a1f71 100644 --- a/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart +++ b/lib/modules/tm_module/gas_refill/update_gas_refill_request.dart @@ -11,6 +11,7 @@ import 'package:test_sa/controllers/providers/api/user_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/timer_model.dart'; @@ -292,6 +293,7 @@ class _UpdateGasRefillRequestState extends State { AttachmentPicker( label: context.translation.attachFiles, attachment: _attachments, + moduleId: RequestAttachmentTypeEnum.gasRefill.id, showAsListView: true, buttonColor: AppColor.black10, onlyImages: false, diff --git a/lib/modules/tm_module/tasks/create_task_view.dart b/lib/modules/tm_module/tasks/create_task_view.dart index 931c5e68..d3a06e45 100644 --- a/lib/modules/tm_module/tasks/create_task_view.dart +++ b/lib/modules/tm_module/tasks/create_task_view.dart @@ -5,10 +5,12 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/dashboard_latest/dashboard_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; +import 'package:test_sa/extensions/enum_extensions.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/enums/user_types.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; @@ -58,7 +60,9 @@ class _CreateTaskViewState extends State with TickerProviderStat void initState() { // TODO: implement initState super.initState(); - Provider.of(context, listen: false).reset(); + // WidgetsBinding.instance.addPostFrameCallback((_) { + Provider.of(context, listen: false).reset(); + // }); } @override @@ -116,6 +120,7 @@ class _CreateTaskViewState extends State with TickerProviderStat AttachmentPicker( label: context.translation.attachImage, attachment: attachments, + moduleId: RequestAttachmentTypeEnum.taskRequest.id, buttonColor: AppColor.black10, showAsListView: true, onlyImages: false, diff --git a/lib/modules/tm_module/tasks/update_task_request_view.dart b/lib/modules/tm_module/tasks/update_task_request_view.dart index d0c102e9..a47506a5 100644 --- a/lib/modules/tm_module/tasks/update_task_request_view.dart +++ b/lib/modules/tm_module/tasks/update_task_request_view.dart @@ -15,6 +15,7 @@ import 'package:test_sa/extensions/string_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/building.dart'; @@ -193,6 +194,7 @@ class _UpdateTaskRequestState extends State { label: context.translation.attachFiles, showAsListView: true, attachment: attachments, + moduleId: RequestAttachmentTypeEnum.taskRequest.id, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/traf_module/create_traf_request_page.dart b/lib/modules/traf_module/create_traf_request_page.dart index 78c98e5f..11b124c1 100644 --- a/lib/modules/traf_module/create_traf_request_page.dart +++ b/lib/modules/traf_module/create_traf_request_page.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/asset.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/models/new_models/traf_customer.dart'; @@ -518,6 +519,7 @@ class _CreateTRAFRequestPageState extends State { label: context.translation.attachFiles, showAsListView: true, attachment: attachments, + moduleId: RequestAttachmentTypeEnum.traf.id, buttonColor: AppColor.black10, onlyImages: false, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), diff --git a/lib/modules/traf_module/traf_request_detail_page.dart b/lib/modules/traf_module/traf_request_detail_page.dart index 16796bdb..783ff707 100644 --- a/lib/modules/traf_module/traf_request_detail_page.dart +++ b/lib/modules/traf_module/traf_request_detail_page.dart @@ -149,12 +149,7 @@ class _TrafRequestDetailPageState extends State { ], if (_attachments.isNotEmpty) ...[ 4.height, - Text( - // todo @waseem conver to header - "Attachments".addTranslation, - style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50), - ), - // 8.height, + InfoHeader16Widget("Attachments".addTranslation), FilesList( showAsListView: true, types: _attachments diff --git a/lib/modules/traf_module/update_traf_request_page.dart b/lib/modules/traf_module/update_traf_request_page.dart index e9b042d8..f41cc71c 100644 --- a/lib/modules/traf_module/update_traf_request_page.dart +++ b/lib/modules/traf_module/update_traf_request_page.dart @@ -7,6 +7,7 @@ import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; @@ -213,6 +214,7 @@ class _UpdateTrafRequestPageState extends State { AttachmentPicker( label: context.translation.attachFiles, showAsListView: true, + moduleId: RequestAttachmentTypeEnum.traf.id, attachment: attachments, buttonColor: AppColor.black10, onlyImages: false, diff --git a/lib/providers/task_request_provider/task_job_provider.dart b/lib/providers/task_request_provider/task_job_provider.dart index 8b9b74fc..e605b7fe 100644 --- a/lib/providers/task_request_provider/task_job_provider.dart +++ b/lib/providers/task_request_provider/task_job_provider.dart @@ -12,7 +12,6 @@ import '../../controllers/api_routes/urls.dart'; class TaskTypeProvider extends LoadingListNotifier { @override Future getData({int? id}) async { - print('get data called...'); if (loading == true) return -2; loading = true; notifyListeners(); @@ -23,7 +22,6 @@ class TaskTypeProvider extends LoadingListNotifier { // client's request was successfully received List categoriesListJson = json.decode(response.body)["data"]; items = categoriesListJson.map((item) => TaskType.fromJson(item)).toList(); - print('item lenght i got is ${items.length}'); } loading = false; diff --git a/lib/views/widgets/equipment/asset_details_view.dart b/lib/views/widgets/equipment/asset_details_view.dart index a00ac9d9..5ccf24c3 100644 --- a/lib/views/widgets/equipment/asset_details_view.dart +++ b/lib/views/widgets/equipment/asset_details_view.dart @@ -317,6 +317,7 @@ class _AssetDetailsViewState extends State with SingleTickerPr opacity: attachmentAnimation, child: const Divider().defaultStyle(context), ), + InfoHeader16Widget("Attachments".addTranslation), FadeTransition( opacity: attachmentAnimation, child: SlideTransition( diff --git a/lib/views/widgets/equipment/asset_image_upload_page.dart b/lib/views/widgets/equipment/asset_image_upload_page.dart index 8c2eaddf..43094baa 100644 --- a/lib/views/widgets/equipment/asset_image_upload_page.dart +++ b/lib/views/widgets/equipment/asset_image_upload_page.dart @@ -10,6 +10,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/device/asset_by_id_model.dart'; +import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; @@ -109,12 +110,12 @@ class _AssetImageUploadPageState extends State { AttachmentPicker( label: "Additional Images", pickerTitle: "Attach Images", + moduleId: RequestAttachmentTypeEnum.transferAsset.id, attachment: trainingImageData.additionalImages!, buttonColor: AppColor.black10, onlyImages: true, showAsListView: true, pickMultiple: true, - // showAsGrid: true, buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10), onChange: (_attachments) { trainingImageData.additionalImages = _attachments; @@ -165,6 +166,7 @@ class _AssetImageUploadPageState extends State { child: AttachmentPicker( label: "", pickerTitle: title, + moduleId: RequestAttachmentTypeEnum.transferAsset.id, showAsListView:true, onlyImages: true, checkQuality: true, diff --git a/lib/views/widgets/images/multi_image_picker.dart b/lib/views/widgets/images/multi_image_picker.dart index f6bffcbf..210dc816 100644 --- a/lib/views/widgets/images/multi_image_picker.dart +++ b/lib/views/widgets/images/multi_image_picker.dart @@ -1,8 +1,10 @@ +import 'dart:developer'; import 'dart:io'; import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; import 'package:image_blur_detection/image_blur_detection.dart'; import 'package:image_picker/image_picker.dart'; +import 'package:provider/provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; @@ -43,8 +45,8 @@ class AttachmentPicker extends StatefulWidget { final String pickerTitle; final String label; final bool error; + final int moduleId; final List attachment; - final bool enabled, onlyImages; double? buttonHeight; Widget? buttonIcon; @@ -63,7 +65,8 @@ class AttachmentPicker extends StatefulWidget { this.pickerTitle = "Attach File", this.error = false, this.buttonHeight, - required this.showAsListView, + required this.moduleId, + required this.showAsListView, this.buttonIcon, this.enabled = true, this.onlyImages = false, @@ -83,6 +86,7 @@ class AttachmentPicker extends StatefulWidget { class _AttachmentPickerState extends State with SingleTickerProviderStateMixin { late AnimationController _animationController; Lookup? documentLookup; + late AttachmentTypeLookupProviderLatest attachmentTypeLookupProvider; @override void initState() { @@ -92,6 +96,10 @@ class _AttachmentPickerState extends State with SingleTickerPr vsync: this, ); _animationController.forward(); + WidgetsBinding.instance.addPostFrameCallback((_) { + Provider.of(context, listen: false).reset(); + log('i am going to reset the value'); + }); } @override @@ -283,7 +291,8 @@ class _AttachmentPickerState extends State with SingleTickerPr mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - Align(alignment: AlignmentDirectional.center, + Align( + alignment: AlignmentDirectional.center, child: Container( width: 40.toScreenWidth, height: 5.toScreenHeight, @@ -291,11 +300,12 @@ class _AttachmentPickerState extends State with SingleTickerPr ), ), 8.height, - InfoHeader16Widget(widget.pickerTitle), + InfoHeader16Widget(widget.pickerTitle), 8.height, SingleItemDropDownMenu( context: context, height: 56.toScreenHeight, + requestById: widget.moduleId, title: "Document Type", initialValue: documentLookup, showShadow: false, From dd644732c906c32690bd2b95736cb8af13d59d0e Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 26 Aug 2026 10:46:51 +0300 Subject: [PATCH 18/47] bug fixes --- lib/models/generic_attachment_model.dart | 33 +++++++-------- .../pages/attachment_view.dart | 5 +-- .../models/asset_inventory_model.dart | 4 +- .../models/session_model.dart | 2 - .../pages/asset_inventory_form_view.dart | 14 ++++--- .../pages/create_loan_request_page.dart | 2 +- .../ppm_wo/update_ppm/wo_info_form.dart | 6 +++ .../widgets/images/multi_image_picker.dart | 42 +++++++++++-------- 8 files changed, 58 insertions(+), 50 deletions(-) diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 684c3c61..41749f68 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -117,7 +117,7 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName']; moduleReferenceId = json['gasRefillId']; - documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; } GenericAttachmentModel.fromIncidentJson(Map json) { @@ -199,8 +199,8 @@ class GenericAttachmentModel { data['id'] = id; data['attachmentName'] = name; data['loanId'] = moduleReferenceId; - data['loanAttachmentTypeId'] = attachmentTypeId; - data['documentTypeId'] = documentType?.id; + data['loanAttachmentTypeId'] = documentType?.id; + // data['documentTypeId'] = documentType?.id; data['attachmentDescription'] = attachmentDescription; return data; } @@ -221,16 +221,6 @@ class GenericAttachmentModel { return data; } -//TODO need to check where to use this need to verify with backend team. - Map toPpmJson() { - final Map data = {}; - data['id'] = id; - data['visitId'] = moduleReferenceId; - data['attachmentName'] = name; - data['documentTypeId'] = documentType?.id; - data['attachmentURL'] = attachmentURL; - return data; - } Map toGasRefillJson() { final Map data = {}; @@ -246,7 +236,7 @@ class GenericAttachmentModel { data['id'] = id; data['attachmentName'] = name; data['incidentId'] = moduleReferenceId; - data['documentTypeId'] = documentType?.id; + data['attachmentTypeId'] = documentType?.id; data['attachmentDescription'] = attachmentDescription; return data; } @@ -255,7 +245,7 @@ class GenericAttachmentModel { final Map data = {}; data['id'] = id; data['attachmentName'] = name; - data['documentTypeId'] = documentType?.id; + data['attachmentTypeId'] = documentType?.id; return data; } @@ -276,7 +266,7 @@ class GenericAttachmentModel { data['id'] = id; data['name'] = name; data['originalName'] = originalName; - data['documentTypeId'] = documentType?.id; + data['attachmentTypeId'] = documentType?.id; return data; } @@ -284,7 +274,7 @@ class GenericAttachmentModel { final Map data = {}; data['id'] = id; data['attachmentName'] = name; - data['documentTypeId'] = documentType?.id; + data['attachmentTypeId'] = documentType?.id; return data; } @@ -297,6 +287,15 @@ class GenericAttachmentModel { data['originalName'] = originalName; return data; } + Map toInventoryJson() { + final Map data = {}; + data['id'] = id; + data['attachmentName'] = name; + data['attachmentURL'] = attachmentURL; + data['attachmentTypeId'] = documentType?.id; + data['originalName'] = originalName; + return data; + } Map toTrafJson() { final Map data = {}; diff --git a/lib/modules/asset_delivery_module/pages/attachment_view.dart b/lib/modules/asset_delivery_module/pages/attachment_view.dart index 70f3a956..6d699a62 100644 --- a/lib/modules/asset_delivery_module/pages/attachment_view.dart +++ b/lib/modules/asset_delivery_module/pages/attachment_view.dart @@ -76,9 +76,7 @@ class _AssetDeliveryAttachmentViewState extends State v?.toAssetJson() ?? {}).toList() - : [], + 'assetInventoryDetailAssetAttachments': assetInventoryDetailAssetAttachments.map((v) => v.toInventoryJson() ?? {}).toList(), }; } diff --git a/lib/modules/asset_inventory_module/models/session_model.dart b/lib/modules/asset_inventory_module/models/session_model.dart index 8de8503b..ba18ab36 100644 --- a/lib/modules/asset_inventory_module/models/session_model.dart +++ b/lib/modules/asset_inventory_module/models/session_model.dart @@ -43,11 +43,9 @@ class SessionModel { statusName = json['statusName']; startDate = json['startDate']; endDate = json['endDate']; - if (json['assetInventorySites'] != null) { assetInventorySites = (json['assetInventorySites'] as List).map((e) => Site.fromJson(e)).toList(); } - if (json['assetInventoryAssignedEmployee'] != null) { assetInventoryAssignedEmployee = (json['assetInventoryAssignedEmployee'] as List).map((e) => AssetInventoryAssignedEmployee.fromJson(e)).toList(); } diff --git a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart index 2fe422b4..48f5fcb0 100644 --- a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart +++ b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart @@ -24,6 +24,7 @@ import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/views/widgets/equipment/asset_picker.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker_item.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/requests/request_status.dart'; import '../../../new_views/common_widgets/app_filled_button.dart'; import '../../../new_views/common_widgets/default_app_bar.dart'; @@ -295,11 +296,12 @@ class _AssetInventoryFormViewState extends State { classificationWidget(label: _scannedAssetModel?.status), ], 12.height, - Text( - 'Attachments'.addTranslation, - style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936), - ), - + InfoHeader16Widget('Attachments'.addTranslation), + // Text( + // 'Attachments'.addTranslation, + // style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936), + // ), + 8.height, AttachmentPicker( moduleId: RequestAttachmentTypeEnum.assetInventory.id, label: context.translation.attachFiles, @@ -409,7 +411,7 @@ class _AssetInventoryFormViewState extends State { // try { for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _scannedAssetModel?.assetInventoryDetailAssetAttachments.add(GenericAttachmentModel(id: item.id, name: fileName,documentType: item.documentType)); + _scannedAssetModel?.assetInventoryDetailAssetAttachments.add(GenericAttachmentModel(id: item.id, name: fileName, documentType: item.documentType)); } // // } catch (error) { // // print(error); diff --git a/lib/modules/loan_module/pages/create_loan_request_page.dart b/lib/modules/loan_module/pages/create_loan_request_page.dart index 2b40032b..6e03259f 100644 --- a/lib/modules/loan_module/pages/create_loan_request_page.dart +++ b/lib/modules/loan_module/pages/create_loan_request_page.dart @@ -629,7 +629,7 @@ class _CreateLoanRequestPageState extends State with Tick _loanFormModel.loanAttachment = []; for (var item in attachments) { String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? ''; - _loanFormModel.loanAttachment?.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: 0)); + _loanFormModel.loanAttachment?.add(GenericAttachmentModel(id: 0, name: fileName, moduleReferenceId: 0,documentType: item.documentType)); } Utils.showLoading(context); LoanProvider loanProvider = Provider.of(context, listen: false); diff --git a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart index 122f13ca..e5d8ec05 100644 --- a/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart +++ b/lib/modules/pm_module/ppm_wo/update_ppm/wo_info_form.dart @@ -1,3 +1,4 @@ +import 'dart:developer'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -99,10 +100,15 @@ class _WoInfoFormState extends State { @override Widget build(BuildContext context) { + + // double totalWorkingHours = // widget.planPreventiveVisit.preventiveVisitTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDateTime!).difference(DateTime.parse(item.startDateTime!)).inSeconds) ?? 0; return Consumer(builder: (context, ppmProvider, child) { + ppmProvider.ppmPlanAttachments.forEach((e){ + log('attachemnt type ${e.documentType}'); + }); return ListView( padding: const EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 16), children: [ diff --git a/lib/views/widgets/images/multi_image_picker.dart b/lib/views/widgets/images/multi_image_picker.dart index 210dc816..2099b165 100644 --- a/lib/views/widgets/images/multi_image_picker.dart +++ b/lib/views/widgets/images/multi_image_picker.dart @@ -45,6 +45,7 @@ class AttachmentPicker extends StatefulWidget { final String pickerTitle; final String label; final bool error; + final bool showTypeDropdown; final int moduleId; final List attachment; final bool enabled, onlyImages; @@ -75,6 +76,7 @@ class AttachmentPicker extends StatefulWidget { // this.showAsListView = false, this.pickMultiple = false, this.checkQuality = false, + this.showTypeDropdown = true, this.child, this.buttonColor}) : super(key: key); @@ -227,7 +229,8 @@ class _AttachmentPickerState extends State with SingleTickerPr return StatefulBuilder( builder: (BuildContext context, StateSetter setModalState) { Widget listCard({required String icon, required String label, required VoidCallback onTap}) { - bool isEnabled = documentLookup != null; + + bool isEnabled = !widget.showTypeDropdown?true:documentLookup != null; return Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( @@ -302,24 +305,27 @@ class _AttachmentPickerState extends State with SingleTickerPr 8.height, InfoHeader16Widget(widget.pickerTitle), 8.height, - SingleItemDropDownMenu( - context: context, - height: 56.toScreenHeight, - requestById: widget.moduleId, - title: "Document Type", - initialValue: documentLookup, - showShadow: false, - backgroundColor: AppColor.fieldBgColor(context), - showAsBottomSheet: true, - onSelect: (value) { - documentLookup = value; - setModalState(() {}); - }, - ), - if (documentLookup == null) ...[ - 4.height, - const InfoTextLabelWidget(label: 'Please Select Document Type before picking file', color: AppColor.red30), + if(widget.showTypeDropdown)...[ + SingleItemDropDownMenu( + context: context, + height: 56.toScreenHeight, + requestById: widget.moduleId, + title: "Document Type", + initialValue: documentLookup, + showShadow: false, + backgroundColor: AppColor.fieldBgColor(context), + showAsBottomSheet: true, + onSelect: (value) { + documentLookup = value; + setModalState(() {}); + }, + ), + if (documentLookup == null) ...[ + 4.height, + const InfoTextLabelWidget(label: 'Please Select Document Type before picking file', color: AppColor.red30), + ], ], + GridView.builder( padding: const EdgeInsets.only(top: 16, bottom: 0), shrinkWrap: true, From 448a85522a85a211d43734684b95cff862d52f8d Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Thu, 27 Aug 2026 12:10:52 +0300 Subject: [PATCH 19/47] bug fixes --- lib/main.dart | 4 + lib/models/generic_attachment_model.dart | 22 +++- .../helper_function.dart | 1 + .../pages/attachment_view.dart | 116 +++++++++--------- .../models/asset_inventory_model.dart | 2 +- .../pages/asset_detail_card_view.dart | 1 + .../pages/asset_inventory_form_view.dart | 7 +- .../demo_module/demo_request_item_view.dart | 2 +- .../update_equipment_internal_audit_page.dart | 1 + .../system_internal_audit_detail_page.dart | 11 +- .../traf_module/traf_request_detail_page.dart | 16 +-- .../create_request_type_bottom_sheet.dart | 1 + lib/views/widgets/images/files_list.dart | 1 + .../widgets/images/multi_image_picker.dart | 17 +-- 14 files changed, 116 insertions(+), 86 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index d65c1255..615b98ba 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -68,6 +68,7 @@ import 'package:test_sa/modules/applicationDemo/providers/application_demo_reque import 'package:test_sa/modules/applicationDemo/screens/application_demo_request_form_screen.dart'; import 'package:test_sa/modules/tm_module/gas_refill/create_gas_refill_request.dart'; import 'package:test_sa/modules/tm_module/gas_refill/update_gas_refill_request.dart'; +import 'package:test_sa/modules/traf_module/create_traf_request_page.dart'; import 'package:test_sa/new_views/app_style/app_themes.dart'; import 'package:test_sa/new_views/pages/help_center_page.dart'; import 'package:test_sa/new_views/pages/land_page/land_page.dart'; @@ -145,6 +146,7 @@ import 'modules/tm_module/device_transfer/device_filter_screen.dart'; import 'modules/tm_module/device_transfer/device_search_screen.dart'; import 'modules/tm_module/tasks/create_task_view.dart'; import 'modules/tm_module/gas_refill/gas_refill_request_form.dart'; +import 'modules/traf_module/traf_request_provider.dart'; import 'providers/lookups/classification_lookup_provider.dart'; import 'providers/lookups/customer_lookup_provider.dart'; import 'providers/lookups/department_lookup_provider.dart'; @@ -387,6 +389,7 @@ class MyApp extends StatelessWidget { // UTILITY PROVIDERS (1) ChangeNotifierProvider(create: (_) => OracleCodeProvider(), lazy: true), + ChangeNotifierProvider(create: (_) => TrafRequestProvider(), lazy: true), ], child: GestureDetector( onTap: () { @@ -425,6 +428,7 @@ class MyApp extends StatelessWidget { DeviceSearchScreen.id: (_) => const DeviceSearchScreen(), DeviceFilterScreen.id: (_) => const DeviceFilterScreen(), CreateIncidentRequestPage.id: (_) => CreateIncidentRequestPage(), + CreateTRAFRequestPage.id: (_) => CreateTRAFRequestPage(), SettingsPage.id: (_) => const SettingsPage(), ProfilePage.id: (_) => const ProfilePage(), ReportBugPage.id: (_) => const ReportBugPage(), diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 41749f68..68f262b3 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -163,10 +163,19 @@ class GenericAttachmentModel { documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; originalName = json['originalName']; } + GenericAttachmentModel.fromAssetInventoryJson(Map json) { + id = json['id']; + name = json['attachmentName']; + attachmentURL = json['attachmentURL']; + documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + originalName = json['originalName']; + } GenericAttachmentModel.fromTrafJson(Map json) { id = json['id']; + moduleReferenceId= json['trafId']; name = json['attachmentName']; + attachmentDescription = json['attachmentDescription']; moduleReferenceId = json['trafId']; documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; } @@ -287,10 +296,19 @@ class GenericAttachmentModel { data['originalName'] = originalName; return data; } + Map toAssetDeliveryJson() { + final Map data = {}; + data['id'] = id; + data['name'] = name; + data['attachmentTypeId'] = documentType?.id; + data['originalName'] = originalName; + data['createdBy'] = createdBy; + return data; + } Map toInventoryJson() { final Map data = {}; data['id'] = id; - data['attachmentName'] = name; + data['Name'] = name; data['attachmentURL'] = attachmentURL; data['attachmentTypeId'] = documentType?.id; data['originalName'] = originalName; @@ -302,7 +320,7 @@ class GenericAttachmentModel { data['id'] = id; data['trafId'] = moduleReferenceId; data['attachmentName'] = name; - data['documentTypeId'] = documentType?.id; + data['attachmentTypeId'] = documentType?.id; return data; } diff --git a/lib/modules/asset_delivery_module/helper_function.dart b/lib/modules/asset_delivery_module/helper_function.dart index 747c34c6..0fc2e7ea 100644 --- a/lib/modules/asset_delivery_module/helper_function.dart +++ b/lib/modules/asset_delivery_module/helper_function.dart @@ -34,6 +34,7 @@ class HelperFunction { builder: (context) => AssetDeliveryAttachmentView( tableItemId: deliveryTableItemId, attachmentType: result!.value, + documentType: Lookup(id: result.id, value: result.value, name: result.name), viewOnly: viewOnly, attachmentList: list, ))); diff --git a/lib/modules/asset_delivery_module/pages/attachment_view.dart b/lib/modules/asset_delivery_module/pages/attachment_view.dart index 6d699a62..c42a97e8 100644 --- a/lib/modules/asset_delivery_module/pages/attachment_view.dart +++ b/lib/modules/asset_delivery_module/pages/attachment_view.dart @@ -11,6 +11,7 @@ import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/request_attachment_type_enum.dart'; import 'package:test_sa/models/generic_attachment_model.dart'; +import 'package:test_sa/models/lookup.dart'; import 'package:test_sa/modules/asset_delivery_module/provider/asset_delivery_provider.dart'; import 'package:test_sa/modules/cm_module/cm_request_utils.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; @@ -26,6 +27,7 @@ import 'package:test_sa/views/widgets/loaders/no_data_found.dart'; class AssetDeliveryAttachmentView extends StatefulWidget { final int? tableItemId; final int? attachmentType; + final Lookup? documentType; bool viewOnly = false; final List attachmentList; @@ -34,6 +36,7 @@ class AssetDeliveryAttachmentView extends StatefulWidget { required this.attachmentList, this.viewOnly = false, this.attachmentType, + this.documentType, this.tableItemId, }); @@ -76,73 +79,74 @@ class _AssetDeliveryAttachmentViewState extends State URLs.getFileUrl(e.name ?? '') ?? '',).toList() ?? []).toShadowContainer( - context, - borderRadius: 20, - padding: 12, - margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - ), - ], - ), - ], - ), - ), - if (widget.attachmentType == 5 && !widget.viewOnly) - FooterActionButton.footerContainer( - context: context, - child: AppFilledButton( - buttonColor: AppColor.primary10, - label: 'Save'.addTranslation, - maxWidth: true, - onPressed: _onSavePressed, - ), - ), + widget.attachmentType == 5 && !widget.viewOnly + ? AttachmentPicker( + label: context.translation.attachments, + showTypeDropdown: false, + attachment: _attachments, + moduleId: RequestAttachmentTypeEnum.assetDelivery.id, + buttonColor: AppColor.primary10, + documentType: widget.documentType, + onlyImages: false, + showAsListView: true, + buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), + onChange: (attachment) {}, + ).toShadowContainer( + context, + borderRadius: 20, + padding: 12, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + ) + : FilesList( + showAsListView: true, + types: _attachments.map((doc) { + final attachmentType = doc.documentType?.name ?? ''; + return attachmentType.isNotEmpty ? attachmentType : 'Asset Guide'; + }).toList(), + images: _attachments + .map( + (e) => URLs.getFileUrl(e.name ?? '') ?? '', + ) + .toList() ?? + []) + .toShadowContainer( + context, + borderRadius: 20, + padding: 12, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + ), ], ), + ), + if (widget.attachmentType == 5 && !widget.viewOnly) + FooterActionButton.footerContainer( + context: context, + child: AppFilledButton( + buttonColor: AppColor.primary10, + label: 'Save'.addTranslation, + maxWidth: true, + onPressed: _onSavePressed, + ), + ), + ], + ), ); } Future _onSavePressed() async { - final List attachmentPayload = _attachments.map((item) { + final List> attachmentPayload = _attachments.map((item) { final String name = CMRequestUtils.isLocalUrl(item.name ?? '') ? '${item.name?.split("/").last}|${base64Encode(File(item.name!).readAsBytesSync())}' : item.name ?? ''; - return GenericAttachmentModel( id: item.id ?? 0, name: name, - documentType: item.documentType, - - ); + documentType: widget.documentType, + ).toAssetDeliveryJson(); }).toList(); showDialog( diff --git a/lib/modules/asset_inventory_module/models/asset_inventory_model.dart b/lib/modules/asset_inventory_module/models/asset_inventory_model.dart index fd913df8..c63f477f 100644 --- a/lib/modules/asset_inventory_module/models/asset_inventory_model.dart +++ b/lib/modules/asset_inventory_module/models/asset_inventory_model.dart @@ -200,7 +200,7 @@ class AssetInventoryModel { if (json['assetInventoryDetailAssetAttachments'] != null) { assetInventoryDetailAssetAttachments = []; json['assetInventoryDetailAssetAttachments'].forEach((v) { - assetInventoryDetailAssetAttachments.add(GenericAttachmentModel.fromAssetJson(v)); + assetInventoryDetailAssetAttachments.add(GenericAttachmentModel.fromAssetInventoryJson(v)); }); } diff --git a/lib/modules/asset_inventory_module/pages/asset_detail_card_view.dart b/lib/modules/asset_inventory_module/pages/asset_detail_card_view.dart index 60a5c710..d90ec511 100644 --- a/lib/modules/asset_inventory_module/pages/asset_detail_card_view.dart +++ b/lib/modules/asset_inventory_module/pages/asset_detail_card_view.dart @@ -11,6 +11,7 @@ import 'package:test_sa/modules/asset_inventory_module/models/asset_inventory_mo import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/views/widgets/loaders/image_loader.dart'; +///TODO We are not showing attachment here we need to check this with backend team and flow . class AssetDetailCardView extends StatelessWidget { AssetInventoryModel assetInventoryModel; VoidCallback onDeletePress; diff --git a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart index 48f5fcb0..09277488 100644 --- a/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart +++ b/lib/modules/asset_inventory_module/pages/asset_inventory_form_view.dart @@ -296,12 +296,7 @@ class _AssetInventoryFormViewState extends State { classificationWidget(label: _scannedAssetModel?.status), ], 12.height, - InfoHeader16Widget('Attachments'.addTranslation), - // Text( - // 'Attachments'.addTranslation, - // style: AppTextStyles.bodyText.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.white936), - // ), - 8.height, + AttachmentPicker( moduleId: RequestAttachmentTypeEnum.assetInventory.id, label: context.translation.attachFiles, diff --git a/lib/modules/demo_module/demo_request_item_view.dart b/lib/modules/demo_module/demo_request_item_view.dart index 6abc6d58..5338dcac 100644 --- a/lib/modules/demo_module/demo_request_item_view.dart +++ b/lib/modules/demo_module/demo_request_item_view.dart @@ -54,7 +54,7 @@ class DemoRequestItemView extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ StatusLabel( - label: requestDetails!.status!, + label: requestDetails?.status??'', textColor: AppColor.demoRequestStatusTextColor(context, requestDetails?.statusValue ?? 0), backgroundColor: AppColor.demoRequestStatus(context, requestDetails?.statusValue ?? 0), ), diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart index 5e986081..cf60b860 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/update_equipment_internal_audit_page.dart @@ -26,6 +26,7 @@ import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart'; import 'package:test_sa/new_views/common_widgets/default_app_bar.dart'; import 'package:test_sa/new_views/common_widgets/working_time_tile.dart'; import 'package:test_sa/views/widgets/images/multi_image_picker.dart'; +import 'package:test_sa/views/widgets/item_views/info_header_widget.dart'; import 'package:test_sa/views/widgets/loaders/loading_manager.dart'; import 'package:test_sa/views/widgets/timer/app_timer.dart'; import 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.dart'; diff --git a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart index dda1f510..1f264369 100644 --- a/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/system_internal_audit/system_internal_audit_detail_page.dart @@ -86,19 +86,19 @@ class _SystemInternalAuditDetailPageState extends State { if (_attachments.isNotEmpty) ...[ 4.height, InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( - showAsListView: true, - types: _attachments - .whereType() - .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) - .map((toElement) => toElement.documentType!.name!) - .toList(), - images: _attachments.map((e) => URLs.getFileUrl(e.path ?? '') ?? '').toList() ?? []), + showAsListView: true, + types: data.attachments + ?.whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList() ?? + [], + images: _attachments.map((e) => URLs.getFileUrl(e.path ?? '') ?? '').toList()), ], ], ).toShadowContainer(context); diff --git a/lib/new_views/pages/land_page/create_request_type_bottom_sheet.dart b/lib/new_views/pages/land_page/create_request_type_bottom_sheet.dart index 04eaf070..dcad5347 100644 --- a/lib/new_views/pages/land_page/create_request_type_bottom_sheet.dart +++ b/lib/new_views/pages/land_page/create_request_type_bottom_sheet.dart @@ -106,6 +106,7 @@ class _CreateRequestTypeBottomSheetState extends State with SingleTickerPr vsync: this, ); _animationController.forward(); + // if (widget.documentType != null) { + // documentLookup = widget.documentType; + // } WidgetsBinding.instance.addPostFrameCallback((_) { Provider.of(context, listen: false).reset(); - log('i am going to reset the value'); }); } @@ -136,6 +138,7 @@ class _AttachmentPickerState extends State with SingleTickerPr file: image, showAsListView: widget.showAsListView, enabled: widget.enabled, + // documentType: widget.documentType != null ? widget.documentType?.name : widget.attachment[index].documentType?.name, documentType: widget.attachment[index].documentType?.name, onRemoveTap: (image) { if (!widget.enabled) { @@ -186,7 +189,7 @@ class _AttachmentPickerState extends State with SingleTickerPr ); if (result != null) { for (var path in result.paths) { - widget.attachment.add(GenericAttachmentModel(id: 0, name: File(path!).path, documentType: documentLookup)); + widget.attachment.add(GenericAttachmentModel(id: 0, name: File(path!).path, documentType: widget.documentType ?? documentLookup)); } if (widget.onChange != null) { widget.onChange!(widget.attachment); @@ -229,8 +232,7 @@ class _AttachmentPickerState extends State with SingleTickerPr return StatefulBuilder( builder: (BuildContext context, StateSetter setModalState) { Widget listCard({required String icon, required String label, required VoidCallback onTap}) { - - bool isEnabled = !widget.showTypeDropdown?true:documentLookup != null; + bool isEnabled = !widget.showTypeDropdown ? true : documentLookup != null; return Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( @@ -305,7 +307,7 @@ class _AttachmentPickerState extends State with SingleTickerPr 8.height, InfoHeader16Widget(widget.pickerTitle), 8.height, - if(widget.showTypeDropdown)...[ + if (widget.showTypeDropdown) ...[ SingleItemDropDownMenu( context: context, height: 56.toScreenHeight, @@ -325,7 +327,6 @@ class _AttachmentPickerState extends State with SingleTickerPr const InfoTextLabelWidget(label: 'Please Select Document Type before picking file', color: AppColor.red30), ], ], - GridView.builder( padding: const EdgeInsets.only(top: 16, bottom: 0), shrinkWrap: true, @@ -381,7 +382,7 @@ class _AttachmentPickerState extends State with SingleTickerPr pickedFiles.forEach((pickedFile) { File fileImage = File(pickedFile.path); - widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: documentLookup)); + widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: widget.documentType ?? documentLookup)); }); if (widget.onChange != null) { widget.onChange!(widget.attachment); @@ -408,7 +409,7 @@ class _AttachmentPickerState extends State with SingleTickerPr } } - widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: documentLookup)); + widget.attachment.add(GenericAttachmentModel(id: 0, name: fileImage.path, documentType: widget.documentType ?? documentLookup)); if (widget.onChange != null) { widget.onChange!(widget.attachment); } From 55f39fadbcd2f2b2c7366bbbef3310a145b28670 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Thu, 27 Aug 2026 14:27:09 +0300 Subject: [PATCH 20/47] improvements --- .../cleaner_module/pages/one_time_task_preview_screen.dart | 1 + .../cm_module/views/components/activities_list_view.dart | 1 + .../cm_module/views/components/service_request_detail_view.dart | 2 ++ lib/modules/demo_module/demo_activities_page.dart | 1 + lib/modules/demo_module/demo_detail_view_page.dart | 2 ++ lib/modules/incident_module/incident_detail_page.dart | 1 + .../equipment_internal_audit_detail_page.dart | 1 + lib/modules/loan_module/pages/intallation_details_view.dart | 2 +- lib/modules/loan_module/pages/loan_equipment_detail_page.dart | 1 + .../medical_gas_inspection_detail_page.dart | 1 + .../tm_module/device_transfer/device_transfer_details.dart | 1 + lib/modules/tm_module/gas_refill/gas_refill_details.dart | 1 + lib/modules/tm_module/tasks/task_request_detail_view.dart | 1 + lib/views/widgets/equipment/asset_details_view.dart | 1 + lib/views/widgets/images/files_list.dart | 2 +- 15 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/modules/cleaner_module/pages/one_time_task_preview_screen.dart b/lib/modules/cleaner_module/pages/one_time_task_preview_screen.dart index 19ef67fb..57433425 100644 --- a/lib/modules/cleaner_module/pages/one_time_task_preview_screen.dart +++ b/lib/modules/cleaner_module/pages/one_time_task_preview_screen.dart @@ -300,6 +300,7 @@ class OneTimeTaskPreviewScreen extends StatelessWidget { InfoHeader16Widget( 'Attachments', ), + 4.height, FilesList( images: taskData.attachments!.map((attachment) => URLs.getFileUrl(attachment.name ?? '') ?? '').toList(), showAsListView: true, diff --git a/lib/modules/cm_module/views/components/activities_list_view.dart b/lib/modules/cm_module/views/components/activities_list_view.dart index b611c3a4..1a4821c6 100644 --- a/lib/modules/cm_module/views/components/activities_list_view.dart +++ b/lib/modules/cm_module/views/components/activities_list_view.dart @@ -175,6 +175,7 @@ class _ActivitiesListViewState extends State { 2.height, const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: activity.activitySparePart!.acitiySparePartAttachments! diff --git a/lib/modules/cm_module/views/components/service_request_detail_view.dart b/lib/modules/cm_module/views/components/service_request_detail_view.dart index 4a081b6e..e6055eec 100644 --- a/lib/modules/cm_module/views/components/service_request_detail_view.dart +++ b/lib/modules/cm_module/views/components/service_request_detail_view.dart @@ -266,6 +266,7 @@ class _ServiceRequestDetailViewState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList(), @@ -299,6 +300,7 @@ class _ServiceRequestDetailViewState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( images: _attachments.map((toElement) => URLs.getFileUrl(toElement.name!)!).toList(), showAsListView: true, diff --git a/lib/modules/demo_module/demo_activities_page.dart b/lib/modules/demo_module/demo_activities_page.dart index 7fa31795..0288afc4 100644 --- a/lib/modules/demo_module/demo_activities_page.dart +++ b/lib/modules/demo_module/demo_activities_page.dart @@ -56,6 +56,7 @@ class DemoActivitiesPage extends StatelessWidget { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: allAttachments diff --git a/lib/modules/demo_module/demo_detail_view_page.dart b/lib/modules/demo_module/demo_detail_view_page.dart index 3278a6fb..5aa0939a 100644 --- a/lib/modules/demo_module/demo_detail_view_page.dart +++ b/lib/modules/demo_module/demo_detail_view_page.dart @@ -126,6 +126,7 @@ class _DemoDetailViewPageState extends State { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments"), + 4.height, FilesList( showAsListView: true, images: allAttachments.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(), @@ -134,6 +135,7 @@ class _DemoDetailViewPageState extends State { if (suppAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Supplier Attachments"), + 4.height, FilesList( showAsListView: true, images: suppAttachments.whereType().map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList(), diff --git a/lib/modules/incident_module/incident_detail_page.dart b/lib/modules/incident_module/incident_detail_page.dart index d54f4b4d..d22f72d7 100644 --- a/lib/modules/incident_module/incident_detail_page.dart +++ b/lib/modules/incident_module/incident_detail_page.dart @@ -71,6 +71,7 @@ class IncidentDetailPage extends StatelessWidget { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: allAttachments diff --git a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart index 7276a1fa..239a366a 100644 --- a/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart +++ b/lib/modules/internal_audit_module/pages/equipment_internal_audit/equipment_internal_audit_detail_page.dart @@ -127,6 +127,7 @@ class _EquipmentInternalAuditDetailPageState extends State URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ], ], diff --git a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart index 49800d56..b19b20ff 100644 --- a/lib/modules/loan_module/pages/loan_equipment_detail_page.dart +++ b/lib/modules/loan_module/pages/loan_equipment_detail_page.dart @@ -97,6 +97,7 @@ class _LoanEquipmentDetailPageState extends State { if (allAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: allAttachments diff --git a/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart b/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart index 29eb131f..3840418c 100644 --- a/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart +++ b/lib/modules/medical_gas_inspection/medical_gas_inspection_detail_page.dart @@ -104,6 +104,7 @@ class _MedicalGasInspectionDetailPageState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: _model?.assetTransferAttachments!=null? diff --git a/lib/modules/tm_module/gas_refill/gas_refill_details.dart b/lib/modules/tm_module/gas_refill/gas_refill_details.dart index cfd42605..77b5b70a 100644 --- a/lib/modules/tm_module/gas_refill/gas_refill_details.dart +++ b/lib/modules/tm_module/gas_refill/gas_refill_details.dart @@ -238,6 +238,7 @@ class _GasRefillDetailsPageState extends State { if (_attachments.isNotEmpty) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: _model.gasRefillAttachments?.whereType().where((e) => e.documentType != null && e.documentType!.name != null).map((toElement) => toElement.documentType!.name!).toList() ?? [], diff --git a/lib/modules/tm_module/tasks/task_request_detail_view.dart b/lib/modules/tm_module/tasks/task_request_detail_view.dart index 13ad69f8..b60740fb 100644 --- a/lib/modules/tm_module/tasks/task_request_detail_view.dart +++ b/lib/modules/tm_module/tasks/task_request_detail_view.dart @@ -160,6 +160,7 @@ class _TaskRequestDetailsViewState extends State { if (taskProvider.taskRequestModel?.taskJobAttachments?.isNotEmpty ?? false) ...[ const Divider().defaultStyle(context), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FilesList( showAsListView: true, types: taskProvider.taskRequestModel!.taskJobAttachments!.whereType().where((e) => e.name != null).map((toElement) => toElement.documentType?.name ?? '').toList(), diff --git a/lib/views/widgets/equipment/asset_details_view.dart b/lib/views/widgets/equipment/asset_details_view.dart index 5ccf24c3..5db28370 100644 --- a/lib/views/widgets/equipment/asset_details_view.dart +++ b/lib/views/widgets/equipment/asset_details_view.dart @@ -318,6 +318,7 @@ class _AssetDetailsViewState extends State with SingleTickerPr child: const Divider().defaultStyle(context), ), InfoHeader16Widget("Attachments".addTranslation), + 4.height, FadeTransition( opacity: attachmentAnimation, child: SlideTransition( diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 265b5e82..67d71ce6 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -115,7 +115,7 @@ class FilesList extends StatelessWidget { icon: "download".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)), padding: EdgeInsets.zero, visualDensity: VisualDensity.compact, - tooltip: "Download", + // tooltip: "Download", onPressed: () async { try { if (!await launchUrl(Uri.parse(images[itemIndex]), mode: LaunchMode.externalApplication)) { From 9f76874217ea684fd6e74faeb090b0cb97c5aaea Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Sun, 30 Aug 2026 10:58:17 +0300 Subject: [PATCH 21/47] improvements --- lib/controllers/providers/api/devices_provider.dart | 4 +++- lib/models/generic_attachment_model.dart | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/controllers/providers/api/devices_provider.dart b/lib/controllers/providers/api/devices_provider.dart index c8b5b9c7..d8c9ec51 100644 --- a/lib/controllers/providers/api/devices_provider.dart +++ b/lib/controllers/providers/api/devices_provider.dart @@ -269,7 +269,9 @@ class AssetProvider extends ChangeNotifier { var body = { "pageSize": documentPageItemNumber, "pageNumber": pageNumber, - "assetIds": [assetId] + "assetIds": [assetId], + 'ModuleIds': [1],///backend team ask to add this static values + 'SubModuleIds': [3],///backend team ask to add this static values }; response = await ApiManager.instance.post(URLs.assetDocumentHistory, body: body); stateCode = response.statusCode; diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 68f262b3..a3854344 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -160,7 +160,7 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName']; attachmentURL = json['attachmentURL']; - documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; originalName = json['originalName']; } GenericAttachmentModel.fromAssetInventoryJson(Map json) { From 2304700fb833d83e362e14c4027c60391b60189c Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Sun, 30 Aug 2026 11:47:36 +0300 Subject: [PATCH 22/47] final fixes --- lib/controllers/providers/api/devices_provider.dart | 3 +-- lib/models/generic_attachment_model.dart | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/controllers/providers/api/devices_provider.dart b/lib/controllers/providers/api/devices_provider.dart index d8c9ec51..a8369891 100644 --- a/lib/controllers/providers/api/devices_provider.dart +++ b/lib/controllers/providers/api/devices_provider.dart @@ -270,8 +270,7 @@ class AssetProvider extends ChangeNotifier { "pageSize": documentPageItemNumber, "pageNumber": pageNumber, "assetIds": [assetId], - 'ModuleIds': [1],///backend team ask to add this static values - 'SubModuleIds': [3],///backend team ask to add this static values + }; response = await ApiManager.instance.post(URLs.assetDocumentHistory, body: body); stateCode = response.statusCode; diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index a3854344..0821953f 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -138,7 +138,7 @@ class GenericAttachmentModel { id = json['id']; name = json['attachmentName']; originalName = json['originalName']; - documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; moduleReferenceId = json['demoRequestId']; } From f3722e3671dd54f3b54e9d13c81eb60b63e944de Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Sun, 30 Aug 2026 12:57:47 +0300 Subject: [PATCH 23/47] improvements --- .../widgets/equipment/asset_details_view.dart | 21 ++++++++++++------- .../asset_document_history_view.dart | 11 +++++----- lib/views/widgets/images/files_list.dart | 2 +- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/lib/views/widgets/equipment/asset_details_view.dart b/lib/views/widgets/equipment/asset_details_view.dart index 5db28370..81ab2866 100644 --- a/lib/views/widgets/equipment/asset_details_view.dart +++ b/lib/views/widgets/equipment/asset_details_view.dart @@ -317,19 +317,25 @@ class _AssetDetailsViewState extends State with SingleTickerPr opacity: attachmentAnimation, child: const Divider().defaultStyle(context), ), - InfoHeader16Widget("Attachments".addTranslation), + FadeTransition( + opacity: attachmentAnimation, + child: SlideTransition( + position: attachmentSlideAnimation, + child: InfoHeader16Widget("Attachments".addTranslation), + ), + ), 4.height, FadeTransition( opacity: attachmentAnimation, child: SlideTransition( position: attachmentSlideAnimation, child: FilesList( - showAsListView: true, - types: attachments - .whereType() - .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) - .map((toElement) => toElement.documentType!.name!) - .toList(), + showAsListView: true, + types: attachments + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), images: attachments.map((toElement) => URLs.getFileUrl(toElement.name!) ?? '').toList()), ), ), @@ -351,5 +357,4 @@ class _AssetDetailsViewState extends State with SingleTickerPr ], ); } - } diff --git a/lib/views/widgets/equipment/asset_document_history_view.dart b/lib/views/widgets/equipment/asset_document_history_view.dart index 701824a2..12acaa90 100644 --- a/lib/views/widgets/equipment/asset_document_history_view.dart +++ b/lib/views/widgets/equipment/asset_document_history_view.dart @@ -115,24 +115,25 @@ class _AssetDocumentHistoryViewState extends State { onRefresh: _onRefresh, child: ListView( controller: _scrollController, - padding: EdgeInsets.symmetric( - horizontal: 16.toScreenWidth, - ), + padding: const EdgeInsets.only(right: 16, left: 16, bottom: 16), children: [ FilesList( showAsListView: true, showDownloadButton: true, itemGap: 12.toScreenHeight, + separator: const Divider().defaultStyle(context), images: _documents .map((doc) { return URLs.getFileUrl(doc.name) ?? ''; - }).where((url) => url.isNotEmpty).toList(), + }) + .where((url) => url.isNotEmpty) + .toList(), types: _documents.map((doc) { final attachmentType = doc.documentType?.name ?? ''; return attachmentType.isNotEmpty ? attachmentType : 'Asset Guide'; }).toList(), ).toShadowContainer(context), - if (_isLoading && _documents.isNotEmpty&&_hasMore) ...[ + if (_isLoading && _documents.isNotEmpty && _hasMore) ...[ 16.height, Center( child: Padding( diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 67d71ce6..0590c60e 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -82,7 +82,7 @@ class FilesList extends StatelessWidget { RichText( text: TextSpan( text: '${types.isEmpty ? "Asset Guide" : types[itemIndex]} | ', - style: AppTextStyles.tinyFont.copyWith(color: AppColor.labelTextStyleColor(context)), + style: AppTextStyles.tinyFont.copyWith(color: AppColor.lightTextColor(context)), children: [ TextSpan( text: 'View', From a01f40e20d352d2d438ba78caa5929737609b2ae Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Sun, 30 Aug 2026 13:06:46 +0300 Subject: [PATCH 24/47] code merged from main production. --- lib/main.dart | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index fbe0cb2a..544e12c5 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -149,8 +149,6 @@ import 'modules/tm_module/device_transfer/device_filter_screen.dart'; import 'modules/tm_module/device_transfer/device_search_screen.dart'; import 'modules/tm_module/tasks/create_task_view.dart'; import 'modules/tm_module/gas_refill/gas_refill_request_form.dart'; -import 'modules/traf_module/traf_request_provider.dart'; -import 'modules/traf_module/create_traf_request_page.dart'; import 'modules/traf_module/update_traf_request_page.dart'; import 'providers/lookups/classification_lookup_provider.dart'; import 'providers/lookups/customer_lookup_provider.dart'; @@ -406,7 +404,6 @@ class MyApp extends StatelessWidget { // UTILITY PROVIDERS (1) ChangeNotifierProvider(create: (_) => OracleCodeProvider(), lazy: true), - ChangeNotifierProvider(create: (_) => TrafRequestProvider(), lazy: true), ], child: GestureDetector( onTap: () { @@ -447,7 +444,6 @@ class MyApp extends StatelessWidget { DeviceSearchScreen.id: (_) => const DeviceSearchScreen(), DeviceFilterScreen.id: (_) => const DeviceFilterScreen(), CreateIncidentRequestPage.id: (_) => CreateIncidentRequestPage(), - CreateTRAFRequestPage.id: (_) => CreateTRAFRequestPage(), SettingsPage.id: (_) => const SettingsPage(), ProfilePage.id: (_) => const ProfilePage(), ReportBugPage.id: (_) => const ReportBugPage(), From fac7b92711d5c2e015a545569898b9c82010add5 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 31 Aug 2026 09:14:48 +0300 Subject: [PATCH 25/47] improvement. --- lib/modules/incident_module/incident_detail_page.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/modules/incident_module/incident_detail_page.dart b/lib/modules/incident_module/incident_detail_page.dart index 55282143..848a59c5 100644 --- a/lib/modules/incident_module/incident_detail_page.dart +++ b/lib/modules/incident_module/incident_detail_page.dart @@ -85,7 +85,7 @@ class IncidentDetailPage extends StatelessWidget { ], ).toShadowContainer(context), ); - })); + }))); } List requestDetails(BuildContext context, IncidentDataModel incidentData) { From 4ca6862f3bef3275e1a8e0abe4b319c5f880c918 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 1 Sep 2026 10:10:26 +0300 Subject: [PATCH 26/47] apk provided to QA --- lib/controllers/api_routes/urls.dart | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 5dd33c86..85a70b8e 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -4,12 +4,12 @@ class URLs { static const String appReleaseBuildNumber = "53"; // static const host1 = "https://atomsm.hmg.com"; // production url - static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url + static const host1 = "https://atomsmuat.hmg.com"; // local UAT url // static final String _baseUrl = "$_host/mobile"; // host local UAT - // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis - static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM + static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis + // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation // static final String _baseUrl = "$_host/v6/mobile"; // for asset delivery module From 51d1f38083da4f143d003685642a002bc7fa416c Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Tue, 1 Sep 2026 17:30:09 +0300 Subject: [PATCH 27/47] user site api added --- lib/controllers/api_routes/urls.dart | 9 +++-- .../providers/site_request_provider.dart | 19 +++++++++ .../screens/site_request_form_screen.dart | 39 ++++++++++++++++++- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index f45e772e..1055c3e4 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -3,13 +3,13 @@ class URLs { static const String appReleaseBuildNumber = "53"; - static const host1 = "https://atomsm.hmg.com"; // production url + // static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + static const host1 = "https://atomsmuat.hmg.com"; // local UAT url - // static final String _baseUrl = "$_host/mobile"; // host local UAT + static final String _baseUrl = "$_host/mobile"; // host local UAT // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis - static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM + // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation // static final String _baseUrl = "$_host/v6/mobile"; // for asset delivery module @@ -68,6 +68,7 @@ class URLs { static get getSiteRequests => "$_baseUrl/SiteRequest/GetSiteRequests"; // get site request history static get getDepartmentsBySites => "$_baseUrl/Customer/GetDepartmentsBySites"; // post get departments by sites static getUserSites(String userId) => "$_baseUrl/Customer/GetSitesForUser?userId=$userId"; // get user's current sites + static getSitesNotAccessibleForUser(String userId) => "$_baseUrl/Customer/GetSitesNotAccessibleForUser?userId=$userId"; // get user's current sites // static get login => "$_baseUrl/MobileAuth/LoginIntegration"; // mobile login static get register => "$_baseUrl/handle/create/user"; // post diff --git a/lib/modules/site_request_module/providers/site_request_provider.dart b/lib/modules/site_request_module/providers/site_request_provider.dart index d97b5b7d..0b4191ab 100644 --- a/lib/modules/site_request_module/providers/site_request_provider.dart +++ b/lib/modules/site_request_module/providers/site_request_provider.dart @@ -27,6 +27,7 @@ class SiteRequestProvider extends ChangeNotifier { // Data List _requestTypes = []; List _userCurrentSites = []; + List userFilterSites = []; List _requestHistory = []; // Pagination @@ -124,6 +125,24 @@ class SiteRequestProvider extends ChangeNotifier { errorMessage: 'Failed to fetch user sites', ); } + Future fetchUserFilteredSites(String userId) async { + if (_loading) return -2; + return _performApiCall( + apiCall: () => ApiManager.instance.post(URLs.getSitesNotAccessibleForUser(userId), showToast: false, body: {}), + onSuccess: (responseData) { + List listJson = responseData['data'] ?? []; + userFilterSites = listJson + .map((item) => SiteRequestSiteModel( + id: item['siteId']?.toString() ?? '', + name: item['siteName'] ?? '', + )) + .toList(); + notifyListeners(); + }, + errorMessage: 'Failed to fetch user sites', + ); + + } /// Submits a site request to the server Future submitSiteRequest(SiteRequestModel request, UserProvider userProvider) async { diff --git a/lib/modules/site_request_module/screens/site_request_form_screen.dart b/lib/modules/site_request_module/screens/site_request_form_screen.dart index 1dde072a..86b905d5 100644 --- a/lib/modules/site_request_module/screens/site_request_form_screen.dart +++ b/lib/modules/site_request_module/screens/site_request_form_screen.dart @@ -175,11 +175,12 @@ class _SiteRequestFormScreenState extends State { _siteReplacements.clear(); _loadedDepartmentSiteIds.clear(); // Reset loaded department site IDs }); - + final userId = _provider.getCurrentUserUserId(_userProvider); // Fetch user's current sites if Change Site or Remove Site is selected if ((_isChangeSiteRequest() || _isRemoveSiteRequest()) && value != null) { - final userId = _provider.getCurrentUserUserId(_userProvider); await _provider.fetchUserCurrentSites(userId); + }else { + await _provider.fetchUserFilteredSites(userId); } // Fetch all sites if Change Site is selected (needed for new site dropdown) @@ -318,6 +319,40 @@ class _SiteRequestFormScreenState extends State { } Widget _buildSiteMultiSelect() { + return MultipleItemDropDownMenu( + context: context, + title: context.translation.site, + initialValue: _selectedSites + .map((s) => SiteRequestSiteModel( + id: s.identifier ?? '', + name: s.name ?? '', + )) + .toList(), + staticData: _provider.userFilterSites, + showAsFullScreenDialog: true, + backgroundColor: context.isDark ? AppColor.neutral60 : Colors.white, + showShadow: true, + height: 56.toScreenHeight, + showCancel: true, + onSelect: (value) { + if (value != null) { + setState(() { + _selectedSites = value.map((s) { + final site = Site( + id: int.tryParse(s.identifier ?? '0'), + custName: s.name, + ); + return site; + }).toList(); + final departmentProvider = Provider.of(context, listen: false); + final siteIds = value.map((site) => int.tryParse(site.identifier ?? '0') ?? 0).toList(); + departmentProvider.setSiteIds(siteIds); + departmentProvider.getData(); + }); + + } + }, + ); return MultipleItemDropDownMenu( context: context, title: context.translation.site, From e1f52b9925b48c692a82466925fc07ab4c9bb198 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Sun, 6 Sep 2026 08:10:24 +0300 Subject: [PATCH 28/47] improvement --- .../device_transfer_details.dart | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/modules/tm_module/device_transfer/device_transfer_details.dart b/lib/modules/tm_module/device_transfer/device_transfer_details.dart index 5a4933d4..f39e4c6f 100644 --- a/lib/modules/tm_module/device_transfer/device_transfer_details.dart +++ b/lib/modules/tm_module/device_transfer/device_transfer_details.dart @@ -76,6 +76,7 @@ class _DeviceTransferDetailsState extends State { stateCode: 200, onRefresh: () async {}, child: SingleChildScrollView( + padding: const EdgeInsets.all(16), child: Column( children: [ Column( @@ -124,18 +125,20 @@ class _DeviceTransferDetailsState extends State { InfoHeader16Widget("Attachments".addTranslation), 4.height, FilesList( - showAsListView: true, - types: _model?.assetTransferAttachments!=null? - _model!.assetTransferAttachments!.whereType() - .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) - .map((toElement) => toElement.documentType!.name!) - .toList():[], + showAsListView: true, + types: _model?.assetTransferAttachments != null + ? _model!.assetTransferAttachments! + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList() + : [], images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []), ] ], ), ], - ).toShadowContainer(context, padding: 16), + ).toShadowContainer(context), 8.height, if (_model?.transferType?.value == 1) ...[ _internalRequestDetailsCard() @@ -180,7 +183,7 @@ class _DeviceTransferDetailsState extends State { ), ], ], - ).paddingAll(16), + ), ), ), ) From 2bb126c91f0f57080771230afc941f2236ffa9dc Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Wed, 9 Sep 2026 12:16:27 +0300 Subject: [PATCH 29/47] ios version upgraded to 15 --- ios/Podfile | 6 +++--- ios/Runner.xcodeproj/project.pbxproj | 12 ++++++------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/ios/Podfile b/ios/Podfile index 5596a08a..72d600e0 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -platform :ios, '14.0' +platform :ios, '15.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' @@ -40,7 +40,7 @@ post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0' + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0' # Fix for Xcode 15+ DT_TOOLCHAIN_DIR issue if config.base_configuration_reference && File.exist?(config.base_configuration_reference.real_path) @@ -55,7 +55,7 @@ post_install do |installer| installer.generated_projects.each do |project| project.targets.each do |target| target.build_configurations.each do |config| - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0' + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0' config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [ '$(inherited)', ## dart: PermissionGroup.microphone diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 3c09fbf5..e0fcb9d1 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -379,7 +379,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -403,7 +403,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = Atoms; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -534,7 +534,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -587,7 +587,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -613,7 +613,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = Atoms; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -709,7 +709,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; INFOPLIST_FILE = Runner/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = Atoms; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", From eb880893e246263a16d50b7de17f09a5bff8391b Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Wed, 9 Sep 2026 15:45:25 +0300 Subject: [PATCH 30/47] release config --- lib/controllers/api_routes/urls.dart | 2 +- pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index ead55e82..777758c6 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -1,7 +1,7 @@ class URLs { URLs._(); - static const String appReleaseBuildNumber = "53"; + static const String appReleaseBuildNumber = "54"; // static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url diff --git a/pubspec.yaml b/pubspec.yaml index ccf2f535..4634a19a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 1.9.3+53 +version: 1.9.4+54 environment: sdk: ">=3.5.0 <4.0.0" From fbd5d8167d6f2a6af60867577624f1af704feba6 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Thu, 10 Sep 2026 10:37:22 +0300 Subject: [PATCH 31/47] v1.9.4+54 uploaded. --- lib/controllers/api_routes/urls.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 777758c6..0e1858df 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -3,9 +3,9 @@ class URLs { static const String appReleaseBuildNumber = "54"; - // static const host1 = "https://atomsm.hmg.com"; // production url + static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url static final String _baseUrl = "$_host/mobile"; // host local UAT // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis From 4bdb5c2da33e94312019d7cf105b2dd0025f8369 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Tue, 15 Sep 2026 10:20:09 +0300 Subject: [PATCH 32/47] improvements --- .../medical_gas_inspection/models/medical_gas_form_model.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/modules/medical_gas_inspection/models/medical_gas_form_model.dart b/lib/modules/medical_gas_inspection/models/medical_gas_form_model.dart index a3f08ac1..fa55d368 100644 --- a/lib/modules/medical_gas_inspection/models/medical_gas_form_model.dart +++ b/lib/modules/medical_gas_inspection/models/medical_gas_form_model.dart @@ -55,7 +55,7 @@ class MedicalGasFormModel { 'siteId': site?.id, 'supplierId': supplier?.id, 'isSubmitted': isSubmitted, - 'gasRequestDetailDtos': gasRequestDetail?.map((e) => e.toJson()).toList(), + 'gasRequestDetailDtos': gasRequestDetail != null ? gasRequestDetail?.map((e) => e.toJson()).toList() : [], }; } } @@ -81,7 +81,7 @@ class MedicalGasFormDetailModel { return { 'id': id, 'medicalGasAttributeId': medicalGasAttributeId, - 'requestedQuantity': requestedQuantity??0, + 'requestedQuantity': requestedQuantity ?? 0, }; } } From 709b8a699bff5b3d3b3b716fd880bcd90738ecd3 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 15 Sep 2026 15:14:40 +0300 Subject: [PATCH 33/47] bug 2247 fixed --- lib/views/widgets/images/files_list.dart | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/views/widgets/images/files_list.dart b/lib/views/widgets/images/files_list.dart index 0590c60e..223fedff 100644 --- a/lib/views/widgets/images/files_list.dart +++ b/lib/views/widgets/images/files_list.dart @@ -42,6 +42,14 @@ class FilesList extends StatelessWidget { var isPdf = images[itemIndex].split(".").last.toLowerCase() == "pdf"; var isExcel = images[itemIndex].split(".").last.toLowerCase() == "xlsx"; + String checkNull(int index) { + try { + return types[itemIndex]; + } catch (ex) { + return "Asset Guide"; + } + } + return Row( spacing: 8, children: [ @@ -81,7 +89,7 @@ class FilesList extends StatelessWidget { 2.height, RichText( text: TextSpan( - text: '${types.isEmpty ? "Asset Guide" : types[itemIndex]} | ', + text: '${types.isEmpty ? "Asset Guide" : checkNull(itemIndex)} | ', style: AppTextStyles.tinyFont.copyWith(color: AppColor.lightTextColor(context)), children: [ TextSpan( From fa254ca73ba679862cf84eac0c2af310850dfc68 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 15 Sep 2026 15:30:53 +0300 Subject: [PATCH 34/47] improvement --- lib/views/widgets/images/multi_image_picker.dart | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/views/widgets/images/multi_image_picker.dart b/lib/views/widgets/images/multi_image_picker.dart index 57943a5d..70a1472d 100644 --- a/lib/views/widgets/images/multi_image_picker.dart +++ b/lib/views/widgets/images/multi_image_picker.dart @@ -228,6 +228,7 @@ class _AttachmentPickerState extends State with SingleTickerPr ImageSource? source = await showModalBottomSheet( context: context, + backgroundColor: Colors.transparent, builder: (BuildContext context) { return StatefulBuilder( builder: (BuildContext context, StateSetter setModalState) { From 85bcc1a0eae12f4bf00ee28f538532f5ded9b2f8 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Sun, 20 Sep 2026 09:18:38 +0300 Subject: [PATCH 35/47] Fixed bug ATOMS-2248 --- lib/models/generic_attachment_model.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 0821953f..15068740 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -78,7 +78,7 @@ class GenericAttachmentModel { id = json['id']?.toInt(); name = json['attachmentName']; attachmentDescription = json['attachmentDescription']; - documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; moduleReferenceId = json['loanId']; attachmentTypeId = json['loanAttachmentTypeId']; } @@ -88,7 +88,7 @@ class GenericAttachmentModel { name = json['attachmentName']; attachmentDescription = json['attachmentDescription']; moduleReferenceId = json['loanId']; - documentType = json['attachmentType'] != null ? Lookup.fromJson(json['attachmentType']) : null; + documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; attachmentTypeId = json['loanAttachmentTypeId']; createdBy = json['createdBy']; createdDate = json['createdDate']; From 6ad8471e9b3b396af3fa55dc7e0db6aaf3152ebd Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 29 Sep 2026 09:58:50 +0300 Subject: [PATCH 36/47] loading issue fixed in cm update spare part --- lib/modules/cm_module/cm_detail_provider.dart | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/lib/modules/cm_module/cm_detail_provider.dart b/lib/modules/cm_module/cm_detail_provider.dart index 9aa4aa4d..f328ad33 100644 --- a/lib/modules/cm_module/cm_detail_provider.dart +++ b/lib/modules/cm_module/cm_detail_provider.dart @@ -747,23 +747,16 @@ class CMDetailProvider extends ChangeNotifier { } } - Future updateActivitySparePart() async { - isLoading = true; + Future updateActivitySparePart() async { Response response; try { response = await ApiManager.instance.post(URLs.updateActivitySparePartUrl, body: sparePartHelperModel!.toJson()); - stateCode = response.statusCode; - isLoading = false; - notifyListeners(); if (stateCode == 200) { - return true; + return ""; } - return false; + return "Failed, Try Again"; } catch (error) { - isLoading = false; - stateCode = -1; - notifyListeners(); - return false; + return "Failed, Try Again"; } } From 072953a3a72d5af0955d467af76f1654262fbc36 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Sun, 11 Oct 2026 16:02:19 +0300 Subject: [PATCH 37/47] role name added --- lib/dashboard_latest/widgets/app_bar_widget.dart | 2 +- lib/models/user.dart | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/dashboard_latest/widgets/app_bar_widget.dart b/lib/dashboard_latest/widgets/app_bar_widget.dart index 39a97f7a..a08a9809 100644 --- a/lib/dashboard_latest/widgets/app_bar_widget.dart +++ b/lib/dashboard_latest/widgets/app_bar_widget.dart @@ -145,7 +145,7 @@ class _AppBarWidgetState extends State with TickerProviderStateMix style: AppTextStyles.heading6.copyWith(color: AppColor.headingTextColor(context), fontSize: context.isTablet() ? 14 : null), ), Text( - snapshot.user?.type?.name.toCamelCase ?? "", + snapshot.user?.roleName ?? "", style: AppTextStyles.bodyText.copyWith(color: AppColor.lightTextColor(context), fontSize: context.isTablet() ? 12 : null), ), ], diff --git a/lib/models/user.dart b/lib/models/user.dart index aa3389dc..608e0989 100644 --- a/lib/models/user.dart +++ b/lib/models/user.dart @@ -100,6 +100,8 @@ class User { return {"username": userName, "password": password, "fireBaseToken": FirebaseNotificationManger?.token ?? "", "notificationType": notificationType}; } + String get roleName => userRoles?.first.name ?? ""; + UsersTypes? get type { switch (userRoles?.first.value) { case "R-6": From e4a09fed1f694916d50ab5f5cbdc2db85bf8bcff Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Sun, 11 Oct 2026 18:08:15 +0300 Subject: [PATCH 38/47] improvement --- .../widgets/app_bar_widget.dart | 11 ++++++----- .../device_transfer/device_filter_screen.dart | 19 +++++++++++-------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/lib/dashboard_latest/widgets/app_bar_widget.dart b/lib/dashboard_latest/widgets/app_bar_widget.dart index a08a9809..8dcc73b2 100644 --- a/lib/dashboard_latest/widgets/app_bar_widget.dart +++ b/lib/dashboard_latest/widgets/app_bar_widget.dart @@ -142,18 +142,19 @@ class _AppBarWidgetState extends State with TickerProviderStateMix children: [ Text( snapshot.user?.username ?? "", + maxLines: 2, style: AppTextStyles.heading6.copyWith(color: AppColor.headingTextColor(context), fontSize: context.isTablet() ? 14 : null), ), - Text( - snapshot.user?.roleName ?? "", - style: AppTextStyles.bodyText.copyWith(color: AppColor.lightTextColor(context), fontSize: context.isTablet() ? 12 : null), - ), + // Text( + // snapshot.user?.roleName ?? "", + // style: AppTextStyles.bodyText.copyWith(color: AppColor.lightTextColor(context), fontSize: context.isTablet() ? 12 : null), + // ), ], ), ), ), ), - const Spacer(), + // const Spacer(), // Action icons with right-to-left fade animation SlideTransition( position: _rightSlideAnimation, diff --git a/lib/modules/tm_module/device_transfer/device_filter_screen.dart b/lib/modules/tm_module/device_transfer/device_filter_screen.dart index 04802a5e..9540c5d8 100644 --- a/lib/modules/tm_module/device_transfer/device_filter_screen.dart +++ b/lib/modules/tm_module/device_transfer/device_filter_screen.dart @@ -1,5 +1,7 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import 'package:test_sa/controllers/api_routes/api_manager.dart'; +import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/providers/api/devices_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; @@ -117,14 +119,15 @@ class _DeviceFilterScreenState extends State { ListView( padding: const EdgeInsets.all(16), children: [ - AssetStatusButtons( - initialValue: _commissioningStatus, - onSelect: (value) { - if (value != null) { - _commissioningStatus = value; - } - }, - ), + // AssetStatusButtons( + // initialValue: _commissioningStatus, + // onSelect: (value) { + // if (value != null) { + // _commissioningStatus = value; + // } + // }, + // ), + context.translation.filter.heading5(context).custom(color: AppColor.textStyleColor(context)), 16.height, MultipleItemDropDownMenu( context: context, From 2ab2abd6938742dbe7a7d4736042ca138434c428 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 12 Oct 2026 11:06:29 +0300 Subject: [PATCH 39/47] site are changed as per organization --- lib/controllers/api_routes/urls.dart | 5 ++-- lib/main.dart | 1 + .../create_device_transfer_request.dart | 3 ++- .../device_transfer/device_filter_screen.dart | 3 ++- .../gas_request_providers/site_provider.dart | 25 +++++++++++++++++++ 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 0e1858df..68dfcd26 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -3,9 +3,9 @@ class URLs { static const String appReleaseBuildNumber = "54"; - static const host1 = "https://atomsm.hmg.com"; // production url + // static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + static const host1 = "https://atomsmuat.hmg.com"; // local UAT url static final String _baseUrl = "$_host/mobile"; // host local UAT // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis @@ -69,6 +69,7 @@ class URLs { static get getDepartmentsBySites => "$_baseUrl/Customer/GetDepartmentsBySites"; // post get departments by sites static getUserSites(String userId) => "$_baseUrl/Customer/GetSitesForUser?userId=$userId"; // get user's current sites static getSitesNotAccessibleForUser(String userId) => "$_baseUrl/Customer/GetSitesNotAccessibleForUser?userId=$userId"; // get user's current sites + static get getCustomersAutoCompleteSameOrg => "$_baseUrl/Customer/GetCustomersAutoCompleteSameOrg"; // get user's current sites // static get login => "$_baseUrl/MobileAuth/LoginIntegration"; // mobile login static get register => "$_baseUrl/handle/create/user"; // post diff --git a/lib/main.dart b/lib/main.dart index 90efc744..de8877f4 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -357,6 +357,7 @@ class MyApp extends StatelessWidget { ChangeNotifierProvider(create: (_) => DepartmentProvider(), lazy: true), ChangeNotifierProvider(create: (_) => DepartmentBySitesProvider(), lazy: true), ChangeNotifierProvider(create: (_) => SiteProvider(), lazy: true), + ChangeNotifierProvider(create: (_) => SameOrgSiteProvider(), lazy: true), ChangeNotifierProvider(create: (_) => MappedSiteProvider(), lazy: true), ChangeNotifierProvider(create: (_) => MedicalDepartmentProvider(), lazy: true), ChangeNotifierProvider(create: (_) => FlowMedicalDepartmentProvider(), lazy: true), diff --git a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart index 89c92bc1..f639fcb2 100644 --- a/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart +++ b/lib/modules/tm_module/device_transfer/create_device_transfer_request.dart @@ -155,8 +155,9 @@ class _CreateDeviceTransferRequestState extends State( + SingleItemDropDownMenu( context: context, + requestById: context.userProvider.user?.clientId, title: context.translation.site, initialValue: _assetDestination.site, disableValue: isInternal ? null : _pickedAsset?.site, diff --git a/lib/modules/tm_module/device_transfer/device_filter_screen.dart b/lib/modules/tm_module/device_transfer/device_filter_screen.dart index 9540c5d8..19fb163a 100644 --- a/lib/modules/tm_module/device_transfer/device_filter_screen.dart +++ b/lib/modules/tm_module/device_transfer/device_filter_screen.dart @@ -148,11 +148,12 @@ class _DeviceFilterScreenState extends State { }, ), 12.height, - MultipleItemDropDownMenu( + MultipleItemDropDownMenu( context: context, title: context.translation.bySite, initialValue: _selectedSites, showAsBottomSheet: true, + requestById: context.userProvider.user?.clientId, // backgroundColor: AppColor.fieldBgColor(context), backgroundColor: context.isDark ? AppColor.neutral60 : Colors.white, showShadow: true, diff --git a/lib/providers/gas_request_providers/site_provider.dart b/lib/providers/gas_request_providers/site_provider.dart index d497a88d..c2ce34f4 100644 --- a/lib/providers/gas_request_providers/site_provider.dart +++ b/lib/providers/gas_request_providers/site_provider.dart @@ -33,6 +33,31 @@ class SiteProvider extends LoadingListNotifier { } } +class SameOrgSiteProvider extends LoadingListNotifier { + @override + Future getData({int? id}) async { + if (loading ?? false) return -2; + loading = true; + notifyListeners(); + try { + Response response = await ApiManager.instance.get(URLs.getCustomersAutoCompleteSameOrg + "?senderSiteId=$id"); + stateCode = response.statusCode; + if (response.statusCode >= 200 && response.statusCode < 300) { + List categoriesListJson = json.decode(response.body)["data"]; + items = categoriesListJson.map((item) => Site.fromJson(item)).toList(); + } + loading = false; + notifyListeners(); + return response.statusCode; + } catch (error) { + loading = false; + stateCode = -1; + notifyListeners(); + return -1; + } + } +} + class MappedSiteProvider extends LoadingListNotifier { @override Future getData({int? id}) async { From 494d9ba8d737cf5a3e977d2d4355db7b64c17b59 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 12 Oct 2026 15:36:45 +0300 Subject: [PATCH 40/47] get site by user id replace in asset filters --- .../providers/site_request_provider.dart | 20 +++++++++++- .../device_transfer/device_filter_screen.dart | 32 +++++++++++-------- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/lib/modules/site_request_module/providers/site_request_provider.dart b/lib/modules/site_request_module/providers/site_request_provider.dart index 0b4191ab..375c4d86 100644 --- a/lib/modules/site_request_module/providers/site_request_provider.dart +++ b/lib/modules/site_request_module/providers/site_request_provider.dart @@ -107,6 +107,24 @@ class SiteRequestProvider extends ChangeNotifier { ); } + /// Fetches user's current sites for Change/Remove Site operations + Future> getSitesByUserId(String userId) async { + List usersSite = []; + try { + Response response = await ApiManager.instance.post(URLs.getUserSites(userId), body: {},showToast: false); + if (response.statusCode >= 200 && response.statusCode < 300) { + List categoriesListJson = json.decode(response.body)["data"]; + usersSite = categoriesListJson + .map((item) => SiteRequestSiteModel( + id: item['siteId']?.toString() ?? '', + name: item['siteName'] ?? '', + )) + .toList(); + } + } catch (ex) {} + return usersSite; + } + /// Fetches user's current sites for Change/Remove Site operations Future fetchUserCurrentSites(String userId) async { if (_loading) return -2; @@ -125,6 +143,7 @@ class SiteRequestProvider extends ChangeNotifier { errorMessage: 'Failed to fetch user sites', ); } + Future fetchUserFilteredSites(String userId) async { if (_loading) return -2; return _performApiCall( @@ -141,7 +160,6 @@ class SiteRequestProvider extends ChangeNotifier { }, errorMessage: 'Failed to fetch user sites', ); - } /// Submits a site request to the server diff --git a/lib/modules/tm_module/device_transfer/device_filter_screen.dart b/lib/modules/tm_module/device_transfer/device_filter_screen.dart index 19fb163a..3458f9cb 100644 --- a/lib/modules/tm_module/device_transfer/device_filter_screen.dart +++ b/lib/modules/tm_module/device_transfer/device_filter_screen.dart @@ -1,23 +1,21 @@ import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; -import 'package:test_sa/controllers/api_routes/api_manager.dart'; -import 'package:test_sa/controllers/api_routes/urls.dart'; import 'package:test_sa/controllers/providers/api/devices_provider.dart'; import 'package:test_sa/extensions/context_extension.dart'; import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; +import 'package:test_sa/helper/utils.dart'; import 'package:test_sa/models/lookup.dart'; -import 'package:test_sa/models/new_models/site.dart'; import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart'; +import 'package:test_sa/modules/site_request_module/models/dropdown_models.dart'; +import 'package:test_sa/modules/site_request_module/providers/site_request_provider.dart'; import 'package:test_sa/new_views/app_style/app_color.dart'; import 'package:test_sa/new_views/common_widgets/app_filled_button.dart'; import 'package:test_sa/new_views/common_widgets/multiple_item_drop_down_menu.dart'; import 'package:test_sa/providers/department_provider.dart'; -import 'package:test_sa/providers/gas_request_providers/site_provider.dart'; +import 'package:test_sa/providers/loading_list_notifier.dart'; import 'package:test_sa/views/widgets/date_and_time/date_picker.dart'; -import 'package:test_sa/views/widgets/equipment/asset_status_buttons.dart'; - import '../../../models/device/asset_search.dart'; import '../../../new_views/common_widgets/app_lazy_loading.dart'; import '../../../new_views/common_widgets/default_app_bar.dart'; @@ -35,11 +33,13 @@ class DeviceFilterScreen extends StatefulWidget { class _DeviceFilterScreenState extends State { late DeviceSearch filter; Lookup? _commissioningStatus; - List _selectedSites = []; + List _selectedSites = []; List _selectedDepartments = []; String? startDate, endDate; bool loading = false; + List userSites = []; + @override void initState() { filter = widget.data ?? DeviceSearch(); @@ -49,10 +49,14 @@ class _DeviceFilterScreenState extends State { startDate = filter.supplyDateFrom; endDate = filter.supplyDateTo; _commissioningStatus = filter.assetStatus; + final departmentProvider = Provider.of(context, listen: false); - final siteProvider = Provider.of(context, listen: false); if (departmentProvider.items.isEmpty ?? true) await departmentProvider.getData(); - if (siteProvider.items.isEmpty ?? true) await siteProvider.getData(); + if (userSites.isEmpty) { + Utils.showLoading(context); + userSites = await Provider.of(context, listen: false).getSitesByUserId(context.userProvider.user?.userID ?? ""); + Utils.hideLoading(context); + } // Initialize selected departments from filter if (filter.departments != null && filter.departments!.isNotEmpty) { @@ -72,11 +76,11 @@ class _DeviceFilterScreenState extends State { if (filter.sites != null && filter.sites!.isNotEmpty) { _selectedSites = []; for (var siteName in filter.sites!) { - final match = siteProvider.items.firstWhere( + final match = userSites.firstWhere( (site) => site.name == siteName, - orElse: () => Site(), + orElse: () => SiteRequestSiteModel(id: '', name: ''), ); - if (match.id != null) { + if (match.identifier != null) { _selectedSites.add(match); } } @@ -148,12 +152,12 @@ class _DeviceFilterScreenState extends State { }, ), 12.height, - MultipleItemDropDownMenu( + MultipleItemDropDownMenu( context: context, title: context.translation.bySite, initialValue: _selectedSites, showAsBottomSheet: true, - requestById: context.userProvider.user?.clientId, + staticData: userSites, // backgroundColor: AppColor.fieldBgColor(context), backgroundColor: context.isDark ? AppColor.neutral60 : Colors.white, showShadow: true, From 4218acb4b8fa0e066c9952f9c258a5dd52829982 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 12 Oct 2026 15:44:10 +0300 Subject: [PATCH 41/47] improvement --- .../tm_module/device_transfer/device_filter_screen.dart | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/modules/tm_module/device_transfer/device_filter_screen.dart b/lib/modules/tm_module/device_transfer/device_filter_screen.dart index 3458f9cb..cdd65c2d 100644 --- a/lib/modules/tm_module/device_transfer/device_filter_screen.dart +++ b/lib/modules/tm_module/device_transfer/device_filter_screen.dart @@ -51,13 +51,13 @@ class _DeviceFilterScreenState extends State { _commissioningStatus = filter.assetStatus; final departmentProvider = Provider.of(context, listen: false); + Utils.showLoading(context); if (departmentProvider.items.isEmpty ?? true) await departmentProvider.getData(); if (userSites.isEmpty) { - Utils.showLoading(context); userSites = await Provider.of(context, listen: false).getSitesByUserId(context.userProvider.user?.userID ?? ""); - Utils.hideLoading(context); } - + await Future.delayed(const Duration(milliseconds: 100)); + Utils.hideLoading(context); // Initialize selected departments from filter if (filter.departments != null && filter.departments!.isNotEmpty) { _selectedDepartments = []; From a9000de678158628b8362e39dcad2ebc972931a3 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Mon, 12 Oct 2026 16:05:30 +0300 Subject: [PATCH 42/47] v1.9.5+55 uploaded on stores --- lib/controllers/api_routes/urls.dart | 6 +++--- pubspec.yaml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 68dfcd26..1a13c9c3 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -1,11 +1,11 @@ class URLs { URLs._(); - static const String appReleaseBuildNumber = "54"; + static const String appReleaseBuildNumber = "55"; - // static const host1 = "https://atomsm.hmg.com"; // production url + static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url static final String _baseUrl = "$_host/mobile"; // host local UAT // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis diff --git a/pubspec.yaml b/pubspec.yaml index 4634a19a..b2e61e4a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 1.9.4+54 +version: 1.9.5+55 environment: sdk: ">=3.5.0 <4.0.0" From 50df0fb5b83dd56d9674b3780f6798fdd8920900 Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Tue, 20 Oct 2026 08:27:24 +0300 Subject: [PATCH 43/47] merge conflict resolve --- .../spare_part/activity_spare_part_model.dart | 8 ++-- .../plan_preventive_visit_model.dart | 45 +++++++++---------- .../activities/pm_activities_list_view.dart | 2 +- 3 files changed, 25 insertions(+), 30 deletions(-) diff --git a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart index 6e051b66..68586a44 100644 --- a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart +++ b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart @@ -28,7 +28,7 @@ class SparePartHelperModel { this.activityStatusId, this.activityStatus, this.comment, - List? sparePartAttachments, + List? sparePartAttachments, }) : sparePartAttachments = sparePartAttachments ?? []; Map toJson() { @@ -44,11 +44,11 @@ class SparePartHelperModel { } data['comment'] = comment; if (sparePartAttachments != null) { - data['acitiySparePartAttachments'] = - sparePartAttachments!.map((v) => v?.toJson() ?? {}).toList(); + data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v?.toJson() ?? {}).toList(); } return data; } + Map toPMJson() { final Map data = {}; data['id'] = id; @@ -58,7 +58,7 @@ class SparePartHelperModel { data['comment'] = comment; data['installQty'] = installQty; data['returnQty'] = returnQty; - if (sparePartAttachments.isNotEmpty) { + if (sparePartAttachments?.isNotEmpty ?? false) { data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toJson()).toList(); } return data; diff --git a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart index d2471a6b..99a51444 100644 --- a/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart +++ b/lib/models/plan_preventive_visit/plan_preventive_visit_model.dart @@ -65,7 +65,6 @@ class PlanPreventiveVisit { List? timerModelList = []; TimerModel? ppMTimePicker; - PlanPreventiveVisit( {this.id, this.visitNo, @@ -109,14 +108,14 @@ class PlanPreventiveVisit { this.timerModelList, this.ppMTimePicker, this.activities, - this.labourCost, - this.sparePartCost, - this.travelCost, - this.qAmount, - this.prNo, - this.poNo, - this.mrNo, - this.exchangeCost, + this.labourCost, + this.sparePartCost, + this.travelCost, + this.qAmount, + this.prNo, + this.poNo, + this.mrNo, + this.exchangeCost, this.preventiveVisitSuppliers}); PlanPreventiveVisit.fromJson(Map json) { @@ -153,14 +152,14 @@ class PlanPreventiveVisit { safety = json['safety'] != null ? Lookup.fromJson(json['safety']) : null; engSignature = json['engSignature']; nurseSignature = json['nurseSignature']; - travelCost= json['travelCost']; - sparePartCost= json['sparePartCost']; - labourCost =json['laborCost']; - qAmount= json['qAmount']; - prNo= json['prNo']; - poNo= json['poNo']; - mrNo= json['mrNo']; - exchangeCost= json['exchangeCost']; + travelCost = json['travelCost']; + sparePartCost = json['sparePartCost']; + labourCost = json['laborCost']; + qAmount = json['qAmount']; + prNo = json['prNo']; + poNo = json['poNo']; + mrNo = json['mrNo']; + exchangeCost = json['exchangeCost']; if (json['preventiveVisitAttachments'] != null) { preventiveVisitAttachments = []; json['preventiveVisitAttachments'].forEach((v) { @@ -487,7 +486,7 @@ class PMSparePartActivityModel { String? comment; dynamic price; - List activitySparePartPPMAttachments; + List activitySparePartPPMAttachments; PMSparePartActivityModel({ this.id, @@ -498,7 +497,7 @@ class PMSparePartActivityModel { this.returnQty, this.comment, this.price, - List? activitySparePartPPMAttachments, + List? activitySparePartPPMAttachments, }) : activitySparePartPPMAttachments = activitySparePartPPMAttachments ?? []; PMSparePartActivityModel.fromJson(Map json) : activitySparePartPPMAttachments = [] { @@ -516,13 +515,9 @@ class PMSparePartActivityModel { price = json['price']; // Handle typo in API response: "acitiySparePartPPMAttachments" instead of "activitySparePartPPMAttachments" - final attachmentsKey = json.containsKey('acitiySparePartPPMAttachments') - ? 'acitiySparePartPPMAttachments' - : 'activitySparePartPPMAttachments'; + final attachmentsKey = json.containsKey('acitiySparePartPPMAttachments') ? 'acitiySparePartPPMAttachments' : 'activitySparePartPPMAttachments'; - activitySparePartPPMAttachments = json[attachmentsKey] == null - ? [] - : List.from(json[attachmentsKey]).map((e) => SparePartAttachments.fromJson(e)).toList(); + activitySparePartPPMAttachments = json[attachmentsKey] == null ? [] : List.from(json[attachmentsKey]).map((e) => GenericAttachmentModel.fromJson(e)).toList(); } Map toJson() { diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index a9a1542f..a4e2b18c 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -185,7 +185,7 @@ class _PmActivitiesListViewState extends State { ], if (activity.activitySparePartPPMAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList()), + FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList(), showAsListView: true), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { From 08d8bd93041aace325845d329005ad38fc147861 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Wed, 21 Oct 2026 15:37:41 +0300 Subject: [PATCH 44/47] attachment parameter fixes for sparepart request --- lib/models/generic_attachment_model.dart | 9 +++++++++ .../spare_part/activity_spare_part_model.dart | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 15068740..981db927 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -189,6 +189,15 @@ class GenericAttachmentModel { data['documentTypeId'] = documentType?.id; return data; } + Map toSparePartJson() { + final Map data = {}; + data['id'] = id; + data['name'] = name; + data['createdBy'] = createdBy; + data['originalName'] = originalName; + data['attachmentTypeId'] = documentType?.id; + return data; + } Map toWorkOrderJson() { final Map data = {}; diff --git a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart index 68586a44..0a77f858 100644 --- a/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart +++ b/lib/models/helper_data_models/spare_part/activity_spare_part_model.dart @@ -44,7 +44,7 @@ class SparePartHelperModel { } data['comment'] = comment; if (sparePartAttachments != null) { - data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v?.toJson() ?? {}).toList(); + data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v?.toSparePartJson() ?? {}).toList(); } return data; } @@ -59,7 +59,7 @@ class SparePartHelperModel { data['installQty'] = installQty; data['returnQty'] = returnQty; if (sparePartAttachments?.isNotEmpty ?? false) { - data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toJson()).toList(); + data['acitiySparePartAttachments'] = sparePartAttachments!.map((v) => v.toSparePartJson()).toList(); } return data; } From bce5691b13b166e86c7be5cd4d748d5c0597c1e3 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Thu, 22 Oct 2026 09:17:54 +0300 Subject: [PATCH 45/47] improvements --- lib/models/enums/request_attachment_type_enum.dart | 11 +++++++++-- .../views/forms/spare_part/spare_part_request.dart | 2 +- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/models/enums/request_attachment_type_enum.dart b/lib/models/enums/request_attachment_type_enum.dart index 8bffa130..de1052ba 100644 --- a/lib/models/enums/request_attachment_type_enum.dart +++ b/lib/models/enums/request_attachment_type_enum.dart @@ -18,7 +18,8 @@ enum RequestAttachmentTypeEnum { incidents, // 16 sparePartActivity, // 17 updateDeliveryNotes, // 18 - traf, // 19 + traf,//19 + ppmSparePartActivity// 20 } extension RequestAttachmentTypeEnumExtension on RequestAttachmentTypeEnum { @@ -62,6 +63,8 @@ extension RequestAttachmentTypeEnumExtension on RequestAttachmentTypeEnum { return 18; case RequestAttachmentTypeEnum.traf: return 19; + case RequestAttachmentTypeEnum.ppmSparePartActivity: + return 20; } } int get lookupEnumId { @@ -101,6 +104,8 @@ extension RequestAttachmentTypeEnumExtension on RequestAttachmentTypeEnum { return 40308; case RequestAttachmentTypeEnum.sparePartActivity: return 40321; + case RequestAttachmentTypeEnum.ppmSparePartActivity: + return 4021; case RequestAttachmentTypeEnum.updateDeliveryNotes: return 40309; case RequestAttachmentTypeEnum.traf: @@ -190,7 +195,9 @@ extension RequestAttachmentTypeEnumExtension on RequestAttachmentTypeEnum { case 18: return RequestAttachmentTypeEnum.updateDeliveryNotes; case 19: - return RequestAttachmentTypeEnum.traf; + return RequestAttachmentTypeEnum.traf; + case 20: + return RequestAttachmentTypeEnum.ppmSparePartActivity; default: return null; } diff --git a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart index 85388772..1dff3d3c 100644 --- a/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart +++ b/lib/modules/cm_module/views/forms/spare_part/spare_part_request.dart @@ -310,7 +310,7 @@ class _SparePartRequestState extends State { AttachmentPicker( label: context.translation.attachQuotation, showAsListView: true, - moduleId: RequestAttachmentTypeEnum.sparePartActivity.id, + moduleId: widget.fromCm?RequestAttachmentTypeEnum.sparePartActivity.id:RequestAttachmentTypeEnum.ppmSparePartActivity.id, attachment: _attachments, buttonIcon: 'quotation_icon'.toSvgAsset(color: AppColor.primary10), buttonColor: AppColor.primary10, From f9f1728abf523053cef0a757e3166a84c9f8c580 Mon Sep 17 00:00:00 2001 From: WaseemAbbasi22 <50428976+WaseemAbbasi22@users.noreply.github.com> Date: Thu, 22 Oct 2026 14:45:17 +0300 Subject: [PATCH 46/47] document type improvements --- lib/models/generic_attachment_model.dart | 14 +++++++++----- .../ppm_wo/activities/pm_activities_list_view.dart | 11 ++++++++++- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/lib/models/generic_attachment_model.dart b/lib/models/generic_attachment_model.dart index 981db927..1418d4c4 100644 --- a/lib/models/generic_attachment_model.dart +++ b/lib/models/generic_attachment_model.dart @@ -26,9 +26,9 @@ class GenericAttachmentModel { int? id; String? name; - String ? module; - String ? subModule; - String ? uploadedBy; + String? module; + String? subModule; + String? uploadedBy; String? createdBy; String? originalName; Lookup? documentType; @@ -163,6 +163,7 @@ class GenericAttachmentModel { documentType = json['documentType'] != null ? Lookup.fromJson(json['documentType']) : null; originalName = json['originalName']; } + GenericAttachmentModel.fromAssetInventoryJson(Map json) { id = json['id']; name = json['attachmentName']; @@ -173,7 +174,7 @@ class GenericAttachmentModel { GenericAttachmentModel.fromTrafJson(Map json) { id = json['id']; - moduleReferenceId= json['trafId']; + moduleReferenceId = json['trafId']; name = json['attachmentName']; attachmentDescription = json['attachmentDescription']; moduleReferenceId = json['trafId']; @@ -189,6 +190,7 @@ class GenericAttachmentModel { data['documentTypeId'] = documentType?.id; return data; } + Map toSparePartJson() { final Map data = {}; data['id'] = id; @@ -239,7 +241,6 @@ class GenericAttachmentModel { return data; } - Map toGasRefillJson() { final Map data = {}; data['id'] = id; @@ -305,6 +306,7 @@ class GenericAttachmentModel { data['originalName'] = originalName; return data; } + Map toAssetDeliveryJson() { final Map data = {}; data['id'] = id; @@ -314,6 +316,7 @@ class GenericAttachmentModel { data['createdBy'] = createdBy; return data; } + Map toInventoryJson() { final Map data = {}; data['id'] = id; @@ -342,6 +345,7 @@ class GenericAttachmentModel { data['attachmentURL'] = attachmentURL; return data; } + Map toTaskJson() { final Map data = {}; data['id'] = id; diff --git a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart index a4e2b18c..a8c13b19 100644 --- a/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart +++ b/lib/modules/pm_module/ppm_wo/activities/pm_activities_list_view.dart @@ -1,3 +1,5 @@ +import 'dart:developer'; + import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:test_sa/controllers/api_routes/urls.dart'; @@ -8,6 +10,7 @@ import 'package:test_sa/extensions/int_extensions.dart'; import 'package:test_sa/extensions/text_extensions.dart'; import 'package:test_sa/extensions/widget_extensions.dart'; import 'package:test_sa/models/enums/user_types.dart'; +import 'package:test_sa/models/generic_attachment_model.dart'; import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart'; import 'package:test_sa/models/plan_preventive_visit/plan_preventive_visit_model.dart'; import 'package:test_sa/models/service_request/spare_parts.dart'; @@ -185,7 +188,13 @@ class _PmActivitiesListViewState extends State { ], if (activity.activitySparePartPPMAttachments.isNotEmpty) ...[ const Divider().defaultStyle(context), - FilesList(images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList(), showAsListView: true), + FilesList( + types: activity.activitySparePartPPMAttachments! + .whereType() + .where((e) => e.documentType != null && e.documentType!.name!.isNotEmpty) + .map((toElement) => toElement.documentType!.name!) + .toList(), + images: activity.activitySparePartPPMAttachments.map((toElement) => URLs.getFileUrl(toElement.name ?? '') ?? '').toList(), showAsListView: true), ], ], ).toShadowContainer(context, showShadow: false).onPress(() { From 7c6443185dc60be9cbd3f63252b771d99420080c Mon Sep 17 00:00:00 2001 From: Sikander Saleem Date: Thu, 22 Oct 2026 16:36:17 +0300 Subject: [PATCH 47/47] v1.9.6+56 uploaded --- lib/controllers/api_routes/urls.dart | 10 +++++----- pubspec.yaml | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/controllers/api_routes/urls.dart b/lib/controllers/api_routes/urls.dart index 040259cc..0262fc1d 100644 --- a/lib/controllers/api_routes/urls.dart +++ b/lib/controllers/api_routes/urls.dart @@ -1,15 +1,15 @@ class URLs { URLs._(); - static const String appReleaseBuildNumber = "55"; + static const String appReleaseBuildNumber = "56"; - // static const host1 = "https://atomsm.hmg.com"; // production url + static const host1 = "https://atomsm.hmg.com"; // production url // static const host1 = "https://atomsmdev.hmg.com"; // local DEV url - static const host1 = "https://atomsmuat.hmg.com"; // local UAT url + // static const host1 = "https://atomsmuat.hmg.com"; // local UAT url // static final String _baseUrl = "$_host/mobile"; // host local UAT - static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis - // static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM + // static final String _baseUrl = "$_host/v2/mobile"; // new V2 apis + static final String _baseUrl = "$_host/v3/mobile"; // v3 for production CM,PM,TM // static final String _baseUrl = "$_host/v4/mobile"; // v4 for Demo module // static final String _baseUrl = "$_host/v5/mobile"; // v5 for data segregation // static final String _baseUrl = "$_host/v6/mobile"; // for asset delivery module diff --git a/pubspec.yaml b/pubspec.yaml index b2e61e4a..bfd9e7dd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 1.9.5+55 +version: 1.9.6+56 environment: sdk: ">=3.5.0 <4.0.0"