Commit Graph

48 Commits

Author SHA1 Message Date
Suriyakumarvijayanayagam
b0f733ae38 feat: miler POD upload — presigned Spaces PUT (/miler/uploads/sign)
Rider proof-of-delivery / signature photos need a way to reach storage.
The legacy (jupiter) rider app shipped the DigitalOcean Spaces access/secret
key inside the Flutter build and PUT to the bucket directly. This moves the
key server-side and hands the app a short-lived presigned PUT URL instead.

- internal/storage/spaces.go: self-contained AWS SigV4 query presigner for
  Spaces (S3 API) — no aws-sdk-go-v2 dependency for a single presign op.
  Verified live end-to-end (presign -> PUT 200 -> CDN GET matches).
- controllers/uploadController.go: POST /miler/uploads/sign returns
  { uploadurl, url, method, headers, key, expiresin }. Same bucket/folders/
  CDN (images.nearle.app) as jupiter so images share one store.
- Reads DO_SPACES_* from .env via godotenv; returns 503 UPLOAD_NOT_CONFIGURED
  when unset rather than handing out URLs that 403.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WRaFH5hMRqmUQvVPQsyjZD
2026-08-24 18:18:52 +05:30
Suriyakumarvijayanayagam
f6d339a33f feat: miler delivery-leg fixes — consignmentid, auto route sequencing, admin consignment status
Miler app P0 + contract gaps found in the live audit:

- GET /miler/bookings now returns consignmentid + consignmentstatus on every
  row (nullable), so the app can call deliver/skip/start-delivery straight from
  the list. /miler/assignments is the active-only queue, so this is the
  authoritative fix for stops that have moved onto the delivery leg.
- GET /miler/bookings now returns sequencedat per row: non-null means the
  console/optimizer fixed this stop's order and the app follows step exactly;
  null means no route assigned and the app may fall back to nearest-first.
- Route sequencing (internal/routing) now runs automatically after every
  assignment — customer auto-assign, express auto-assign, manual assign, and
  accept — via SequenceMilerStopsAsync (fire-and-forget, no-op below two active
  stops). Previously only hub batch-assign sequenced, so most riders saw step=0.
- GET /admin/bookings now surfaces the live consignmentstatus alongside the
  frozen booking status, so a Converted_To_Consignment booking can still show
  Out_for_Delivery / Delivered instead of a generic "Active".

Two-step hyperlocal flow (Arrived_At_Pickup, Collected_By_Miler, start-delivery)
stays gated behind MILER_COLLECTED_STATE_ENABLED (default off) until the app
ships; consignmentid/status, GET /miler/consignments/:id, stable error codes and
Idempotency-Key handling are unconditional and safe on the current app.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WRaFH5hMRqmUQvVPQsyjZD
2026-08-24 10:34:12 +05:30
Suriyakumarvijayanayagam
531185cf66 feat: miler app contract gaps — stop type, COD, pre-pickup skip, profile
Close the gaps the miler-app dev flagged against the deployed contract.

- GET /miler/bookings: return stoptype (pickup|delivery, from status),
  step + road-optimized sequence (cumulativekms/etaminutes/cumulativeeta),
  and codamount/paymentmode. List sorted by step, unsequenced last.
  Lookups batched to avoid N+1.
- POST /miler/bookings/:bookingid/skip: pre-pickup skip that keeps the
  booking assigned and resumable — the "route back" the consignment-only
  delivery skip couldn't give a not-yet-picked-up booking.
- GET /miler/earnings: add cancelled_stops + total_stops for success rate.
- PUT /miler/profile: persist email (to appusers, 409 on unique clash) and
  a new nullable milerprofiles.address column.
- POST /miler/assignments/:id/reject: accept reason from body OR ?reason=.

Notifications read-state and bonuspoints deliberately left as-is — both
need a product/business decision, not code.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-21 11:22:01 +05:30
Suriyakumarvijayanayagam
f09efcaf59 feat: express-batch dispatch — manual trigger for the AI agent
Adds the backend half of the ExpressDispatchAgent flow. Express orders can now
be created batch by batch (bulk create only accumulates them, unassigned), then
an operator hits one endpoint to hand the whole pending set to the agent for
tenant-scoped assignment + road sequencing. The normal B2C flow is untouched.

- POST /admin/expressbooking/dispatch: manual trigger. Console-auth, tenant-
  scoped; gathers the tenant's pending unassigned express orders (or a chosen
  subset) and publishes express.dispatch_requested.
- internal API for the agent: GET /internal/express/riders (tenant's available
  riders), GET /internal/express/bookings, POST /internal/express/assign (writes
  the agent's decided assignments with their sequence; re-checks the already-
  assigned guard so the agent can't double-assign).
- booking_assignment_service.go: extracted a behavior-preserving assignMilerTx
  core; AssignMilerToBooking is unchanged in behavior. assignExpressStops writes
  a batch, one FCM per rider instead of one per stop.
- EXPRESS JetStream stream / express.dispatch_requested subject.
- Gated behind EXPRESS_AGENT_ENABLED (default off): deploying this changes
  nothing until the agent is confirmed running and the flag is flipped.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-17 19:33:48 +05:30
Suriyakumarvijayanayagam
cfdc99ec9a feat: give the console customer page a flat address to edit
The admin customer page collected an address (door no, street, suburb,
city, state, postcode, landmark, lat/lng) that the backend had nowhere to
store, so it was silently dropped on save. Add those fields flat onto
appcustomers, matching the reference console's shape, plus an applocationid
for zone scoping.

- GET /admin/customers: add ?applocationid= filter; emit firstname/lastname
  split and the address fields alongside the existing joined name.
- GET /admin/customers/summary (new): stat-tile counts (total/active/blocked)
  scoped like the list, so the client stops deriving them from the full page.
- PATCH /admin/customers/🆔 accept firstname/lastname directly (single name
  still splits as a fallback) and persist every address field; pointer fields
  so an omitted field is not confused with one cleared to empty.

Pagination and keyword search were already present. Additive, nullable
columns — AutoMigrate handles it, no data rewrite.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-17 11:05:51 +05:30
Suriya
ba800aee66 docs: the order-to-delivery flow, end to end
Payloads taken from the request structs rather than from documentation,
since the two had already drifted once. Records the things that are easy
to get wrong and hard to diagnose: configid 1001 on both rider auth
calls, tenantlocationid vs pickuplocationid pointing at different tables,
step 0 meaning 'not sequenced' rather than 'first', and admin miler
endpoints keying on milerprofileid while assign-miler takes a
mileruserid.

Also states plainly why bulk creation cannot sequence stops: assignment
picks who, sequencing picks the order, and the second needs the first.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 15:38:06 +05:30
Suriya
cb2660a3da feat: talk to the optimizer in Doormile's own vocabulary
The client was speaking jupiter's provider dialect -- deliveryid,
pickuplat, coordinates as strings -- because that was the only endpoint
the Route Optimization API offered. rider-bike now has
/api/v1/optimization/doormile/sequence, which takes bookingid and
pickuplatitude, so the translation layer is gone.

The new endpoint validates its body; the provider one cannot, because
jupiter is live on it and tightening it would break real deliveries.
That matters here: sending the provider endpoint the wrong field names
returns HTTP 200 "Success" with every coordinate defaulted to 0.0, no
reordering and all distances zero. The Doormile endpoint rejects that
outright, and rejects 0,0 coordinates, which are inside the valid range
but are a point in the Atlantic that drags a whole route toward it.

Responses now come back properly typed, so the loose float/string
coercion is deleted rather than kept for a shape that no longer arrives.
Tests replaced to match: they run the real client against a stub server
and pin the outbound field names, the mapping back onto assignment ids,
that steps for assignments we never sent are discarded, that step 0 is
not persisted as a position, and that a failed optimise surfaces an
error instead of quietly looking like success.

Needs rider-bike deployed first; until then sequencing fails
best-effort, which leaves bookings assigned but unordered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 15:29:08 +05:30
Suriya
0288fb7af8 feat: order a rider's stops using the Route Optimization API
Assignment decided who carried a booking but never what order to run
several of them in -- the one capability jupiter had that Doormile did
not. It turns out we already own the solver: routes.workolik.com is a
live in-house Route Optimization API backed by Valhalla road-network
routing, not the paid third party I had assumed. This is a client for
it, not a solver.

internal/routing posts a rider's active stops and writes back step,
previouskms, cumulativekms and ETA onto BookingAssignment. HubBatchAssign
calls it after committing a batch, which is exactly the case it exists
for: a rider used to walk away with several bookings and no order to run
them in. GetMilerAssignments now returns sequenced stops in step order,
falling back to newest-first for anything unsequenced.

Contract discovered by probing the live service -- the OpenAPI schema
types the body as a bare object array, so the field names are not
documented anywhere. They are pickuplat/pickuplong/deliverylat/
deliverylong, NOT pickuplatitude/deliverylatitude. Sending the wrong
names does not fail: it returns HTTP 200 with every coordinate defaulted
to "0.0", no reordering and all distances zero. That trap is recorded in
a comment so the next person does not lose an afternoon to it.

Numeric fields come back inconsistently typed -- previouskms as a number,
actualkms and eta as strings, some decimal -- so they are decoded loosely
and coerced, with tests pinning the coercion. Steps for deliveryids we
did not send are discarded rather than written, so an echoed or stale id
cannot reorder another rider's work.

Sequencing is best-effort throughout and runs after assignments commit.
The optimizer is a separate service over the network; it being down must
leave bookings assigned but unordered, never undo the batch. Step 0 means
"not sequenced", not "first".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 15:06:24 +05:30
Suriya
2cbc9e5b13 docs: record that the external stream setup script is now read-only
Birock/doormile-bookings/setup_jetstream.py called update_stream with the
subject list replaced wholesale, from a hardcoded list that had drifted
behind this repo. Re-running it would have stripped booking.cancelled,
booking.outcome, booking.assignment_failed, chat.room.closed.* and --
worst -- booking.assignment_requested, which carries the assignment
retry loop rather than merely reporting on it. Bookings would have
stopped reaching riders with nothing logged, until a restart repaired
the stream via EnsureStreams. A "setup" script that causes an outage
when run is a bad thing to leave lying around.

It is now an inspector: it reports streams, subjects and consumer state
and has no add/update/delete calls at all. Verified it is the only
script anywhere that pointed at doormile-nats (66.116.226.161:4223) --
every other stream-mutating script targets jupiter's NATS.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 10:48:53 +05:30
Suriya
2158031191 fix: assignment retries no longer die with the pod
AssignCustomerMiler and AssignCRMMiler retried five times, two minutes
apart, using time.Sleep inside a bare goroutine — about ten minutes of
state held only in one pod's memory. Any restart dropped every retry in
flight, and nothing recorded it: the booking just stayed unassigned
forever with no failure event, because publishAssignmentFailed only runs
at the end of a loop that no longer existed. Deploying during a quiet
patch was enough to lose bookings this way, and it happened during
today's rollout.

Retries now run on the ASSIGNMENTS stream. Each entry point publishes
one booking.assignment_requested message; a durable consumer performs a
single attempt per delivery and NAKs with retryDelay when no miler is
available, so JetStream owns both the waiting and the delivery count.
A pod dying mid-wait costs nothing — the message is still on the server
and another replica takes it.

Behaviour is deliberately unchanged from the caller's side: same five
attempts, same two-minute spacing, same publishAssignmentFailed handoff
to the DispatchAgent. The failure event is fired explicitly on the last
delivery, since JetStream stops redelivering at MaxDeliver and would
otherwise let the booking fail silently again.

runInline keeps the old loop as a fallback for when JetStream is down.
Assignment is how a booking reaches a rider, so it must not become
dependent on the event bus: an outage should cost durability, which is
what we had before, not stop bookings being assigned at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 16:29:32 +05:30
Suriya
41f0013751 revert: drop the jupiter->Doormile telemetry bridge
Doormile should not be wired to jupiter's APIs at all. The ingest routes,
the legacy identity middleware and the worker-side fan-out existed to
copy jupiter's rider GPS into Doormile, which was never the goal:
Doormile needs its own JetStream in front of its own endpoints, not a
pipe from someone else's.

Removed here: /internal/miler/* ingest, LegacyMilerIdentity, and the
legacyuserid field on the miler update payload. The worker-side shadow
forward and its k8s secret are removed separately in the Kubernetes
repo; jupiter forwarding is untouched and verified still healthy.

MilerProfile.Legacyuserid is deliberately kept. Nothing reads it now,
but it records which jupiter rider each of the six migrated riders came
from, which is worth having during the cutover. Dropping a populated
column buys nothing and AutoMigrate would not drop it anyway.

Kept from that work because they are unrelated to jupiter and fix real
bugs: db.EnsureStreams (four subjects were publishing to no stream and
being dropped silently) and the tenantlocationid column.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 16:24:35 +05:30
Suriya
5458d080c6 feat: let ops set a miler's legacyuserid through the console
Backfilling the jupiter->Doormile rider mapping otherwise needs a direct
UPDATE against production, since nothing else writes the column.
UpdateMiler already runs behind admin auth and findMilerForConsole's
tenant scoping, which is the right gate for an ops-only field: it is set
for migrated riders and never by the rider themselves.

Confirmed mapping, matched on phone (jupiter userid -> Doormile userid):
852->37 Sivakumar Subramani, 883->38 Rajan A, 897->39 Varun Edward,
950->40 Jayasabesh Kumar S, 1111->41 Murali P, 1114->42 Tamilazhagan K.

852 sat under a different jupiter partner (Xpress-Mdu-Main) than the
other five, which looked like it might put him out of scope. He is not:
he was migrated to tenant 14 / Nagercoil / hub 18, so a Madurai-side
partner is exactly where jupiter would carry him. jupiter's partnerid is
a rider hub, not a tenant, so it cannot be used to decide tenant
membership.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 15:48:41 +05:30
Suriya
6738d37d7b feat: own the JetStream subject contract, and ingest jupiter rider telemetry
Half of this binary's js.Publish calls were bound to no stream at all.
The streams were declared only by an external Python script on another
machine (Birock/doormile-bookings/setup_jetstream.py) and had drifted
from the code: booking.cancelled, booking.outcome and
booking.assignment_failed had no stream, and CHAT declared the literal
"chat.room.closed" while chat.go publishes "chat.room.closed.<id>",
which it does not match. Every publish site is best-effort
(`if db.Js != nil` + warn-log), so those events were failing and being
dropped silently — every cancellation, delivery outcome and assignment
failure since the streams were created.

db.EnsureStreams now declares the streams at startup from a map that
sits next to the code that publishes, so the contract cannot drift
again. It only ever adds: existing streams keep their storage type,
retention, limits and every subject they already have. Nothing is
deleted. Losing the create race against a sibling replica is expected
and reconciles rather than erroring.

Alongside that, /internal/miler/* ingests rider telemetry still arriving
over the jupiter NATS chain. The forwarding worker holds no rider JWT —
the rider app is still jupiter-shaped — so LegacyMilerIdentity resolves
an identity from a header into c.Locals("userid") behind the existing
X-Internal-Key guard. That lets the routes reuse the miler handlers
unchanged instead of growing a parallel set that would drift.

Identity comes from a header, never the body: the telemetry handlers
overwrite a body-supplied userid precisely so one rider cannot write
another's GPS trail, and reading it from the body here would reopen that
from behind the internal key. MilerProfile.Legacyuserid (nullable,
indexed) maps a jupiter userid to a Doormile one.

Only fire-and-forget telemetry is exposed. Transactional actions stay
synchronous — a rider needs a real answer from pickup-complete, which a
queue in front of it cannot give.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-10 12:56:30 +05:30
Suriya
90fa4fbb74 fix: per-site attribution needs its own column, not pickuplocationid
Caught by testing the previous commit against production: creating a booking
with a resolved site failed with

  pickupbookings_pickuplocationid_fkey
  FOREIGN KEY (pickuplocationid) REFERENCES appcustomerlocations(...)

pickuplocationid is the *customer's* saved address, a B2C concept. It never
referred to the client company's own kitchens or branches. The pre-existing
code that validated an incoming pickuplocationid against TenantLocation was
wrong on the same point and would have 500'd for any caller that used it — it
had simply never been called with a value.

Adds tenantlocationid to pickupbookings and consignments (nullable, indexed,
additive via AutoMigrate), carried across at pickup, and points the reporting
filter, the by_location breakdown and the Unattributed bucket at it.

The booking request accepts tenantlocationid, and still accepts
pickuplocationid as an alias so anything written against the earlier docs
starts working instead of failing.

Also gofmt on the two model files touched; booking.go was already failing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 13:08:57 +05:30
Suriya
0c407e5b27 feat: per-site reporting, and actually populate the site on a booking
jupiter's getreportsummary took a locationid — per kitchen, per branch. That
was the one report parameter with no Doormile equivalent, and for a food
client with 23 kitchens it is the difference between one number and a usable
report.

  GET /admin/reports?locationid=      narrows every figure to one site
  GET /admin/reports                  now carries a by_location block
  GET /admin/locations/summary        the standalone per-site table

The filter alone would have been useless: pickuplocationid was null on every
booking in the system, because the console sends a kitchen's address rather
than its id. createExpressBooking now resolves the site itself — nearest
stored location within 150m, falling back to an address match, nil when
nothing matches confidently, since a wrong attribution silently moves orders
between kitchens. An explicit pickuplocationid still wins.

Bookings that named no site are reported as their own "Unattributed" row
rather than dropped, so per-site rows add up to the summary total.

Two fixes found while in here:
- the payments join in the per-site query fanned out, counting a booking once
  per payment row; payments are now pre-aggregated per booking
- by_rider was empty for every client login, which reads as "your riders did
  nothing". Riders are tenant-scoped now, so a client sees its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:56:56 +05:30
Suriya
cf488b3d76 docs: jupiter to Doormile API migration map
Maps every jupiter endpoint we have replaced to its Doormile equivalent, for
the express console and the miler app only. Marks which jupiter paths were
confirmed from live network logs versus taken from the prior codebase
analysis, and states per row whether the Doormile side has been hit with a
real request or only compiles.

Includes the 11-way decomposition of PUT /deliveries/updatedelivery, the
behaviour changes that break a naive repoint, and the gaps jupiter covered
that Doormile does not yet — per-site reporting being the notable one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:49:40 +05:30
Suriya
511d369d7f docs: refresh the express-console API reference
Adds the five rider/tracking endpoints, the ?tenantid= staff filter and the
403-vs-404 refusal rules, and replaces the guesswork coverage note with what
was actually run against production on 2026-08-06.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:46:21 +05:30
Suriya
f44e8fa3b4 fix: access checks that returned utils.Forbidden never blocked anything
utils.Forbidden and utils.NotFound write the response and return c.JSON's
nil. Any helper that signalled refusal by returning one of them handed its
caller a nil error, so every `if err != nil { return err }` guard passed and
the handler carried straight on.

The observable result: GET /admin/milers?tenantid=14 as a DailyGrubs login
returned HTTP 403 with all 30 of the network's riders in the body. Status
line correct, payload leaked.

Three helpers were affected:
  effectiveTenantID    (yesterday, mine) — cross-tenant read returned the
                       unfiltered list under a 403
  canAccessBooking     (was assertBookingAccess, shipped in 6d9232f) — four
                       mutating booking handlers were unguarded
  findMilerForConsole  (was assertMilerAccess) — worse, callers went on to
                       dereference the nil profile

All three now return a bool and the caller writes the refusal itself, so the
control flow is visible at the call site instead of hiding in a helper.

Adds a test that pins utils.Forbidden/NotFound returning nil, so if that ever
changes the assumption breaks loudly rather than silently, plus table tests
for effectiveTenantID.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:32:13 +05:30
Suriya
42f2a41ff6 feat: filter console reads by tenant, for clients and for Doormile staff
Two halves of the same thing. A client login was already pinned to its own
tenant on most reads, but the roster, the B2C customer list and the dashboard
counters were not — a DailyGrubs login listed the whole network's riders.

The other half was missing entirely: Doormile's own staff had no way to look
at one client's slice. Reports accepted ?tenantid= but applied it only to the
consignment count, and bookings accepted it while milers, customers,
consignments and the dashboard ignored it.

effectiveTenantID(c) now resolves both cases in one place — the caller's own
tenant for a client login, the requested one for Doormile staff, 0 for the
whole network. A client asking for someone else's tenantid is refused rather
than silently handed their own data back under the wrong label.

Applied to: milers, customers, bookings, consignments, dashboard, reports and
the rider summary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 12:01:13 +05:30
Suriya
d85d5571b8 feat: rider visibility and tracking for the express console
A client login could list its own bookings but had no way to see what its
riders were actually doing. jupiter's console gave them getridersummary and
the rider/delivery logs; Doormile records all of it and exposed none of it.

New console endpoints, all tenant-scoped:
  GET /admin/milers/summary        roster with live state + range totals
  GET /admin/milers/:id/logs       GPS trail from the Redis telemetry index
  GET /admin/milers/:id/activity   one rider's assignments, duty and breaks
  GET /admin/consignments/:id/logs event history + telemetry + proof
  GET /admin/bookings/:id/track    booking -> assignments -> parcel -> proof

Also closes a rider IDOR: GetMilers scoped the roster to the caller's own
fleet, but reading, editing, blocking, notifying or assigning a vehicle to a
single rider by id did not, so a client login could walk the whole network's
riders by incrementing the id. All five now go through assertMilerAccess.

And the client dashboard no longer reports milers/customers/exceptions as
zero — those have no tenant column, so they are counted through appusers,
bookings and consignments respectively.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 11:41:02 +05:30
Suriya
6d9232f3b7 fix: close the remaining express-console tenant leaks
The first scoping pass covered tables carrying a tenantid column. These five
have no such column and were still returning every client's data to a client
login, which is what made creating info@dailygrubs.com unsafe:

- GET /admin/customers — scoped through the bookings placed for them, since a
  customer carries no tenant of their own (the same person can order from two
  clients).
- GET /admin/exceptions — scoped through the consignment the exception was
  raised against.
- GET /admin/tenantcustomers — the legacy customers table predates tenant
  attribution entirely, so no row can be proven to belong to a client. Returns
  empty for client logins rather than handing over the whole list.
- GET /admin/tripsheets — a vehicle run routinely carries several clients'
  parcels on one manifest, so there is no honest per-client view. Doormile
  staff only.
- GET /admin/milers — scoped through appusers.tenantid, so a client sees their
  own riders rather than the whole roster.

Also guards PUT /admin/consignments/:id/status, which took the id straight from
the path and would have let a client move another client's parcel through the
network.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:39:34 +05:30
Suriya
9b3ec886ce fix: populate riderkms and ridercharges on delivery completion
riderkms, ridercharges and bonuspoints appeared in exactly three places in the
codebase — all three GET /miler/earnings reading them. Nothing ever wrote them,
so every completed job reported zero distance and zero value and the earnings
screen was permanently empty.

On delivery completion:
- riderkms is the distance ridden for the booking, pickup point to where the
  rider confirmed delivery, falling back to the booking's delivery coordinates
  when the app sends no position.
- ridercharges is the order amount the tenant is billed, supplied at creation
  as finalprice and already stored on the booking service option. Doormile does
  not compute it; this is pass-through.
- bonuspoints deliberately left at zero pending a decision on what earns them.

Also moves the monthly earnings window onto utils.DBNow, so it doesn't put a
rider in the wrong month for 5h30m either side of a month boundary.

Note historical rows keep whatever completedat they were written with before
the image gained TZ=Asia/Kolkata, so figures spanning today are mixed; not
backfilled.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:33:01 +05:30
Suriya
39dcba3d80 fix: put the Redis user-cache utilities behind console auth
/api/v1/utils/users/redis exposed open CRUD — create, read, update and delete
on the cached-user store — to anonymous callers. The store is currently empty
and nothing in the console or apps calls it, so closing it breaks no client.

Third of the three route groups flagged in the 2026-07-27 audit. /crm/* stays
open by explicit decision: the field-sales Flutter app sends no credentials.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:23:59 +05:30
Suriya
4d03676e60 fix: put the booking cache endpoints behind console auth
/api/v1/bookings/cache/* was open "for testing" but is live in production:
listing it returns real bookings including customer delivery addresses, and
/customer/:customer_id takes the customer straight from the URL, so anyone
could enumerate a given customer's bookings without credentials.

Now requires a console token (roles 1/3/4), matching the rest of the admin
surface. The /crm/* group stays open by deliberate decision — the field-sales
Flutter app authenticates with nothing and would break; revisit when that app
can send a key.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:22:42 +05:30
Suriya
c8a9b5d797 fix: customer PIN-reset takeover, booking-quote and consignment-log IDORs
- POST /customer/reset-pin was unauthenticated and overwrote a customer's PIN
  given only their phone number — which is the login identifier, not a secret —
  so reset-pin followed by verify-pin took over any customer account. Exactly
  the miler flaw fixed in fd7cf3e, on the B2C side. It now requires the account's
  registered email to have been verified through the existing
  send-email-otp/verify-email-otp flow; the verification is recorded in Redis
  for 10 minutes and consumed on use, so one verification authorises one reset.
  Accounts with no email on file are directed to support rather than left open.

- GET /customer/bookings/:id/price had no ownership check, unlike every other
  customer booking route, so any signed-in customer could read the price quoted
  on anyone else's booking by walking the id.

- GET /miler/consignments/userlogs/:userid took the rider from the URL and never
  compared it to the caller, letting any miler read another miler's movement
  history.

Verified as already correct while sweeping: miler assignment and booking-flow
handlers all scope by mileruserid/assignedmileruserid, customer booking detail
and cancel scope by appcustomerid, /internal sits behind InternalKeyAuth, and
CreateHubStaffAccount already refuses non-Doormile staff.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:20:47 +05:30
Suriya
fd7cf3e35e fix: console tenant scoping, miler identity spoofing, delivery proof, timezone
Security
- Express console had no tenant scoping at all: LoginAdmin hardcoded tenantid 0
  into every JWT and none of the 85 admin handlers filtered by tenant, so any
  client given a console login would read every other client's bookings,
  customers, pricing and reports. Adds DoormileAuth.Tenantid (nil = Doormile
  staff, unrestricted; set = client, scoped), emits it in the token, and scopes
  reads, guards writes and pins tenantid on create.
- Miler telemetry (/miler/logs, /miler/status, /miler/consignments/logs) took
  userid from the request body, letting any authenticated rider write another
  rider's status and GPS trail — data the dispatch layer reasons over. Identity
  now comes from the token.
- POST /miler/reset-pin was unauthenticated and overwrote a PIN given only a
  phone number, so reset-pin + verify-pin took over any rider account. Now
  requires admin/manager/executive auth.

Correctness
- Date ranges compared the container's UTC clock against timestamps the DB
  writes as IST wall-clock (DSN sets TimeZone=Asia/Kolkata), so "today so far"
  ended 5h30m in the past and silently dropped everything created after noon
  IST from every report. Sets TZ in the image and adds utils.DBNow/DBToday,
  which stay correct regardless of container timezone.
- CreateMiler never set Configid, so console-created riders got the column
  default of 1 while LoginMiler looks up configid 1001 — every such rider was
  unable to log in, reported as "no miler account found".
- Delivery wrote no consignment history row, so a tracking timeline never
  showed the parcel arriving.

Features
- Delivery OTP is now real (crypto/rand, issued to the receiver, verified and
  cleared on delivery) but opt-in per client via Tenant.Requiredeliveryotp,
  defaulting off — friction worth it for a courier parcel, not a food order.
- Express bookings accept pickuplocationid, so the console can name a client
  site (a DailyGrubs kitchen) instead of retyping its address; validated
  against the tenant and carried through to the consignment.
- TenantLocation.Locationname, miler tenantid/hubid, Nagercoil (629) opened.
- PUT /miler/availability accepts both "status" and "availabilitystatus", and
  /miler/location no longer drops speed/heading — both were contract
  mismatches against the doc the Flutter dev was given.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 18:16:56 +05:30
e1fd4dc5d0 docs: record build/vet verification and commit c272a33 in CLAUDE.md
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 12:31:34 +05:30
57376a466e chore: remove doormile-taskboard.html scratch file
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 12:24:29 +05:30
c272a33fa6 feat: 14 new endpoints closing jupiter->Doormile API gaps, plus two tenant-scoping bug fixes
New endpoints:
- Admin: partner CRUD (GET/POST /admin/partners, GET/PUT/DELETE
  /admin/partners/:id), bulk express booking create
  (POST /admin/expressbooking/bulk), bulk cancel
  (POST /admin/bookings/bulk-cancel), reports (GET /admin/reports),
  password change (PUT /admin/profile/password), miler notify
  (POST /admin/milers/:id/notify)
- Miler: PIN reset (POST /miler/reset-pin), cancel assignment
  (POST /miler/bookings/:bookingid/cancel), skip delivery
  (POST /miler/consignments/:id/skip)
- Hub: batch assign (POST /hub/bookings/batch-assign) - greedy
  nearest-rider queue clearing, capped per rider

Bug fixes:
- BookingPickupComplete now sets Consignment.Tenantid from the
  booking's tenant instead of the completing miler's own tenant
  (fixes cross-tenant shipment mis-attribution)
- GetHubUnassignedBookings/GetHubBookingsRange now scoped via
  scopeBookingsToOwnTenant (fixes partner hub staff seeing other
  tenants' bookings)

Also: CRM booking routes renamed to expressbooking to end the naming
collision with the separate CRM clients feature; PickupBooking gains
nullable Tenantid; adds CLAUDE.md project memory.

Verified: go build ./... and go vet ./... both clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 12:22:39 +05:30
Suriya
77a723e047 internal modifications 2026-08-04 20:44:42 +05:30
Suriya
588f84c344 docs: runbook for creating a test booking and assigning a miler
Captures the working request bodies for the customer login/booking and the
admin/hub assign-miler endpoints, plus the constraints that are easy to hit
and hard to diagnose:

- CityGate only accepts pickup pincodes in 641/600/560/500
- hub assign-miler 403s unless milerprofiles.hubid matches the calling hub,
  and most milers have hubid NULL
- CreateCustomerBooking auto-assigns in the background, so a booking is often
  already on a miler before you assign one
- the routing watchdog sweeps unaccepted assignments within ~a minute and may
  re-assign under a new bookingassignmentid, so accept IDs must be re-read
- reject takes its reason in the body, not the query string

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 12:38:05 +05:30
Suriya
a2dc55e4f3 feat: allow https://hub.doormile.com in CORS
The hub console has its own subdomain; without it browsers block every
cross-origin call from the hub UI.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 12:18:16 +05:30
Suriya
2c26cbe4ba fix: panic recovery, rate limiting, transaction error handling, pagination
Hardening pass over the API surface. No route's auth requirements change.

Resilience:
- Add recover middleware. There was none, so an unhandled panic in any
  handler propagated out of the process instead of becoming a 500.
- Add a centralized ErrorHandler so errors and recovered panics return the
  same {success,message} envelope as the utils helpers, not Fiber's default
  plain-text body. 5xx responses are logged with method and path.

Rate limiting:
- Global 300/min per IP as an abuse backstop, exempting health/readiness
  probes and websocket upgrades.
- 10/min shared across every credential endpoint (customer/miler/admin/hub
  login, verify-pin, reset-pin, email OTP). PINs are 4 digits, so the whole
  keyspace was previously walkable in seconds. One shared limiter instance
  means rotating between endpoints doesn't reset the budget.
- Add TRUSTED_PROXIES config. Limits key on c.IP(), which behind a TLS
  terminator is the proxy, collapsing every client into one bucket. When set,
  X-Forwarded-For is honoured only from those proxies so the header can't be
  spoofed to dodge the limit. Logs a warning when unset.

Transactions:
- Check the error on all 51 previously-unchecked tx.Save/Create/Delete/
  Model(...).Update/Commit calls across 6 controllers. A failed write inside
  a transaction was silently ignored and the request still reported success;
  an unchecked Commit could fail with the caller told everything worked.
  Each site now rolls back and returns a specific message.

Pagination:
- Add utils.ParsePage/Paginated, reusing the pageno/pagesize convention
  GetAdminBookings already established. Default 500, hard cap 1000.
- Apply to the previously unbounded consignments, tripsheets, exceptions,
  app-users and clients endpoints. Defaults are high so existing consoles
  that don't paginate keep working; the cap only stops a growing table from
  being loaded wholesale. total is now a real COUNT, not len(data).
- GetClients also loaded the entire auth table to join in memory; it now
  fetches only the current page's rows.

Tests (first in the repo):
- Extract the hyperlocal pincode rule out of BookingPickupComplete into
  isHyperlocal so it is testable, covering the short/empty pincode fallback.
- Cover calculateVolumetricWeight and the ParsePage clamping rules.

Repo hygiene:
- Tag scratch/*.go with //go:build ignore. Each declared its own main(), so
  `go build ./...` failed on redeclaration; it now passes repo-wide.
- Untrack scratch/node_modules (216 files) and ignore node_modules, test
  artifacts, and the `doormile` binary `go build .` emits.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 12:13:39 +05:30
Suriya
a2b9268189 fix: miler assignment lifecycle, pickup hub resolution, and hyperlocal delivery
Bugs found during live Coimbatore testing against production:

- GetMilerAssignments returned every assignment ever made to a miler with
  no status filter, so weeks-old Rejected assignments still showed up as
  actionable in the app. Now filters to Assigned/Accepted only.
- AcceptMilerAssignment overwrote assignmentstatus unconditionally, letting
  a stale Rejected assignment be silently reactivated (and pushing its
  booking back to Pickup_Scheduled). Now 400s unless currently Assigned,
  reporting the actual status.
- RejectMilerAssignment read `reason` from the query string instead of the
  JSON body, contradicting the API contract and every sibling endpoint.
- BookingPickupComplete resolved the origin hub via db.First(&hub) with no
  Where clause — i.e. the lowest hub ID in the table, unrelated to the
  booking or miler. Now uses the miler's own MilerProfile.Hubid, falling
  back to the old behaviour with a warning only when unassigned.
- No code path ever set a consignment to Out_for_Delivery, making
  MilerDeliverConsignment unreachable. BookingPickupComplete now goes
  straight to Out_for_Delivery when pickup and delivery pincodes share a
  3-digit postal-area prefix (same-miler hyperlocal), reusing the
  hubPincodePrefix convention. Cross-hub still lands at Inwarded_at_Hub.

Also allow https://app.doormile.com in CORS, and drop a stray Windows-path
log file that was committed by accident.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 11:04:01 +05:30
6b3c95c259 feat: miler duty/break tracking, delivery confirmation, earnings, notifications, and support
Adds MilerDutyLog, MilerBreakLog, MilerSupportTicket models and earnings
fields on BookingAssignment, plus a new milerAppController.go wiring 10
endpoints under /api/v1/miler for the rider app: duty start/end/status,
break start/end, own-bookings listing, delivery confirmation (writes
DeliveryProof, completes the assignment, publishes booking.outcome via
NATS, and pushes an FCM delivery notification), earnings summaries
(daily/weekly/monthly), synthetic notifications, and support tickets.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 11:25:49 +05:30
1c24e93a7a feat: date-range endpoints for hub inbound, bookings, and batches
Adds GET /hub/inbound, GET /hub/bookings (both new), and extends the
existing GET /hub/batches with optional from/to (YYYY-MM-DD, inclusive)
query params, backing the Hub Console's date-range picker on the Pickup
Requests, Receive Parcels, and Dispatch & Transfer pages. Reuses the same
range-parsing helper (renamed from parseHubDashboardRange to
parseHubDateRange) added for GET /hub/dashboard, defaulting to today when
omitted. The existing live endpoints (/inbound/today, /bookings/unassigned)
are untouched.

GET /hub/bookings also surfaces each booking's assignment status, mapped
to a small vocabulary (pending/assigned/picked_up/delivered/cancelled) via
the new hubBookingDisplayStatus, plus milername when assigned.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 15:14:36 +05:30
624891b7bd fix: GET /hub/dashboard now honors from/to date range
Previously always scoped parcels_received_today, batches_sent_today,
exceptions, and parcels_sorted to "since midnight today", ignoring any
from/to query params — so any non-default range silently returned
zeros. Now parses optional from/to (YYYY-MM-DD, same semantics as
GET /hub/report) and defaults to today when omitted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 12:36:49 +05:30
5a2da49c35 feat: PATCH /admin/customers/:id — customer update endpoint
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 12:10:49 +05:30
d7c0f35ffe fix: admin console endpoints
- Remove scratch/check_users.go
- GetAdminBookings: LIMIT/OFFSET enforced, returns pageno/pagesize/pages
- GetAdminCustomers: new B2C appcustomers list with booking count
- AdminCancelBooking: cancel + miler release + FCM + NATS event
2026-07-08 20:31:25 +05:30
a30713c633 Add weight field to GetHubInboundToday response
Frontend inbound page needs it; every other field was already there.
2026-07-07 16:42:40 +05:30
808ac953a1 new changes in hub api messages 2026-07-07 12:47:26 +05:30
707323b68c feat: hub console backend — complete API surface 2026-07-04 16:14:12 +05:30
c8adaf7815 hub apis 2026-07-04 11:10:52 +05:30
bd6427f5db agentic mode 2026-06-30 12:03:04 +05:30
7c55b523af Add AI agent decision memory layer with pgvector similarity search
- models/agentdecision.go: AgentDecision GORM model (context/decision as jsonb, reasoning as text)
- migrations/migrate.go: AutoMigrate AgentDecision then ALTER TABLE to add vector(1536) column and CREATE ivfflat index via raw SQL
- controllers/agentDecisionController.go: CreateAgentDecision, FindSimilarDecisions (cosine distance), UpdateDecisionOutcome
- routes/routes.go: three routes under /api/v1/internal (InternalKeyAuth applied at group level)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 11:57:53 +05:30
9d409a0d85 Fix 9 backend bugs: pricing, zones, geocoding, device tokens, assignment retry
- pricingid null: lookupDoormilePrice now returns matched rule ID; wired to BookingServiceOption.Pricingid
- Zone rename: Interstate→Regional, OtherState→National throughout (code + DB migrated)
- Zone from pincodes: CheckPrice now accepts pickup_pincode+delivery_pincode and auto-resolves zone
- Delivery geocoding: pincodeToLatLon() maps 3-digit prefix to city coords when lat/lon are 0
- Device tokens: device_token field added to PinVerify DTOs; saved on both customer and miler login
- Assignment retry: RejectMilerAssignment now re-triggers AssignCustomerMiler/AssignCRMMiler immediately
- Provider empty B2C: defaults to Doormile when no pricing provider row matches
- City gate 422→400: StatusUnprocessableEntity corrected to StatusBadRequest
- Miler GPS 0,0: WS tracking falls back to MilerProfile DB coords when Redis key is expired

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 11:47:41 +05:30
c91c887726 Add assignment engine, FCM, WebSockets, city gate, and internal APIs
- internal/assignment: GEORADIUS miler assignment with retry/escalation,
  customer-side provider scoring, FCM notifications on assign
- internal/notify: Firebase Admin SDK (FCM) client initialisation
- internal/ws: WebSocket handlers for live parcel tracking and
  customer↔miler chat
- middlewares: city gate (pincode prefix validation), internal API key
  auth, WebSocket JWT auth
- controllers: InternalNotify + InternalReassign for machine-to-machine
  calls; pricing helpers wired into CreateCustomerBooking and CreateCRMBooking
- routes: /internal/*, /ws/bookings/:id/track, /ws/bookings/:id/chat
- models/users, models/doormile_pricing: new fields for device tokens,
  assignment state, pricing bands
- seed_data.sql: initial pricing seed rows

.env and Firebase service-account JSON intentionally excluded.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 12:31:53 +05:30
c577d47b75 Initial commit including .env 2026-06-22 17:43:40 +05:30