update and correction of create order

This commit is contained in:
José Salazar
2026-01-25 13:21:16 -05:00
parent 8f8c6ff2d2
commit bda0b441e9
15 changed files with 23283 additions and 22306 deletions

View File

@@ -118,6 +118,7 @@ class ClientCreateOrderRepositoryImpl
.startTime(_toTimestamp(start))
.endTime(_toTimestamp(normalizedEnd))
.hours(hours)
.breakType(_breakDurationFromValue(position.lunchBreak))
.totalValue(totalValue)
.execute();
}
@@ -148,6 +149,17 @@ class ClientCreateOrderRepositoryImpl
return total;
}
dc.BreakDuration _breakDurationFromValue(String value) {
switch (value) {
case 'MIN_15':
return dc.BreakDuration.MIN_15;
case 'MIN_30':
return dc.BreakDuration.MIN_30;
default:
return dc.BreakDuration.NO_BREAK;
}
}
DateTime _parseTime(DateTime date, String time) {
if (time.trim().isEmpty) {
throw Exception('Shift time is missing.');

View File

@@ -230,7 +230,7 @@ class OneTimeOrderPositionCard extends StatelessWidget {
border: Border.all(color: UiColors.border),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<int>(
child: DropdownButton<String>(
isExpanded: true,
value: position.lunchBreak,
icon: const Icon(
@@ -238,16 +238,23 @@ class OneTimeOrderPositionCard extends StatelessWidget {
size: 18,
color: UiColors.iconSecondary,
),
onChanged: (int? val) {
onChanged: (String? val) {
if (val != null) {
onUpdated(position.copyWith(lunchBreak: val));
}
},
items: <int>[0, 15, 30, 45, 60].map((int mins) {
return DropdownMenuItem<int>(
value: mins,
items: <String>['NO_BREAK', 'MIN_15', 'MIN_30'].map((
String value,
) {
final String label = switch (value) {
'NO_BREAK' => 'No Break',
'MIN_15' => '15 min',
_ => '30 min',
};
return DropdownMenuItem<String>(
value: value,
child: Text(
mins == 0 ? 'No Break' : '$mins mins',
label,
style: UiTypography.body2r.textPrimary,
),
);

View File

@@ -62,6 +62,7 @@ class ViewOrdersRepositoryImpl implements IViewOrdersRepository {
return domain.OrderItem(
id: _shiftRoleKey(shiftRole.shiftId, shiftRole.roleId),
orderId: shiftRole.shift.order.id,
title: '${shiftRole.role.name} - ${shiftRole.shift.title}',
clientName: businessName,
status: status,

View File

@@ -133,6 +133,7 @@ class ViewOrdersCubit extends Cubit<ViewOrdersState> {
filled >= order.workersNeeded ? 'filled' : order.status;
return OrderItem(
id: order.id,
orderId: order.orderId,
title: order.title,
clientName: order.clientName,
status: status,

View File

@@ -1,7 +1,10 @@
import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase;
import 'package:firebase_data_connect/firebase_data_connect.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:krow_data_connect/krow_data_connect.dart' as dc;
import 'package:krow_domain/krow_domain.dart';
/// A rich card displaying details of a client order/shift.
@@ -619,6 +622,25 @@ class _ViewOrderCardState extends State<ViewOrderCard> {
}
}
class _RoleOption {
const _RoleOption({
required this.id,
required this.name,
required this.costPerHour,
});
final String id;
final String name;
final double costPerHour;
}
class _ShiftRoleKey {
const _ShiftRoleKey({required this.shiftId, required this.roleId});
final String shiftId;
final String roleId;
}
/// A sophisticated bottom sheet for editing an existing order,
/// following the Unified Order Flow prototype and matching OneTimeOrderView.
class _OrderEditSheet extends StatefulWidget {
@@ -639,8 +661,15 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
late List<Map<String, dynamic>> _positions;
final dc.ExampleConnector _dataConnect = dc.ExampleConnector.instance;
final firebase.FirebaseAuth _firebaseAuth = firebase.FirebaseAuth.instance;
List<Vendor> _vendors = const <Vendor>[];
Vendor? _selectedVendor;
List<_RoleOption> _roles = const <_RoleOption>[];
String? _shiftId;
List<_ShiftRoleKey> _originalShiftRoles = const <_ShiftRoleKey>[];
@override
void initState() {
@@ -652,47 +681,19 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
_positions = <Map<String, dynamic>>[
<String, dynamic>{
'role': widget.order.title,
'shiftId': null,
'roleId': '',
'roleName': '',
'originalRoleId': null,
'count': widget.order.workersNeeded,
'start_time': widget.order.startTime,
'end_time': widget.order.endTime,
'lunch_break': 0,
'lunch_break': 'NO_BREAK',
'location': null,
},
];
// Mock vendors initialization
_vendors = const <Vendor>[
Vendor(
id: 'v1',
name: 'Elite Staffing',
rates: <String, double>{
'Server': 25.0,
'Bartender': 30.0,
'Cook': 28.0,
'Busser': 18.0,
'Host': 20.0,
'Barista': 22.0,
'Dishwasher': 17.0,
'Event Staff': 19.0,
},
),
Vendor(
id: 'v2',
name: 'Premier Workforce',
rates: <String, double>{
'Server': 22.0,
'Bartender': 28.0,
'Cook': 25.0,
'Busser': 16.0,
'Host': 18.0,
'Barista': 20.0,
'Dishwasher': 15.0,
'Event Staff': 18.0,
},
),
];
_selectedVendor = _vendors.first;
_loadOrderDetails();
}
@override
@@ -702,16 +703,396 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
super.dispose();
}
Future<void> _loadOrderDetails() async {
final String? businessId =
dc.ClientSessionStore.instance.session?.business?.id;
if (businessId == null || businessId.isEmpty) {
await _firebaseAuth.signOut();
return;
}
if (widget.order.orderId.isEmpty) {
return;
}
try {
final QueryResult<
dc.ListShiftRolesByBusinessAndOrderData,
dc.ListShiftRolesByBusinessAndOrderVariables> result = await _dataConnect
.listShiftRolesByBusinessAndOrder(
businessId: businessId,
orderId: widget.order.orderId,
)
.execute();
final List<dc.ListShiftRolesByBusinessAndOrderShiftRoles> shiftRoles =
result.data.shiftRoles;
if (shiftRoles.isEmpty) {
return;
}
final dc.ListShiftRolesByBusinessAndOrderShiftRolesShift firstShift =
shiftRoles.first.shift;
final DateTime? orderDate = firstShift.order.date?.toDateTime();
final String dateText = orderDate == null
? widget.order.date
: DateFormat('yyyy-MM-dd').format(orderDate);
final String location = firstShift.order.location ??
firstShift.locationAddress ??
firstShift.location ??
widget.order.locationAddress;
_dateController.text = dateText;
_globalLocationController.text = location;
_shiftId = shiftRoles.first.shiftId;
final List<Map<String, dynamic>> positions =
shiftRoles.map((dc.ListShiftRolesByBusinessAndOrderShiftRoles role) {
return <String, dynamic>{
'shiftId': role.shiftId,
'roleId': role.roleId,
'roleName': role.role.name,
'originalRoleId': role.roleId,
'count': role.count,
'start_time': _formatTimeForField(role.startTime),
'end_time': _formatTimeForField(role.endTime),
'lunch_break': _breakValueFromDuration(role.breakType),
'location': null,
};
}).toList();
if (positions.isEmpty) {
positions.add(_emptyPosition());
}
final List<_ShiftRoleKey> originalShiftRoles =
shiftRoles
.map(
(dc.ListShiftRolesByBusinessAndOrderShiftRoles role) =>
_ShiftRoleKey(shiftId: role.shiftId, roleId: role.roleId),
)
.toList();
await _loadVendorsAndSelect(firstShift.order.vendorId);
if (mounted) {
setState(() {
_positions = positions;
_originalShiftRoles = originalShiftRoles;
});
}
} catch (_) {
// Keep current state on failure.
}
}
Future<void> _loadVendorsAndSelect(String? selectedVendorId) async {
try {
final QueryResult<dc.ListVendorsData, void> result =
await _dataConnect.listVendors().execute();
final List<Vendor> vendors = result.data.vendors
.map(
(dc.ListVendorsVendors vendor) => Vendor(
id: vendor.id,
name: vendor.companyName,
rates: const <String, double>{},
),
)
.toList();
Vendor? selectedVendor;
if (selectedVendorId != null && selectedVendorId.isNotEmpty) {
for (final Vendor vendor in vendors) {
if (vendor.id == selectedVendorId) {
selectedVendor = vendor;
break;
}
}
}
selectedVendor ??= vendors.isNotEmpty ? vendors.first : null;
if (mounted) {
setState(() {
_vendors = vendors;
_selectedVendor = selectedVendor;
});
}
if (selectedVendor != null) {
await _loadRolesForVendor(selectedVendor.id);
}
} catch (_) {
if (mounted) {
setState(() {
_vendors = const <Vendor>[];
_selectedVendor = null;
_roles = const <_RoleOption>[];
});
}
}
}
Future<void> _loadRolesForVendor(String vendorId) async {
try {
final QueryResult<dc.ListRolesByVendorIdData, dc.ListRolesByVendorIdVariables>
result = await _dataConnect
.listRolesByVendorId(vendorId: vendorId)
.execute();
final List<_RoleOption> roles = result.data.roles
.map(
(dc.ListRolesByVendorIdRoles role) => _RoleOption(
id: role.id,
name: role.name,
costPerHour: role.costPerHour,
),
)
.toList();
if (mounted) {
setState(() => _roles = roles);
}
} catch (_) {
if (mounted) {
setState(() => _roles = const <_RoleOption>[]);
}
}
}
Map<String, dynamic> _emptyPosition() {
return <String, dynamic>{
'shiftId': _shiftId,
'roleId': '',
'roleName': '',
'originalRoleId': null,
'count': 1,
'start_time': '09:00',
'end_time': '17:00',
'lunch_break': 'NO_BREAK',
'location': null,
};
}
String _formatTimeForField(Timestamp? value) {
if (value == null) return '';
try {
return DateFormat('HH:mm').format(value.toDateTime());
} catch (_) {
return '';
}
}
String _breakValueFromDuration(dc.EnumValue<dc.BreakDuration>? breakType) {
final dc.BreakDuration? value =
breakType is dc.Known<dc.BreakDuration> ? breakType.value : null;
switch (value) {
case dc.BreakDuration.MIN_15:
return 'MIN_15';
case dc.BreakDuration.MIN_30:
return 'MIN_30';
case dc.BreakDuration.NO_BREAK:
case null:
return 'NO_BREAK';
}
}
dc.BreakDuration _breakDurationFromValue(String value) {
switch (value) {
case 'MIN_15':
return dc.BreakDuration.MIN_15;
case 'MIN_30':
return dc.BreakDuration.MIN_30;
default:
return dc.BreakDuration.NO_BREAK;
}
}
_RoleOption? _roleById(String roleId) {
for (final _RoleOption role in _roles) {
if (role.id == roleId) {
return role;
}
}
return null;
}
double _rateForRole(String roleId) {
return _roleById(roleId)?.costPerHour ?? 0;
}
DateTime _parseDate(String value) {
try {
return DateFormat('yyyy-MM-dd').parse(value);
} catch (_) {
return DateTime.now();
}
}
DateTime _parseTime(DateTime date, String time) {
if (time.trim().isEmpty) {
throw Exception('Shift time is missing.');
}
DateTime parsed;
try {
parsed = DateFormat.Hm().parse(time);
} catch (_) {
parsed = DateFormat.jm().parse(time);
}
return DateTime(
date.year,
date.month,
date.day,
parsed.hour,
parsed.minute,
);
}
Timestamp _toTimestamp(DateTime date) {
final int millis = date.millisecondsSinceEpoch;
final int seconds = millis ~/ 1000;
final int nanos = (millis % 1000) * 1000000;
return Timestamp(nanos, seconds);
}
double _calculateTotalCost() {
double total = 0;
for (final Map<String, dynamic> pos in _positions) {
final String roleId = pos['roleId']?.toString() ?? '';
if (roleId.isEmpty) {
continue;
}
final DateTime date = _parseDate(_dateController.text);
final DateTime start = _parseTime(date, pos['start_time'].toString());
final DateTime end = _parseTime(date, pos['end_time'].toString());
final DateTime normalizedEnd =
end.isBefore(start) ? end.add(const Duration(days: 1)) : end;
final double hours = normalizedEnd.difference(start).inMinutes / 60.0;
final double rate = _rateForRole(roleId);
final int count = pos['count'] as int;
total += rate * hours * count;
}
return total;
}
Future<void> _saveOrderChanges() async {
if (_shiftId == null || _shiftId!.isEmpty) {
return;
}
final String? businessId =
dc.ClientSessionStore.instance.session?.business?.id;
if (businessId == null || businessId.isEmpty) {
await _firebaseAuth.signOut();
return;
}
final DateTime orderDate = _parseDate(_dateController.text);
final String location = _globalLocationController.text;
int totalWorkers = 0;
double shiftCost = 0;
final List<_ShiftRoleKey> remainingOriginal =
List<_ShiftRoleKey>.from(_originalShiftRoles);
for (final Map<String, dynamic> pos in _positions) {
final String roleId = pos['roleId']?.toString() ?? '';
if (roleId.isEmpty) {
continue;
}
final String shiftId = pos['shiftId']?.toString() ?? _shiftId!;
final int count = pos['count'] as int;
final DateTime start = _parseTime(orderDate, pos['start_time'].toString());
final DateTime end = _parseTime(orderDate, pos['end_time'].toString());
final DateTime normalizedEnd =
end.isBefore(start) ? end.add(const Duration(days: 1)) : end;
final double hours = normalizedEnd.difference(start).inMinutes / 60.0;
final double rate = _rateForRole(roleId);
final double totalValue = rate * hours * count;
final String lunchBreak = pos['lunch_break'] as String;
totalWorkers += count;
shiftCost += totalValue;
final String? originalRoleId = pos['originalRoleId']?.toString();
remainingOriginal.removeWhere(
(_ShiftRoleKey key) =>
key.shiftId == shiftId && key.roleId == originalRoleId,
);
if (originalRoleId != null && originalRoleId.isNotEmpty) {
if (originalRoleId != roleId) {
await _dataConnect
.deleteShiftRole(shiftId: shiftId, roleId: originalRoleId)
.execute();
await _dataConnect
.createShiftRole(
shiftId: shiftId,
roleId: roleId,
count: count,
)
.startTime(_toTimestamp(start))
.endTime(_toTimestamp(normalizedEnd))
.hours(hours)
.breakType(_breakDurationFromValue(lunchBreak))
.totalValue(totalValue)
.execute();
} else {
await _dataConnect
.updateShiftRole(shiftId: shiftId, roleId: roleId)
.count(count)
.startTime(_toTimestamp(start))
.endTime(_toTimestamp(normalizedEnd))
.hours(hours)
.breakType(_breakDurationFromValue(lunchBreak))
.totalValue(totalValue)
.execute();
}
} else {
await _dataConnect
.createShiftRole(
shiftId: shiftId,
roleId: roleId,
count: count,
)
.startTime(_toTimestamp(start))
.endTime(_toTimestamp(normalizedEnd))
.hours(hours)
.breakType(_breakDurationFromValue(lunchBreak))
.totalValue(totalValue)
.execute();
}
}
for (final _ShiftRoleKey key in remainingOriginal) {
await _dataConnect
.deleteShiftRole(shiftId: key.shiftId, roleId: key.roleId)
.execute();
}
await _dataConnect
.updateOrder(id: widget.order.orderId)
.vendorId(_selectedVendor?.id)
.location(location)
.date(_toTimestamp(orderDate))
.execute();
await _dataConnect
.updateShift(id: _shiftId!)
.title('shift 1 ${DateFormat('yyyy-MM-dd').format(orderDate)}')
.date(_toTimestamp(orderDate))
.location(location)
.locationAddress(location)
.workersNeeded(totalWorkers)
.cost(shiftCost)
.durationDays(1)
.execute();
}
void _addPosition() {
setState(() {
_positions.add(<String, dynamic>{
'role': '',
'count': 1,
'start_time': '09:00',
'end_time': '17:00',
'lunch_break': 0,
'location': null,
});
_positions.add(_emptyPosition());
});
}
@@ -725,10 +1106,6 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
setState(() => _positions[index][key] = value);
}
double _calculateTotalCost() {
return widget.order.totalValue;
}
@override
Widget build(BuildContext context) {
if (_isLoading && _showReview) {
@@ -781,6 +1158,7 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
onChanged: (Vendor? vendor) {
if (vendor != null) {
setState(() => _selectedVendor = vendor);
_loadRolesForVendor(vendor.id);
}
},
items: _vendors.map((Vendor vendor) {
@@ -956,30 +1334,32 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
_buildDropdownField(
hint: 'Select role',
value: pos['role'],
value: pos['roleId'],
items: <String>[
...(_selectedVendor?.rates.keys.toList() ??
<String>[
'Server',
'Bartender',
'Cook',
'Busser',
'Host',
'Barista',
'Dishwasher',
'Event Staff',
]),
if (pos['role'] != null &&
pos['role'].toString().isNotEmpty &&
!(_selectedVendor?.rates.keys.contains(pos['role']) ?? false))
pos['role'].toString(),
..._roles.map((_RoleOption role) => role.id),
if (pos['roleId'] != null &&
pos['roleId'].toString().isNotEmpty &&
!_roles.any(
(_RoleOption role) => role.id == pos['roleId'].toString(),
))
pos['roleId'].toString(),
],
itemBuilder: (dynamic role) {
final double? rate = _selectedVendor?.rates[role];
if (rate == null) return role.toString();
return '$role - \$${rate.toStringAsFixed(0)}/hr';
itemBuilder: (dynamic roleId) {
final _RoleOption? role = _roleById(roleId.toString());
if (role == null) {
final String fallback = pos['roleName']?.toString() ?? '';
return fallback.isEmpty ? roleId.toString() : fallback;
}
return '${role.name} - \$${role.costPerHour.toStringAsFixed(0)}/hr';
},
onChanged: (dynamic val) {
final String roleId = val?.toString() ?? '';
final _RoleOption? role = _roleById(roleId);
setState(() {
_positions[index]['roleId'] = roleId;
_positions[index]['roleName'] = role?.name ?? '';
});
},
onChanged: (dynamic val) => _updatePosition(index, 'role', val),
),
const SizedBox(height: UiConstants.space3),
@@ -1117,10 +1497,16 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
_buildDropdownField(
hint: 'No break',
value: pos['lunch_break'],
items: <int>[0, 15, 30, 45, 60],
items: <String>['NO_BREAK', 'MIN_15', 'MIN_30'],
itemBuilder: (dynamic val) {
if (val == 0) return 'No break';
return '$val min';
switch (val.toString()) {
case 'MIN_15':
return '15 min';
case 'MIN_30':
return '30 min';
default:
return 'No break';
}
},
onChanged: (dynamic val) =>
_updatePosition(index, 'lunch_break', val),
@@ -1379,7 +1765,7 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
text: 'Confirm & Save',
onPressed: () async {
setState(() => _isLoading = true);
await Future<void>.delayed(const Duration(seconds: 1));
await _saveOrderChanges();
if (mounted) Navigator.pop(context);
},
),
@@ -1413,8 +1799,9 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
}
Widget _buildReviewPositionCard(Map<String, dynamic> pos) {
final double rate =
_selectedVendor?.rates[pos['role']] ?? widget.order.hourlyRate;
final String roleId = pos['roleId']?.toString() ?? '';
final _RoleOption? role = _roleById(roleId);
final double rate = role?.costPerHour ?? 0;
return Container(
margin: const EdgeInsets.only(bottom: 12),
@@ -1433,9 +1820,9 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
pos['role'].toString().isEmpty
(role?.name ?? pos['roleName']?.toString() ?? '').isEmpty
? 'Position'
: pos['role'].toString(),
: (role?.name ?? pos['roleName']?.toString() ?? ''),
style: UiTypography.body2b.textPrimary,
),
Text(