Session expiry, arrival geofence guard, multi-destination stops
Three fixes found by running the app on a real handset against production. 1. An expired token left the app looking signed in and unable to work. MilerApi.onUnauthorized was declared and called on every 401 but never assigned, so the token was dropped and nothing else happened: the profile stayed on disk, logged_out stayed false, and the rider saw his own name over a dashboard whose every call returned 401. He reads that as "no work today". The teardown now lives in endSession() and both ways out of a session — the Log out button and the 401 path — use it. 2. Arrived was written locally even when the rider was not there. updateArrivedStatus answers false for three different things and the caller treated all of them as "the write did not land", which is only true of one. A geofence refusal and a server refusal now stop the rung and hand back the reason; a dead network still advances, as it should. 3. A multi-destination customer pickup collapsed onto one stop. GET /miler/bookings returns a row per destination once collected, all with the same bookingid and reference. Every local store keys on that id, so the accepted store deduped two of three drops away and their consignment ids were unrecoverable. orderid is now the stop key; bookingreference stays the booking's name. Cards show "Stop 2 of 3" and the receiver's own name and number rather than the sender's. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EqVJPB9B4QuieZnBAAKgYQ
This commit is contained in:
@@ -136,7 +136,6 @@ class PickupCard extends StatelessWidget {
|
||||
], 'Address not available');
|
||||
final String orderId = _val(['orderid']);
|
||||
final String notes = _val(['notes', 'Notes']);
|
||||
final String phone = _val(['pickupcontactno']);
|
||||
|
||||
final int deliverQty = deliveryParcelCount(item);
|
||||
final int collectQty = pickupParcelCount(item);
|
||||
@@ -157,15 +156,54 @@ class PickupCard extends StatelessWidget {
|
||||
// The receiver names the far end whenever the rider is carrying it there —
|
||||
// whether that is a milk round (line-level) or a hyperlocal parcel the
|
||||
// backend routed direct (per-order).
|
||||
// Asked of the ROW first. On a meal tenant this static answered true for
|
||||
// every card on the screen, so a CX customer pickup sitting next to a
|
||||
// kitchen load was drawn as though the rider were already carrying it to a
|
||||
// receiver. [WorkPolicy] reads the row's own `next_action` /
|
||||
// `pickup_source_type` and only falls back to the line where the row is
|
||||
// silent — which keeps every existing payload rendering exactly as it does
|
||||
// today.
|
||||
final bool carryingToCustomer =
|
||||
ServiceProfile.active.deliversToCustomer || leg.isCustomer;
|
||||
WorkPolicy.deliversToCustomer(item) || leg.isCustomer;
|
||||
final bool pickupIsSource = carryingToCustomer && source.isNotEmpty;
|
||||
final String pickupName = pickupIsSource ? source : customer;
|
||||
final String dropAddress = _val(['dropaddress', 'DropAddress']);
|
||||
final String dropName = pickupIsSource
|
||||
// ── Who is actually at the far end ──
|
||||
//
|
||||
// `pickupcustomer` is the booking's customer, which on a parcel booking is
|
||||
// the **sender** — the person the rider collected FROM. Using it to name the
|
||||
// drop put the sender's name over the receiver's door, and on a
|
||||
// multi-destination pickup it put the same name over all three of them.
|
||||
// The receiver is carried per destination and is the honest answer whenever
|
||||
// the payload has one.
|
||||
final String recipient = _val(['recipientname']);
|
||||
final String dropName = recipient.isNotEmpty
|
||||
? recipient
|
||||
: pickupIsSource
|
||||
? customer
|
||||
: (dropAddress.isEmpty ? '' : 'Collection centre');
|
||||
|
||||
// ── The Call button has to dial the door he is standing at ──
|
||||
//
|
||||
// `pickupcontactno` is the booking's customer — the SENDER — and it was
|
||||
// what this button dialled on every card, delivery legs included. So a
|
||||
// rider at the receiver's gate pressed Call and rang the man he had
|
||||
// collected from that morning, in another city; on a three-drop pickup he
|
||||
// rang him at all three gates. The receiver's own number is carried per
|
||||
// destination and is the right one to ring whenever the rider is on his way
|
||||
// to that receiver — the same test the name above uses, so the card cannot
|
||||
// show one person and phone another.
|
||||
final String recipientPhone = _val(['recipientphone']);
|
||||
final String phone = (recipient.isNotEmpty && recipientPhone.isNotEmpty)
|
||||
? recipientPhone
|
||||
: _val(['pickupcontactno']);
|
||||
|
||||
/// `Stop 2 of 3` on a customer pickup with several doors, `''` otherwise.
|
||||
/// Sits with the leg eyebrow because it answers the same question — what
|
||||
/// kind of stop is this — and because three cards that differ only in their
|
||||
/// address are three chances to deliver the wrong bag.
|
||||
final String stopLabel = MilkRun.stopLabel(item);
|
||||
|
||||
/// True once the rider is carrying it: the drop becomes the destination and
|
||||
/// takes the top of the card.
|
||||
// ── The immediate destination leads; never a hub leg's receiver ──
|
||||
@@ -179,6 +217,46 @@ class PickupCard extends StatelessWidget {
|
||||
(pickupIsSource || leg.isCustomer) &&
|
||||
(dropName.isNotEmpty || dropAddress.isNotEmpty);
|
||||
|
||||
// ── On a base leg the BASE leads ──
|
||||
//
|
||||
// The card was right to refuse the receiver — he is in another district and
|
||||
// leading with him is the navigation mistake the rule above exists to
|
||||
// prevent. But refusing the receiver only left `pickupName`, so a handover
|
||||
// card read:
|
||||
//
|
||||
// BASE HANDOVER
|
||||
// Anitha R
|
||||
// Gandhipuram
|
||||
//
|
||||
// …the customer he collected from an hour ago, under a heading telling him
|
||||
// to go to a base. The place he is actually going appeared nowhere on the
|
||||
// card and only on the sheet's slider, after he had already set off. On a
|
||||
// round with two bases that is a parcel left in the wrong building.
|
||||
//
|
||||
// `next_hub` rides on the row (the backend sends all six fields), so the
|
||||
// destination is known here. A base with no coordinates still leads with
|
||||
// its name — it is a caption rather than a destination, and the fence
|
||||
// refuses the handover anyway with a sentence pointing at the office.
|
||||
final HandoverHub? handoverBase = leg.isHub
|
||||
? (HandoverHub.from(item['next_hub'] ?? item['nexthub']) ??
|
||||
PickupLocations.baseFor(
|
||||
item['next_hub_id'] ?? item['nexthubid'] ?? item['hubid'],
|
||||
))
|
||||
: null;
|
||||
final bool baseLeads = handoverBase != null;
|
||||
|
||||
/// What the card is headed with, in one place so the name and the address
|
||||
/// below it can never describe two different places.
|
||||
final String headlineName = baseLeads
|
||||
? handoverBase.name
|
||||
: (dropLeads ? dropName : pickupName);
|
||||
final String headlineAddress = baseLeads
|
||||
? [
|
||||
handoverBase.address,
|
||||
handoverBase.pincode,
|
||||
].where((v) => v.trim().isNotEmpty).join(', ')
|
||||
: '';
|
||||
|
||||
// ── No accent stripe any more ──
|
||||
//
|
||||
// The card carried a 4px coloured bar down its left edge, on the argument
|
||||
@@ -261,9 +339,15 @@ class PickupCard extends StatelessWidget {
|
||||
// has to say which before the rider reads the place.
|
||||
// Drawn only once the parcel is actually his; an
|
||||
// uncollected stop has no leg yet.
|
||||
if (leg.leg.eyebrow.isNotEmpty) ...[
|
||||
if (leg.leg.eyebrow.isNotEmpty ||
|
||||
stopLabel.isNotEmpty) ...[
|
||||
Text(
|
||||
leg.leg.eyebrow,
|
||||
[
|
||||
if (leg.leg.eyebrow.isNotEmpty)
|
||||
leg.leg.eyebrow,
|
||||
if (stopLabel.isNotEmpty)
|
||||
stopLabel.toUpperCase(),
|
||||
].join(' · '),
|
||||
style: TextStyle(
|
||||
fontSize: 10.sp,
|
||||
fontWeight: FontWeight.w800,
|
||||
@@ -279,9 +363,7 @@ class PickupCard extends StatelessWidget {
|
||||
SizedBox(height: 3.h),
|
||||
],
|
||||
Text(
|
||||
(dropLeads ? dropName : pickupName).isEmpty
|
||||
? 'Not named'
|
||||
: (dropLeads ? dropName : pickupName),
|
||||
headlineName.isEmpty ? 'Not named' : headlineName,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
@@ -312,6 +394,17 @@ class PickupCard extends StatelessWidget {
|
||||
// lost — see [areaOf].
|
||||
Text(
|
||||
() {
|
||||
// A base is read at a gate, so it gets its street
|
||||
// and pincode rather than the locality summary the
|
||||
// other legs use — "Peelamedu" is not enough to
|
||||
// find a loading bay by.
|
||||
if (baseLeads) {
|
||||
// Empty rather than repeating the name: a base
|
||||
// with no address on the row has nothing more
|
||||
// to say here, and printing "Salem Base" twice
|
||||
// reads as a rendering fault.
|
||||
return headlineAddress;
|
||||
}
|
||||
final full = dropLeads
|
||||
? (dropAddress.isEmpty
|
||||
? address
|
||||
@@ -1560,7 +1653,7 @@ String _destinationName(Map<String, dynamic> item) {
|
||||
String _destinationAddress(Map<String, dynamic> item) {
|
||||
final area = areaOf(
|
||||
item,
|
||||
preferDrop: ServiceProfile.active.deliversToCustomer,
|
||||
preferDrop: WorkPolicy.deliversToCustomer(item),
|
||||
);
|
||||
if (area.isNotEmpty) return area;
|
||||
|
||||
@@ -1569,6 +1662,6 @@ String _destinationAddress(Map<String, dynamic> item) {
|
||||
final drop = (item['dropaddress'] ?? item['DropAddress'] ?? '')
|
||||
.toString()
|
||||
.trim();
|
||||
if (ServiceProfile.active.deliversToCustomer && drop.isNotEmpty) return drop;
|
||||
if (WorkPolicy.deliversToCustomer(item) && drop.isNotEmpty) return drop;
|
||||
return (item['pickupaddress'] ?? '').toString().trim();
|
||||
}
|
||||
|
||||
@@ -36,6 +36,15 @@ enum DeliveryOutcome {
|
||||
|
||||
/// It is not going to happen. `POST /miler/bookings/:id/cancel`.
|
||||
cancelled,
|
||||
|
||||
/// Handed in at a base, ending this rider's custody.
|
||||
/// `POST /miler/consignments/:id/inward-at-hub` — see [handOverAtHub].
|
||||
///
|
||||
/// Not a kind of [delivered]. A base handover has no receiver, no proof
|
||||
/// photo, no OTP and no COD, and it must never reach `deliver` — that route
|
||||
/// moves the consignment to `Out_for_Delivery` against a receiver in another
|
||||
/// district, which is a state the handset cannot undo.
|
||||
handedOver,
|
||||
}
|
||||
|
||||
extension DeliveryOutcomeX on DeliveryOutcome {
|
||||
@@ -43,6 +52,7 @@ extension DeliveryOutcomeX on DeliveryOutcome {
|
||||
DeliveryOutcome.delivered => 'Delivered',
|
||||
DeliveryOutcome.skipped => 'Skip',
|
||||
DeliveryOutcome.cancelled => 'Cancelled',
|
||||
DeliveryOutcome.handedOver => 'Handed over',
|
||||
};
|
||||
|
||||
IconData get icon => switch (this) {
|
||||
@@ -54,12 +64,15 @@ extension DeliveryOutcomeX on DeliveryOutcome {
|
||||
// skip-reason sheet's "Delivery paused" row already wears.
|
||||
DeliveryOutcome.skipped => LucideIcons.clock,
|
||||
DeliveryOutcome.cancelled => LucideIcons.circleX,
|
||||
// A building, not a tick: the parcel is not finished, it has changed hands.
|
||||
DeliveryOutcome.handedOver => LucideIcons.building2,
|
||||
};
|
||||
|
||||
Color get colour => switch (this) {
|
||||
DeliveryOutcome.delivered => ColorConstants.acceptGreen,
|
||||
DeliveryOutcome.skipped => ColorConstants.warning,
|
||||
DeliveryOutcome.cancelled => ColorConstants.errorRed,
|
||||
DeliveryOutcome.handedOver => ColorConstants.acceptGreen,
|
||||
};
|
||||
|
||||
/// What Activity will show once the round is over.
|
||||
@@ -67,6 +80,7 @@ extension DeliveryOutcomeX on DeliveryOutcome {
|
||||
DeliveryOutcome.delivered => 'Delivered',
|
||||
DeliveryOutcome.skipped => 'Skipped',
|
||||
DeliveryOutcome.cancelled => 'Cancelled',
|
||||
DeliveryOutcome.handedOver => 'Handed over',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -583,6 +597,14 @@ Future<Map<String, dynamic>?> _closeDelivery(
|
||||
// reportable from `Collected_By_Miler` as well as `Out_for_Delivery` — a
|
||||
// customer who is not home is not home whether or not the rider remembered
|
||||
// to press Start round. See [ConsignmentStateX.canSkip].
|
||||
// ── A handover is deliberately NOT gated here ──
|
||||
//
|
||||
// [DeliverGate] answers the question "may this be *delivered*", and a
|
||||
// base-routed parcel is `Created` — which it reads as `awaitingInward` and
|
||||
// refuses with "this parcel hasn't been released for delivery yet". Correct
|
||||
// for a delivery, exactly wrong for the rung that performs the inward.
|
||||
// `inward-at-hub` is the server's own judge of its preconditions and answers
|
||||
// `INVALID_STATE` when they are not met.
|
||||
final gated =
|
||||
outcome == DeliveryOutcome.delivered ||
|
||||
outcome == DeliveryOutcome.skipped;
|
||||
@@ -820,6 +842,15 @@ Future<Map<String, dynamic>?> _closeDelivery(
|
||||
notes: notes,
|
||||
);
|
||||
|
||||
case DeliveryOutcome.handedOver:
|
||||
// The fence, the consignment lookup and the `inward-at-hub` write all
|
||||
// live in [handOverAtHub] — this is the one close path, so the record
|
||||
// that gets filed is the same shape whichever rung produced it.
|
||||
ok = await handOverAtHub(stop);
|
||||
if (!ok && lastHandoverFailure != null && context.mounted) {
|
||||
AppFeedback.error(context, lastHandoverFailure!);
|
||||
}
|
||||
|
||||
case DeliveryOutcome.skipped:
|
||||
// ── Straight to the consignment route ──
|
||||
//
|
||||
@@ -1050,3 +1081,142 @@ Future<Map<String, dynamic>?> _closeDelivery(
|
||||
'notes': notes,
|
||||
};
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// THE BASE HANDOVER — the leg the rider could not finish
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/// Why the last [handOverAtHub] refused, in the rider's words. Null on success.
|
||||
String? lastHandoverFailure;
|
||||
|
||||
/// The base this stop must be handed in at, or null when it is not a base leg.
|
||||
///
|
||||
/// Two sources, in order. `next_hub` rides on the row itself (request 25) and
|
||||
/// is the authoritative one. [PickupLocations.baseFor] is the fallback for a
|
||||
/// row that names a hub id without expanding it — a shape older payloads use.
|
||||
HandoverHub? handoverBaseFor(Map<String, dynamic> stop) {
|
||||
final fromRow = HandoverHub.from(stop['next_hub'] ?? stop['nexthub']);
|
||||
if (fromRow != null) return fromRow;
|
||||
return PickupLocations.baseFor(
|
||||
stop['next_hub_id'] ?? stop['nexthubid'] ?? stop['hubid'],
|
||||
);
|
||||
}
|
||||
|
||||
/// Hands a base-routed consignment in, ending this rider's custody of it.
|
||||
///
|
||||
/// ── The leg that existed everywhere except the app ──
|
||||
///
|
||||
/// `MilerApi.inwardAtHub` and `MilerLifecycle.inwardAtHub` were both written,
|
||||
/// documented and covered by `hub_handover_contract_test.dart`. Neither had a
|
||||
/// single call site. So with `MILER_HUB_HANDOVER_ENABLED` on server-side, a
|
||||
/// Gandhipuram → Chennai parcel arrived on Deliveries as [NextLeg.hub],
|
||||
/// [releaseForDelivery] correctly refused to start a customer round for it —
|
||||
/// telling the rider "hand it over at base" — and there was no control in the
|
||||
/// app that could record him doing so. The parcel sat in his queue until hub
|
||||
/// staff inwarded it from the console, and the assignment closed against
|
||||
/// nobody, so the job reported zero distance and zero value on his earnings.
|
||||
///
|
||||
/// ── Correct in both positions of the server flag ──
|
||||
///
|
||||
/// This never asks which way the flag is set, because the app must not mirror
|
||||
/// it. With the flag **off**, `pickup-complete` inwards the parcel itself and
|
||||
/// the row comes back `Inwarded_at_Hub` / `handed_to_hub` — [NextLeg.closed] —
|
||||
/// so this function is never reached and no control is drawn. With it **on**,
|
||||
/// the row is `Created` / `inward_at_hub` — [NextLeg.hub] — and this is the
|
||||
/// rung that finishes it. The leg is read from the row, every time.
|
||||
///
|
||||
/// ── Fenced at the base, like every other presence claim ──
|
||||
///
|
||||
/// 100 m, against the base's own coordinates. A base with no coordinates is
|
||||
/// refused rather than waved through, for the same reason a customer stop with
|
||||
/// no pin is: nobody can say afterwards where the rider was standing.
|
||||
///
|
||||
/// Idempotent twice over — the shared `Idempotency-Key` covers a retry after a
|
||||
/// dropped response, and a parcel already inwarded answers 200 with
|
||||
/// `already_inwarded: true`, which [MilerLifecycle.inwardAtHub] reads as the
|
||||
/// success it is. A rider pressing again on bad signal at a loading bay is
|
||||
/// confirmed, not refused.
|
||||
Future<bool> handOverAtHub(Map<String, dynamic> stop) async {
|
||||
lastHandoverFailure = null;
|
||||
|
||||
final orderId = MilkRun.idOf(stop);
|
||||
final leg = NextLegResolver.resolve(
|
||||
stop,
|
||||
pivotAction: (await getPivotNextActions())[orderId] ?? '',
|
||||
);
|
||||
if (!leg.isHub) {
|
||||
// Not a refusal the rider caused — the row says this parcel is not going to
|
||||
// a base. Saying so beats posting a handover the server will reject.
|
||||
lastHandoverFailure =
|
||||
'This parcel is not going to a base. Check the stop and try again.';
|
||||
debugPrint('[HANDOVER] $orderId is not a base leg — $leg');
|
||||
return false;
|
||||
}
|
||||
|
||||
final base = handoverBaseFor(stop);
|
||||
|
||||
// ── The fence, before anything else is spent ──
|
||||
//
|
||||
// A base with no coordinates lands on [GeofenceOutcome.noTarget] and is
|
||||
// refused with a sentence pointing at the office, which is the only party who
|
||||
// can add the missing pin.
|
||||
final decision = await Geofence.check(
|
||||
targetLat: base?.latitude,
|
||||
targetLng: base?.longitude,
|
||||
action: 'Handed over',
|
||||
);
|
||||
if (!decision.allowed) {
|
||||
lastHandoverFailure = decision.reason;
|
||||
debugPrint('[HANDOVER] $orderId refused by the fence — $decision');
|
||||
return false;
|
||||
}
|
||||
|
||||
final consignmentId = await resolveConsignmentId(stop);
|
||||
if (consignmentId.isEmpty) {
|
||||
lastHandoverFailure =
|
||||
'This stop has no shipment reference yet, so it cannot be handed over. '
|
||||
'Ask your office to check it — pressing again will not help.';
|
||||
debugPrint('[HANDOVER] no consignment id for $orderId');
|
||||
return false;
|
||||
}
|
||||
|
||||
debugPrint(
|
||||
'[TRACE][HANDOVER] consignment=$consignmentId base=${base?.id} '
|
||||
'POST /miler/consignments/$consignmentId/inward-at-hub — calling',
|
||||
);
|
||||
final res = await MilerApi.inwardAtHub(
|
||||
consignmentId,
|
||||
hubId: (base?.id.isNotEmpty ?? false) ? base!.id : null,
|
||||
// The position the fence just judged, not a fresh one: two fixes seconds
|
||||
// apart are two different answers and the hub's history row should carry
|
||||
// the one the app actually allowed the handover on.
|
||||
lat: decision.riderLat,
|
||||
lon: decision.riderLng,
|
||||
);
|
||||
final t = MilerLifecycle.inwardAtHub(res);
|
||||
MilerLifecycle.report('inward-at-hub', t);
|
||||
debugPrint(
|
||||
'[TRACE][HANDOVER] consignment=$consignmentId -> ${res.status} '
|
||||
'${res.code} confirmed=${t.isConfirmed} raw=${res.raw}',
|
||||
);
|
||||
|
||||
if (t.isConfirmed) return true;
|
||||
|
||||
// ── A 200 that names no state is not proof ──
|
||||
//
|
||||
// The rule request 15 exists for, and the one this app has been bitten by on
|
||||
// `reached`: a bare success is not a transition. The rider is not shown a
|
||||
// handover the hub may not have recorded.
|
||||
if (t.isUnconfirmed) {
|
||||
lastHandoverFailure =
|
||||
'Your office did not confirm the handover. Check with the base before '
|
||||
'you leave the parcel.';
|
||||
return false;
|
||||
}
|
||||
|
||||
final serverMsg = (res.message).trim();
|
||||
lastHandoverFailure = serverMsg.isNotEmpty && serverMsg.length < 140
|
||||
? 'The base would not accept this parcel: $serverMsg'
|
||||
: 'The base would not accept this parcel. Ask your office to check it.';
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -193,6 +193,11 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Which leg this stop is on. Async because it reads the pivot store, so the
|
||||
// sheet opens in its delivery shape and corrects itself a frame later —
|
||||
// the base CTA is behind a slide, so there is no window in which the rider
|
||||
// can commit the wrong rung.
|
||||
unawaited(_resolveHubLeg());
|
||||
_camera = MilerMapCamera(controller: _mapController, vsync: this);
|
||||
_routeAnim =
|
||||
AnimationController(
|
||||
@@ -1360,6 +1365,73 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
collectedIds: widget.parentState?._collectedIds ?? const <String>{},
|
||||
).isDelivery;
|
||||
|
||||
/// True when this stop ends at a base rather than at a receiver's door.
|
||||
///
|
||||
/// Read from the row's own `next_action`, never from the rider's line — the
|
||||
/// same resolver [handOverAtHub] and the Deliveries queue use, so the card,
|
||||
/// the sheet and the write cannot disagree about where a parcel is going.
|
||||
///
|
||||
/// Held in state rather than computed in `build` because resolving it reads
|
||||
/// the pivot store, which is async.
|
||||
bool _isHubLeg = false;
|
||||
|
||||
/// The base this stop is handed in at, once [_resolveHubLeg] has looked.
|
||||
HandoverHub? _handoverBase;
|
||||
|
||||
/// Resolves [_isHubLeg] once, on open.
|
||||
///
|
||||
/// Silent on failure: a stop whose leg cannot be read falls back to the
|
||||
/// delivery shape it had before this existed, which is the behaviour every
|
||||
/// other screen already has.
|
||||
Future<void> _resolveHubLeg() async {
|
||||
try {
|
||||
final leg = NextLegResolver.resolve(
|
||||
widget.pickup,
|
||||
pivotAction:
|
||||
(await getPivotNextActions())[MilkRun.idOf(widget.pickup)] ?? '',
|
||||
);
|
||||
if (!mounted) return;
|
||||
final base = leg.isHub ? handoverBaseFor(widget.pickup) : null;
|
||||
setState(() {
|
||||
_isHubLeg = leg.isHub;
|
||||
_handoverBase = base;
|
||||
// ── The destination is the base, not the door he collected at ──
|
||||
//
|
||||
// `MilkRun.navigatesToCustomer` is false for a base leg — correctly, a
|
||||
// base-routed parcel must never point at its receiver 500 km away — so
|
||||
// `_pickupLocation` fell back to the **pickup** coordinates and the map
|
||||
// sent the rider back to the customer he had just collected from.
|
||||
//
|
||||
// A base with no coordinates is left alone: navigating to `0, 0` lands
|
||||
// in the Gulf of Guinea. The handover is still refused by the fence in
|
||||
// that case, with a sentence pointing at the office.
|
||||
if (base != null && base.isNavigable) {
|
||||
_pickupLocation = LatLng(base.latitude, base.longitude);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
debugPrint('[HANDOVER] could not resolve the leg: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the parcel in at the base and closes the stop.
|
||||
///
|
||||
/// The base-routed twin of [_markDelivered]: same shape, different rung. It
|
||||
/// does not open [DeliveryProofPage] — there is no receiver to photograph and
|
||||
/// no OTP to take; the evidence the contract asks for is the position, which
|
||||
/// [handOverAtHub] stamps from the fix the fence judged.
|
||||
Future<void> _handOverAtBase() async {
|
||||
if (_isNavigating || !mounted) return;
|
||||
HapticFeedback.mediumImpact();
|
||||
// Straight through the one close path. [closeDelivery] routes
|
||||
// `handedOver` to [handOverAtHub] — which takes the fence, resolves the
|
||||
// consignment and posts `inward-at-hub` — and then files the same finished
|
||||
// record every other outcome files, so Activity, the carried set and the
|
||||
// queue all see one kind of closed stop. Calling [handOverAtHub] here as
|
||||
// well would post the handover twice.
|
||||
await _closeDelivery(DeliveryOutcome.handedOver);
|
||||
}
|
||||
|
||||
/// True once the rider has set off from **this screen** — slid Start
|
||||
/// delivery, or opened navigation on the collection leg.
|
||||
///
|
||||
@@ -1447,6 +1519,30 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
// [MilkRun.deliveryArrivalIsLocalOnly]), so a button for it would write
|
||||
// nothing. Once he sets off the stop is simply **active**, and the only
|
||||
// question left is whether it was handed over.
|
||||
// ── A base handover is its own rung ──
|
||||
//
|
||||
// It is not a delivery: there is no receiver, no proof photo, no OTP and no
|
||||
// "customer was out" outcome. It is also not nothing, which is what the app
|
||||
// offered before — [releaseForDelivery] refuses a base leg, correctly, and
|
||||
// the rider was left holding a parcel with a message telling him to hand it
|
||||
// over and no control that would record it.
|
||||
if (_isHubLeg) {
|
||||
final onTheRoad = _setOff;
|
||||
// Named where it is known. "Handed over at Coimbatore Base" is a rider
|
||||
// confirming a place; "Handed over at base" is him confirming a category,
|
||||
// and on a round with two bases that is the difference between a parcel
|
||||
// arriving and a parcel being looked for.
|
||||
final base = _handoverBase?.name ?? '';
|
||||
return MilerSlideAction(
|
||||
label: onTheRoad
|
||||
? (base.isEmpty ? 'Handed over at base' : 'Handed over at $base')
|
||||
: 'Slide to start ride',
|
||||
icon: onTheRoad ? LucideIcons.check : LucideIcons.chevronRight,
|
||||
color: ColorConstants.acceptGreen,
|
||||
onCommit: onTheRoad ? _handOverAtBase : _startRideToBase,
|
||||
);
|
||||
}
|
||||
|
||||
if (_isDeliveryLeg) {
|
||||
final onTheRoad = _setOff;
|
||||
final slide = MilerSlideAction(
|
||||
@@ -1572,6 +1668,16 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── Not refused, but not recorded either ──
|
||||
//
|
||||
// The rung advances locally below, which is right — a dead network must
|
||||
// not strand a rider at a door. What was wrong is that it advanced
|
||||
// *silently*: the rider saw ARRIVED and could not tell the difference
|
||||
// between a stop the hub knows about and one it does not.
|
||||
if (!ok && dc.lastArrivalNotice != null && mounted) {
|
||||
AppFeedback.warn(context, dc.lastArrivalNotice!);
|
||||
}
|
||||
|
||||
// The rung the rider sees, on the row he is looking at and in the store
|
||||
// that survives the refresh this flow triggers. `reached` does not
|
||||
// persist on every deployment yet — see `getArrivedOrderIds` — and the
|
||||
@@ -1607,8 +1713,100 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
/// here — no photo, a dead signature, a refused PUT — resolves to an empty
|
||||
/// string, which is what this call site was sending unconditionally until
|
||||
/// now. The local copy stays on the device either way.
|
||||
/// The parcel photograph's storage references, once uploaded. Null until it
|
||||
/// has been, and after a failed attempt — a failure is not a photograph.
|
||||
UploadRef? _parcelProof;
|
||||
|
||||
/// Uploads the door photograph once per stop.
|
||||
///
|
||||
/// Best-effort by design: a dead object store must not strand a rider at a
|
||||
/// customer's door holding parcels he cannot record. When it fails the parcel
|
||||
/// update goes without `photos` — which is honest, and better than an empty
|
||||
/// array claiming no photograph was taken.
|
||||
Future<void> _ensureParcelProofUploaded(int bookingId) async {
|
||||
if (_parcelProof != null || bookingId <= 0) return;
|
||||
final path = (_verificationProofPath ?? '').trim();
|
||||
if (path.isEmpty) return;
|
||||
|
||||
final file = File(path);
|
||||
if (!file.existsSync()) return;
|
||||
|
||||
// Kept on the device first, whatever the network does — see ProofStore.
|
||||
try {
|
||||
final orderId = (widget.pickup['orderid'] ?? '').toString();
|
||||
if (orderId.isNotEmpty) await ProofStore.save(orderId, path);
|
||||
} catch (e) {
|
||||
debugPrint('[PICKUP] could not keep a local copy of the proof: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
_parcelProof = await MilerApi.uploadProofRef(
|
||||
file,
|
||||
purpose: MilerApi.proofPickup,
|
||||
// The BOOKING id, in the booking field. There is no consignment yet —
|
||||
// `pickup-complete` has not run — and this used to pass the booking id
|
||||
// in the `consignmentid` slot, filing every pickup proof under a
|
||||
// consignment number that did not exist.
|
||||
bookingId: bookingId,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[PICKUP] parcel proof upload failed: $e');
|
||||
}
|
||||
|
||||
if (_parcelProof == null || !_parcelProof!.hasKey) {
|
||||
ApiConfig.logGap(
|
||||
'uploads/sign',
|
||||
'the parcel photo for booking $bookingId could not be uploaded (or the '
|
||||
'server returned no key); the parcels are being recorded without '
|
||||
'one and the copy stays on the device.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The local path of the photograph the verification screen took, if any.
|
||||
String? _verificationProofPath;
|
||||
|
||||
/// Copies the uploaded key onto the verification map the provider reads.
|
||||
Map<String, dynamic> _withParcelPhotos(Map<String, dynamic> verification) {
|
||||
final key = _parcelProof?.key ?? '';
|
||||
if (key.isEmpty) return verification;
|
||||
final pickup = verification['pickup'];
|
||||
if (pickup is! Map) return verification;
|
||||
return {
|
||||
...verification,
|
||||
'pickup': {...pickup, 'photos': <String>[key]},
|
||||
};
|
||||
}
|
||||
|
||||
Future<String> _uploadParcelProof(String path, int bookingId) async {
|
||||
if (path.isEmpty || bookingId <= 0) return '';
|
||||
|
||||
// Already sent, on the way to `POST /parcel`. Pushing the same bytes twice
|
||||
// costs a rider at a doorstep several seconds on a mobile connection and
|
||||
// leaves two copies of one photograph in the bucket.
|
||||
await _ensureParcelProofUploaded(bookingId);
|
||||
if (_parcelProof != null) return _parcelProof!.url;
|
||||
|
||||
// ── Kept on the device first, whatever the network does ──
|
||||
//
|
||||
// The uploaded URL goes nowhere: `pickup-complete` takes latitude and
|
||||
// longitude and nothing else, so even a successful upload leaves the hub
|
||||
// with no reference to the photograph (see BE-2, and the gap logged in
|
||||
// `UpdatePickupProvider`). The rider was being made to photograph the
|
||||
// parcels — the flow will not let him confirm without it — for a record
|
||||
// that existed only in a bucket nobody could search.
|
||||
//
|
||||
// A local copy against the order id is the one form of this evidence that
|
||||
// is actually retrievable today: the office rings the rider and he has it.
|
||||
// Best-effort, and deliberately before the upload, because the case where
|
||||
// it matters most is the one where the network is the problem.
|
||||
try {
|
||||
final orderId = (widget.pickup['orderid'] ?? '').toString();
|
||||
if (orderId.isNotEmpty) await ProofStore.save(orderId, path);
|
||||
} catch (e) {
|
||||
debugPrint('[PICKUP] could not keep a local copy of the proof: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
final url = await MilerApi.uploadProof(
|
||||
File(path),
|
||||
@@ -1686,6 +1884,22 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
await _openGoogleMapsNavigation();
|
||||
}
|
||||
|
||||
/// Sets off for the base.
|
||||
///
|
||||
/// Deliberately **not** [_startDelivery]. `start-delivery` moves the
|
||||
/// consignment to `Out_for_Delivery` against a receiver in another district;
|
||||
/// the hub then sees a rider actively delivering a parcel that is going onto
|
||||
/// a line-haul truck, and there is no way back from that state on the
|
||||
/// handset. A base leg has no release rung at all — the rider simply rides
|
||||
/// there, and the next thing the server hears is the handover.
|
||||
Future<void> _startRideToBase() async {
|
||||
if (_isNavigating || !mounted) return;
|
||||
setState(() => _setOff = true);
|
||||
HapticFeedback.mediumImpact();
|
||||
_hasOpenedNavigation = false;
|
||||
await _openGoogleMapsNavigation();
|
||||
}
|
||||
|
||||
/// Records a stop that could not be handed over.
|
||||
///
|
||||
/// The same chooser the proof page shows, reached without having to slide
|
||||
@@ -1845,7 +2059,15 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
|
||||
Map<String, dynamic> verifyResult = <String, dynamic>{'verified': true};
|
||||
|
||||
if (ServiceProfile.active.needsVerification) {
|
||||
// ── Asked of the stop, not of the rider ──
|
||||
//
|
||||
// `ServiceProfile.active.needsVerification` gives the same answer for
|
||||
// every row on the screen. On a meal tenant that walked a CX customer
|
||||
// pickup straight past the door flow — no parcel count, no destination,
|
||||
// no weight — and the booking pivoted on whatever the customer typed into
|
||||
// the app days earlier. [WorkPolicy] asks the row, and falls back to the
|
||||
// line only where the row says nothing.
|
||||
if (WorkPolicy.capturesShipmentDetails(widget.pickup)) {
|
||||
final verified = await openScreen<Map<String, dynamic>>(
|
||||
context,
|
||||
StopVerificationPage(pickup: widget.pickup),
|
||||
@@ -1870,7 +2092,7 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
// customer. Its answers ride along in the same map, and
|
||||
// `_startPickupNavigation` sends them — addresses first, because
|
||||
// `pickup-complete` routes the consignment from them.
|
||||
if (ServiceProfile.active.capturesShipmentAddresses) {
|
||||
if (WorkPolicy.capturesShipmentAddresses(widget.pickup)) {
|
||||
final seeded = Map<String, dynamic>.from(widget.pickup);
|
||||
// Don't ask for the weight twice: the verification page has just taken
|
||||
// it, so the desk opens with it filled in.
|
||||
@@ -2038,6 +2260,12 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
if (_isNavigating || !mounted) return;
|
||||
setState(() => _isNavigating = true);
|
||||
|
||||
// The photograph the verification screen took, remembered so the parcel
|
||||
// update and the pickup-complete proof both use the one upload.
|
||||
_verificationProofPath = (verificationData['parcelImage'] ?? '')
|
||||
.toString()
|
||||
.trim();
|
||||
|
||||
try {
|
||||
final dc = Get.put(PickupsController(), permanent: true);
|
||||
final d = widget.pickup;
|
||||
@@ -2184,9 +2412,23 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
}
|
||||
|
||||
if (pickupId > 0) {
|
||||
// ── The photograph is uploaded HERE, before the parcels are sent ──
|
||||
//
|
||||
// It used to be uploaded much later, inside `_payAndCreateOrder`, and
|
||||
// only its URL was kept — so `POST /parcel` went out with no `photos`
|
||||
// and the evidence ended up in a bucket nobody could search. `photos`
|
||||
// wants the storage **key**, so the upload has to happen before this
|
||||
// call, not after it.
|
||||
//
|
||||
// Uploaded once and remembered: `_payAndCreateOrder` reuses the same
|
||||
// ref for `proofImage` rather than pushing the same bytes twice.
|
||||
await _ensureParcelProofUploaded(pickupId);
|
||||
|
||||
final parcelRes = await UpdatePickupProvider().submitParcels(
|
||||
pickupId,
|
||||
verificationData,
|
||||
// The key rides in on the verification map the provider already
|
||||
// reads, so no third source of truth about this door.
|
||||
_withParcelPhotos(verificationData),
|
||||
);
|
||||
if (parcelRes?['status'] != true) {
|
||||
debugPrint('[PARCEL] booking $pickupId: not recorded — $parcelRes');
|
||||
@@ -2220,7 +2462,7 @@ class _PickupMapScreenState extends State<_PickupMapScreen>
|
||||
// the compliance stamp, the completed record, the next-stop list and the
|
||||
// hand-off screen — runs once and unchanged for either.
|
||||
final dynamic result =
|
||||
(ServiceProfile.active.initiatesShipment && shipmentCapture != null)
|
||||
(WorkPolicy.initiatesShipment(widget.pickup) && shipmentCapture != null)
|
||||
? await openScreen<Map<String, dynamic>>(
|
||||
context,
|
||||
ShipmentReviewPage(
|
||||
|
||||
@@ -15,7 +15,7 @@ library;
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart' show kDebugMode, mapEquals, setEquals;
|
||||
import 'package:flutter/foundation.dart' show mapEquals, setEquals;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:lucide_icons_flutter/lucide_icons.dart';
|
||||
import 'package:miler/views/helpers/constants/design_constants.dart';
|
||||
@@ -82,6 +82,10 @@ import 'package:miler/data/service_day.dart';
|
||||
import 'package:miler/data/work_domain.dart';
|
||||
import 'package:miler/data/work_repository.dart';
|
||||
import 'package:miler/data/miler_api.dart';
|
||||
import 'package:miler/data/lifecycle.dart';
|
||||
import 'package:miler/data/geofence.dart';
|
||||
import 'package:miler/data/task_profile.dart';
|
||||
import 'package:miler/data/pickup_locations.dart';
|
||||
import 'package:miler/data/assignment_lookup.dart';
|
||||
import 'package:miler/utils/external_navigation.dart';
|
||||
|
||||
@@ -943,33 +947,10 @@ class _MyPickupsState extends State<MyPickups>
|
||||
fontFamily: FontConstants.fontFamily,
|
||||
),
|
||||
),
|
||||
_fetchDiagLine(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// The last fetch's stage counts, shown under an empty state in debug only.
|
||||
/// Never compiled into release — [kDebugMode] is a const, so the whole widget
|
||||
/// folds away.
|
||||
Widget _fetchDiagLine() {
|
||||
if (!kDebugMode || _fetchDiag.isEmpty) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(top: 18.h),
|
||||
child: Text(
|
||||
'debug · $_fetchDiag\n'
|
||||
'${_bookingTrips.length} trip(s) · showing ${_visibleStops.length}',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 10.sp,
|
||||
height: 1.5,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: ColorConstants.secondaryText,
|
||||
fontFamily: FontConstants.fontFamily,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTripRail() {
|
||||
// The whole run, finished stops included — see [_railStops]. Drawn as long
|
||||
// as *anything* happened today, so a rider who has just closed his last
|
||||
@@ -2182,8 +2163,10 @@ class _MyPickupsState extends State<MyPickups>
|
||||
// separate causes have made this tab look empty — a gate on the raw API
|
||||
// count, a missing empty state on an unfilled trip tab, and stops
|
||||
// filtered out as still-pending — and every one of them looked identical
|
||||
// on screen. The counts are now shown on the empty state itself, so the
|
||||
// failing stage is visible instead of guessed at.
|
||||
// on screen. The counts go to the log so the failing stage can be read
|
||||
// off a `flutter logs` rather than guessed at. They are deliberately NOT
|
||||
// drawn on the empty state any more: that put developer diagnostics in
|
||||
// front of the rider on every debug and demo build.
|
||||
_fetchDiag =
|
||||
// Which line the app resolved the rider onto. Three of the reports
|
||||
// that landed here as "the tab is wrong" were really "the app thinks
|
||||
@@ -3118,9 +3101,16 @@ class _MyPickupsState extends State<MyPickups>
|
||||
// is the picture now, at a size worth looking at, and
|
||||
// it keeps its own copy.
|
||||
//
|
||||
// [_fetchDiagLine] stays: it is `kDebugMode`-gated and
|
||||
// folds away entirely in release, so nothing ships
|
||||
// underneath the art.
|
||||
// Nothing is drawn under the art. A stage-count
|
||||
// readout used to sit here — `debug · line=milkMan
|
||||
// api=0 accepted=0 …` — on the argument that it was
|
||||
// `kDebugMode`-gated and folded away in release.
|
||||
// True, and it still meant every internal build,
|
||||
// every demo and every screenshot showed a rider a
|
||||
// line of diagnostics under a picture telling him he
|
||||
// was all caught up. The counts are still gathered
|
||||
// and still logged — see `[MYPICKUPS][DIAG]` — where
|
||||
// the person who needs them is looking.
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -3140,7 +3130,6 @@ class _MyPickupsState extends State<MyPickups>
|
||||
),
|
||||
),
|
||||
),
|
||||
_fetchDiagLine(),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -193,7 +193,7 @@ class _PickupBottomSheetState extends State<_PickupBottomSheet>
|
||||
// stays "Confirm pickup".
|
||||
final String confirmLabel = isDelivery
|
||||
? 'Confirm delivery'
|
||||
: (ServiceProfile.active.initiatesShipment
|
||||
: (WorkPolicy.initiatesShipment(widget.pickup)
|
||||
? 'Initiate order'
|
||||
: 'Confirm pickup');
|
||||
|
||||
|
||||
Reference in New Issue
Block a user