Commit Graph

18 Commits

Author SHA1 Message Date
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