refactor: improve code readability and consistency in JobDetailsScreen

This commit is contained in:
Vaibhav Surve 2025-11-17 16:02:03 +05:30
parent 4d47ee3002
commit 605617695e

View File

@ -24,16 +24,15 @@ class JobDetailsScreen extends StatefulWidget {
class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin { class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
late final ServiceProjectDetailsController controller; late final ServiceProjectDetailsController controller;
final _titleController = TextEditingController(); final TextEditingController _titleController = TextEditingController();
final _descriptionController = TextEditingController(); final TextEditingController _descriptionController = TextEditingController();
final _startDateController = TextEditingController(); final TextEditingController _startDateController = TextEditingController();
final _dueDateController = TextEditingController(); final TextEditingController _dueDateController = TextEditingController();
final TextEditingController _tagTextController = TextEditingController();
RxList<Assignee> _selectedAssignees = <Assignee>[].obs; final RxList<Assignee> _selectedAssignees = <Assignee>[].obs;
RxList<Tag> _selectedTags = <Tag>[].obs; final RxList<Tag> _selectedTags = <Tag>[].obs;
final _tagTextController = TextEditingController(); final RxBool isEditing = false.obs;
RxBool isEditing = false.obs; // track edit/view mode
@override @override
void initState() { void initState() {
@ -49,8 +48,8 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
format: "yyyy-MM-dd"); format: "yyyy-MM-dd");
_dueDateController.text = _dueDateController.text =
DateTimeUtils.convertUtcToLocal(job.dueDate, format: "yyyy-MM-dd"); DateTimeUtils.convertUtcToLocal(job.dueDate, format: "yyyy-MM-dd");
_selectedAssignees.assignAll(job.assignees); _selectedAssignees.value = job.assignees;
_selectedTags.assignAll(job.tags); _selectedTags.value = job.tags;
} }
}); });
} }
@ -69,27 +68,23 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
final job = controller.jobDetail.value?.data; final job = controller.jobDetail.value?.data;
if (job == null) return; if (job == null) return;
final operations = <Map<String, dynamic>>[]; final List<Map<String, dynamic>> operations = [];
// Title final trimmedTitle = _titleController.text.trim();
if (_titleController.text.trim() != job.title) { if (trimmedTitle != job.title) {
operations.add({ operations
"op": "replace", .add({"op": "replace", "path": "/title", "value": trimmedTitle});
"path": "/title",
"value": _titleController.text.trim(),
});
} }
// Description final trimmedDescription = _descriptionController.text.trim();
if (_descriptionController.text.trim() != job.description) { if (trimmedDescription != job.description) {
operations.add({ operations.add({
"op": "replace", "op": "replace",
"path": "/description", "path": "/description",
"value": _descriptionController.text.trim(), "value": trimmedDescription
}); });
} }
// Dates
final startDate = DateTime.tryParse(_startDateController.text); final startDate = DateTime.tryParse(_startDateController.text);
final dueDate = DateTime.tryParse(_dueDateController.text); final dueDate = DateTime.tryParse(_dueDateController.text);
@ -97,7 +92,7 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
operations.add({ operations.add({
"op": "replace", "op": "replace",
"path": "/startDate", "path": "/startDate",
"value": startDate.toUtc().toIso8601String(), "value": startDate.toUtc().toIso8601String()
}); });
} }
@ -105,69 +100,44 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
operations.add({ operations.add({
"op": "replace", "op": "replace",
"path": "/dueDate", "path": "/dueDate",
"value": dueDate.toUtc().toIso8601String(), "value": dueDate.toUtc().toIso8601String()
}); });
} }
// Assignees final originalAssignees = job.assignees;
final originalAssignees = job.assignees ?? [];
final assigneesPayload = originalAssignees.map((a) { final assigneesPayload = originalAssignees.map((a) {
final isSelected = _selectedAssignees.any((s) => s.id == a.id); final isSelected = _selectedAssignees.any((s) => s.id == a.id);
return { return {"employeeId": a.id, "isActive": isSelected};
"employeeId": a.id,
"isActive": isSelected,
};
}).toList(); }).toList();
_selectedAssignees.forEach((s) { for (var s in _selectedAssignees) {
if (!originalAssignees.any((a) => a.id == s.id)) { if (!originalAssignees.any((a) => a.id == s.id)) {
assigneesPayload.add({ assigneesPayload.add({"employeeId": s.id, "isActive": true});
"employeeId": s.id,
"isActive": true,
});
} }
}); }
operations.add({ operations.add(
"op": "replace", {"op": "replace", "path": "/assignees", "value": assigneesPayload});
"path": "/assignees",
"value": assigneesPayload,
});
// Tags final originalTags = job.tags;
final originalTags = job.tags ?? [];
final replaceTagsPayload = originalTags.map((t) { final replaceTagsPayload = originalTags.map((t) {
final isSelected = _selectedTags.any((s) => s.id == t.id); final isSelected = _selectedTags.any((s) => s.id == t.id);
return { return {"id": t.id, "name": t.name, "isActive": isSelected};
"id": t.id,
"name": t.name,
"isActive": isSelected,
};
}).toList(); }).toList();
final addTagsPayload = _selectedTags final addTagsPayload = _selectedTags
.where((t) => t.id == "0") .where((t) => t.id == "0")
.map((t) => { .map((t) => {"name": t.name, "isActive": true})
"name": t.name,
"isActive": true,
})
.toList(); .toList();
if (replaceTagsPayload.isNotEmpty) { if (replaceTagsPayload.isNotEmpty) {
operations.add({ operations
"op": "replace", .add({"op": "replace", "path": "/tags", "value": replaceTagsPayload});
"path": "/tags",
"value": replaceTagsPayload,
});
} }
if (addTagsPayload.isNotEmpty) { if (addTagsPayload.isNotEmpty) {
operations.add({ operations.add({"op": "add", "path": "/tags", "value": addTagsPayload});
"op": "add",
"path": "/tags",
"value": addTagsPayload,
});
} }
if (operations.isEmpty) { if (operations.isEmpty) {
@ -181,7 +151,7 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
if (success) { if (success) {
Get.snackbar("Success", "Job updated successfully"); Get.snackbar("Success", "Job updated successfully");
await controller.fetchJobDetail(widget.jobId); await controller.fetchJobDetail(widget.jobId);
isEditing.value = false; // switch back to view mode isEditing.value = false;
} else { } else {
Get.snackbar("Error", "Failed to update job. Check inputs or try again."); Get.snackbar("Error", "Failed to update job. Check inputs or try again.");
} }
@ -199,225 +169,227 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
margin: const EdgeInsets.symmetric(vertical: 8), margin: const EdgeInsets.symmetric(vertical: 8),
child: Padding( child: Padding(
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Column( child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
crossAxisAlignment: CrossAxisAlignment.start, Row(children: [
children: [ Icon(titleIcon, size: 20, color: Colors.blueAccent),
Row( MySpacing.width(8),
children: [ MyText.bodyLarge(title, fontWeight: 700, fontSize: 16),
Icon(titleIcon, size: 20, color: Colors.blueAccent), ]),
MySpacing.width(8), MySpacing.height(8),
MyText.bodyLarge(title, fontWeight: 700, fontSize: 16), const Divider(),
], ...children,
), ]),
MySpacing.height(8),
const Divider(),
...children,
],
),
), ),
); );
} }
Widget _editableRow(String label, TextEditingController controller) { Widget _editableRow(String label, TextEditingController controller) {
return Obx(() => Padding( return Obx(() {
padding: const EdgeInsets.symmetric(vertical: 8), final editing = isEditing.value;
child: Column( return Padding(
crossAxisAlignment: CrossAxisAlignment.start, padding: const EdgeInsets.symmetric(vertical: 8),
children: [ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
MyText.bodySmall(label, MyText.bodySmall(label, color: Colors.grey[600], fontWeight: 600),
color: Colors.grey[600], fontWeight: 600), const SizedBox(height: 6),
const SizedBox(height: 6), editing
isEditing.value ? TextField(
? TextField( controller: controller,
controller: controller, decoration: InputDecoration(
decoration: InputDecoration( border: OutlineInputBorder(
border: OutlineInputBorder( borderRadius: BorderRadius.circular(5)),
borderRadius: BorderRadius.circular(5)), isDense: true,
isDense: true, contentPadding: const EdgeInsets.symmetric(
contentPadding: horizontal: 10, vertical: 12),
const EdgeInsets.symmetric(horizontal: 10, vertical: 12), ),
), )
) : Container(
: Container( width: double.infinity,
width: double.infinity, padding:
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14), const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.grey.shade100, color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(5), borderRadius: BorderRadius.circular(5)),
), child: Text(controller.text,
child: Text(controller.text, style: const TextStyle(fontSize: 14)), style: const TextStyle(fontSize: 14)),
), ),
], ]),
), );
)); });
} }
Widget _assigneeSelector() { Widget _dateRangePicker() {
return Obx(() => Column( return Obx(() {
crossAxisAlignment: CrossAxisAlignment.start, final editing = isEditing.value;
children: [ final startDate =
MyText.bodySmall("Assigned To", DateTime.tryParse(_startDateController.text) ?? DateTime.now();
color: Colors.grey[600], fontWeight: 600), final dueDate = DateTime.tryParse(_dueDateController.text) ??
const SizedBox(height: 8), DateTime.now().add(const Duration(days: 1));
GestureDetector( return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
onTap: isEditing.value MyText.bodySmall("Select Date Range",
? () async { color: Colors.grey[600], fontWeight: 600),
final initiallySelected = const SizedBox(height: 8),
_selectedAssignees.map<EmployeeModel>((a) { editing
return EmployeeModel( ? DateRangePickerWidget(
id: a.id, startDate: Rx<DateTime>(startDate),
employeeId: a.id, endDate: Rx<DateTime>(dueDate),
firstName: a.firstName, startLabel: "Start Date",
lastName: a.lastName, endLabel: "Due Date",
name: "${a.firstName} ${a.lastName}", onDateRangeSelected: (start, end) {
designation: a.jobRoleName ?? '', if (start != null && end != null) {
jobRole: a.jobRoleName ?? '', _startDateController.text =
jobRoleID: a.jobRoleId ?? '', start.toIso8601String().split("T").first;
email: a.email ?? '', _dueDateController.text =
phoneNumber: '', end.toIso8601String().split("T").first;
activity: 0, }
action: 0, },
); )
}).toList(); : Container(
final selected =
await showModalBottomSheet<List<EmployeeModel>>(
context: context,
isScrollControlled: true,
builder: (_) => EmployeeSelectionBottomSheet(
multipleSelection: true,
initiallySelected: initiallySelected,
),
);
if (selected != null) {
final newAssignees = selected.map<Assignee>((e) {
return Assignee(
id: e.id,
firstName: e.firstName,
lastName: e.lastName,
email: e.email ?? '',
photo: '',
jobRoleId: e.jobRoleID ?? '',
jobRoleName: e.jobRole ?? '',
);
}).toList();
_selectedAssignees.assignAll(newAssignees);
}
}
: null,
child: Container(
width: double.infinity, width: double.infinity,
padding: padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 14), const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.grey.shade100, color: Colors.grey.shade100,
border: Border.all(color: Colors.grey.shade400), borderRadius: BorderRadius.circular(5)),
borderRadius: BorderRadius.circular(5),
),
child: Text( child: Text(
_selectedAssignees.isEmpty "${_startDateController.text}${_dueDateController.text}"),
? "No Assignees" ),
: _selectedAssignees ]);
.map((e) => "${e.firstName} ${e.lastName}") });
.join(", "), }
style: const TextStyle(fontSize: 14),
Widget _assigneeInputWithChips() {
return Obx(() {
final editing = isEditing.value;
final assignees = _selectedAssignees;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (assignees.isNotEmpty)
Wrap(
spacing: 6,
children: assignees
.map(
(a) => Chip(
label: Text("${a.firstName} ${a.lastName}"),
onDeleted: editing
? () {
_selectedAssignees.remove(a);
}
: null,
),
)
.toList(),
),
const SizedBox(height: 8),
if (editing)
GestureDetector(
onTap: () async {
final initiallySelected = assignees.map<EmployeeModel>((a) {
return EmployeeModel(
id: a.id,
employeeId: a.id,
firstName: a.firstName,
lastName: a.lastName,
name: "${a.firstName} ${a.lastName}",
designation: a.jobRoleName,
jobRole: a.jobRoleName,
jobRoleID: a.jobRoleId,
email: a.email,
phoneNumber: '',
activity: 0,
action: 0,
);
}).toList();
final selected =
await showModalBottomSheet<List<EmployeeModel>>(
context: context,
isScrollControlled: true,
builder: (_) => EmployeeSelectionBottomSheet(
multipleSelection: true,
initiallySelected: initiallySelected,
),
);
if (selected != null) {
_selectedAssignees.value = selected.map((e) {
return Assignee(
id: e.id,
firstName: e.firstName,
lastName: e.lastName,
email: e.email,
photo: '',
jobRoleId: e.jobRoleID,
jobRoleName: e.jobRole,
);
}).toList();
}
},
child: Container(
height: 40,
padding: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Colors.grey.shade400),
),
alignment: Alignment.centerLeft,
child: Text(
"Tap to select assignees",
style: TextStyle(fontSize: 14, color: Colors.grey[700]),
), ),
), ),
), ),
], ],
)); );
} });
Widget _dateRangePicker() {
return Obx(() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MyText.bodySmall("Select Date Range",
color: Colors.grey[600], fontWeight: 600),
const SizedBox(height: 8),
isEditing.value
? DateRangePickerWidget(
startDate: Rx<DateTime>(
DateTime.tryParse(_startDateController.text) ??
DateTime.now()),
endDate: Rx<DateTime>(
DateTime.tryParse(_dueDateController.text) ??
DateTime.now().add(const Duration(days: 1))),
startLabel: "Start Date",
endLabel: "Due Date",
onDateRangeSelected: (start, end) {
if (start != null && end != null) {
_startDateController.text =
start.toIso8601String().split("T").first;
_dueDateController.text =
end.toIso8601String().split("T").first;
}
},
)
: Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 14),
decoration: BoxDecoration(
color: Colors.grey.shade100,
borderRadius: BorderRadius.circular(5),
),
child: Text(
"${_startDateController.text}${_dueDateController.text}"),
),
],
));
} }
Widget _tagEditor() { Widget _tagEditor() {
return Obx(() => Column( return Obx(() {
crossAxisAlignment: CrossAxisAlignment.start, final editing = isEditing.value;
children: [ final tags = _selectedTags;
MyText.bodySmall("Tags", return Column(
color: Colors.grey[600], fontWeight: 600), crossAxisAlignment: CrossAxisAlignment.start,
const SizedBox(height: 8), children: [
if (isEditing.value) Wrap(
TextField( spacing: 6,
controller: _tagTextController, children: tags
onSubmitted: (v) { .map(
final value = v.trim(); (t) => Chip(
if (value.isNotEmpty && label: Text(t.name),
!_selectedTags.any((t) => t.name == value)) { onDeleted: editing
setState(() { ? () {
_selectedTags.add(Tag(id: "0", name: value)); _selectedTags.remove(t);
}); }
} : null,
_tagTextController.clear(); ),
}, )
decoration: InputDecoration( .toList(),
hintText: "Type and press enter to add tags", ),
border: OutlineInputBorder( const SizedBox(height: 8),
borderRadius: BorderRadius.circular(5)), if (editing)
isDense: true, TextField(
contentPadding: controller: _tagTextController,
const EdgeInsets.symmetric(horizontal: 10, vertical: 12), onSubmitted: (v) {
), final value = v.trim();
if (value.isNotEmpty && !tags.any((t) => t.name == value)) {
_selectedTags.add(Tag(id: "0", name: value));
}
_tagTextController.clear();
},
decoration: InputDecoration(
hintText: "Type and press enter to add tags",
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(5)),
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
), ),
const SizedBox(height: 8),
Wrap(
spacing: 6,
children: _selectedTags
.map((t) => Chip(
label: Text(t.name),
onDeleted: isEditing.value
? () {
setState(() {
_selectedTags.remove(t);
});
}
: null,
))
.toList(),
), ),
], ],
)); );
});
} }
@override @override
@ -425,11 +397,11 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
return Scaffold( return Scaffold(
backgroundColor: const Color(0xFFF5F5F5), backgroundColor: const Color(0xFFF5F5F5),
appBar: CustomAppBar( appBar: CustomAppBar(
title: "Service Project Job Details", title: "Service Project Job Details",
onBackPressed: () => Get.back(), onBackPressed: () => Get.back()),
),
floatingActionButton: Obx(() => FloatingActionButton.extended( floatingActionButton: Obx(() => FloatingActionButton.extended(
onPressed: isEditing.value ? _editJob : () => isEditing.value = true, onPressed:
isEditing.value ? _editJob : () => isEditing.value = true,
label: Text(isEditing.value ? "Save" : "Edit"), label: Text(isEditing.value ? "Save" : "Edit"),
icon: Icon(isEditing.value ? Icons.save : Icons.edit), icon: Icon(isEditing.value ? Icons.save : Icons.edit),
)), )),
@ -463,20 +435,21 @@ class _JobDetailsScreenState extends State<JobDetailsScreen> with UIMixin {
], ],
), ),
MySpacing.height(12), MySpacing.height(12),
_assigneeSelector(), _buildSectionCard(
title: "Assignees",
titleIcon: Icons.person_outline,
children: [_assigneeInputWithChips()]),
MySpacing.height(16), MySpacing.height(16),
_buildSectionCard( _buildSectionCard(
title: "Tags", title: "Tags",
titleIcon: Icons.label_outline, titleIcon: Icons.label_outline,
children: [_tagEditor()], children: [_tagEditor()]),
),
MySpacing.height(16), MySpacing.height(16),
if (job.updateLogs.isNotEmpty) if (job.updateLogs.isNotEmpty)
_buildSectionCard( _buildSectionCard(
title: "Update Logs", title: "Update Logs",
titleIcon: Icons.history, titleIcon: Icons.history,
children: [JobTimeline(logs: job.updateLogs)], children: [JobTimeline(logs: job.updateLogs)]),
),
MySpacing.height(80), MySpacing.height(80),
], ],
), ),
@ -509,51 +482,45 @@ class JobTimeline extends StatelessWidget {
final updatedBy = final updatedBy =
"${log.updatedBy.firstName} ${log.updatedBy.lastName}"; "${log.updatedBy.firstName} ${log.updatedBy.lastName}";
final initials = final initials =
"${log.updatedBy.firstName.isNotEmpty ? log.updatedBy.firstName[0] : ''}" "${log.updatedBy.firstName.isNotEmpty ? log.updatedBy.firstName[0] : ''}${log.updatedBy.lastName.isNotEmpty ? log.updatedBy.lastName[0] : ''}";
"${log.updatedBy.lastName.isNotEmpty ? log.updatedBy.lastName[0] : ''}";
return TimelineTile( return TimelineTile(
alignment: TimelineAlign.start, alignment: TimelineAlign.start,
isFirst: index == 0, isFirst: index == 0,
isLast: index == reversedLogs.length - 1, isLast: index == reversedLogs.length - 1,
indicatorStyle: IndicatorStyle( indicatorStyle: const IndicatorStyle(
width: 16, width: 16,
height: 16, height: 16,
indicator: Container( indicator: DecoratedBox(
decoration: const BoxDecoration( decoration:
color: Colors.blue, shape: BoxShape.circle), BoxDecoration(color: Colors.blue, shape: BoxShape.circle)),
),
), ),
beforeLineStyle: LineStyle(color: Colors.grey.shade300, thickness: 2), beforeLineStyle: LineStyle(color: Colors.grey.shade300, thickness: 2),
endChild: Padding( endChild: Padding(
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(12),
child: Column( child:
crossAxisAlignment: CrossAxisAlignment.start, Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
children: [ MyText.bodyMedium("$statusName$nextStatusName",
MyText.bodyMedium("$statusName$nextStatusName", fontWeight: 600),
fontWeight: 600), if (comment.isNotEmpty) ...[
if (comment.isNotEmpty) ...[ const SizedBox(height: 8),
const SizedBox(height: 8), MyText.bodyMedium(comment),
MyText.bodyMedium(comment),
],
const SizedBox(height: 10),
Row(
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(4)),
child: MyText.bodySmall(initials, fontWeight: 600),
),
const SizedBox(width: 6),
Expanded(child: MyText.bodySmall(updatedBy)),
],
),
const SizedBox(height: 10),
], ],
), const SizedBox(height: 10),
Row(children: [
Container(
padding:
const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(4)),
child: MyText.bodySmall(initials, fontWeight: 600),
),
const SizedBox(width: 6),
Expanded(child: MyText.bodySmall(updatedBy)),
]),
const SizedBox(height: 10),
]),
), ),
); );
}, },