@burdenoff/microfe-kadaikodi 2026.1126.1 → 2026.1127.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_virtual/_rolldown/runtime.js +12 -0
- package/dist/kadaikodi/components/CourierLocationSharingCard.d.ts +10 -0
- package/dist/kadaikodi/components/CourierLocationSharingCard.js +52 -0
- package/dist/kadaikodi/components/CourierLocationSharingCard.js.map +1 -0
- package/dist/kadaikodi/components/DropoffPinField.d.ts +16 -0
- package/dist/kadaikodi/components/DropoffPinField.js +67 -0
- package/dist/kadaikodi/components/DropoffPinField.js.map +1 -0
- package/dist/kadaikodi/components/LiveTrackingMap.d.ts +27 -0
- package/dist/kadaikodi/components/LiveTrackingMap.js +74 -0
- package/dist/kadaikodi/components/LiveTrackingMap.js.map +1 -0
- package/dist/kadaikodi/hooks/useAppointmentsApi.js +42 -40
- package/dist/kadaikodi/hooks/useAppointmentsApi.js.map +1 -1
- package/dist/kadaikodi/hooks/useCourierLocationSharing.d.ts +24 -0
- package/dist/kadaikodi/hooks/useCourierLocationSharing.js +54 -0
- package/dist/kadaikodi/hooks/useCourierLocationSharing.js.map +1 -0
- package/dist/kadaikodi/hooks/useTrackingApi.d.ts +63 -0
- package/dist/kadaikodi/hooks/useTrackingApi.js +37 -0
- package/dist/kadaikodi/hooks/useTrackingApi.js.map +1 -0
- package/dist/kadaikodi/pages/customer/CheckoutPage.js +222 -213
- package/dist/kadaikodi/pages/customer/CheckoutPage.js.map +1 -1
- package/dist/kadaikodi/pages/customer/OrderTrackingPage.d.ts +4 -0
- package/dist/kadaikodi/pages/customer/OrderTrackingPage.js +274 -252
- package/dist/kadaikodi/pages/customer/OrderTrackingPage.js.map +1 -1
- package/dist/kadaikodi/pages/customer/shared.d.ts +0 -13
- package/dist/kadaikodi/pages/customer/shared.js +16 -119
- package/dist/kadaikodi/pages/customer/shared.js.map +1 -1
- package/dist/kadaikodi/pages/worker/TaskDetailsPage.d.ts +3 -2
- package/dist/kadaikodi/pages/worker/TaskDetailsPage.js +67 -65
- package/dist/kadaikodi/pages/worker/TaskDetailsPage.js.map +1 -1
- package/dist/kadaikodi/utils/deviceGeolocation.d.ts +46 -0
- package/dist/kadaikodi/utils/deviceGeolocation.js +71 -0
- package/dist/kadaikodi/utils/deviceGeolocation.js.map +1 -0
- package/dist/kadaikodi/utils/leaflet.d.ts +8 -0
- package/dist/kadaikodi/utils/leaflet.js +11 -0
- package/dist/kadaikodi/utils/leaflet.js.map +1 -0
- package/dist/node_modules/leaflet/dist/leaflet-src.js +4535 -0
- package/dist/node_modules/leaflet/dist/leaflet-src.js.map +1 -0
- package/package.json +4 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAppointmentsApi.js","names":["APPOINTMENT_FIELDS","SETTINGS_FIELDS","ACTIVE_APPOINTMENT_STATUSES","formatAppointmentTime","iso","options","timezone","formatServiceAddress","address","parts","key","value","customerCanChangeAppointment","appointment","now","cancellationCutoffHours","calendarDateIn","instant","PROVIDER_QUEUE_POLL_MS","ACTIVE_APPOINTMENT_POLL_MS","PROVIDER_QUEUE_PAGE_SIZE","PROVIDER_QUEUE_MAX_PAGES","useAppointmentSettings","useKadaikodi","useQuery","providerId","kadaikodiQuery","apiGatewayUrl","useAvailableSlots","offeringId","date","useOrderAppointment","orderId","query","useProviderAppointments","appointments","status","page","rows","rank","byId","seen","a","b","useInvalidateAppointments","queryClient","useQueryClient","useBookAppointment","invalidate","useMutation","useRescheduleAppointment","useCancelAppointment","useUpdateAppointmentStatus","useUpsertAppointmentSettings","settings"],"sources":["../../../src/kadaikodi/hooks/useAppointmentsApi.ts"],"sourcesContent":["/**\n * Service appointment hooks (BOFF-3965).\n *\n * Slot availability, booking, reschedule/cancel and the provider appointment\n * queue all come from wspace-kadaikodi-svc; nothing here computes slots on the\n * client. Every appointment is paired with an order, so mutations also\n * invalidate the order caches the existing pages read.\n *\n * @module kadaikodi/hooks\n */\n\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useKadaikodi } from '../context';\nimport { kadaikodiQuery } from './useKadaikodiApi';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type AppointmentStatus =\n 'BOOKED' | 'CONFIRMED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED' | 'NO_SHOW';\n\n/** Statuses a provider can move an appointment to. */\nexport type ProviderAppointmentStatus = Exclude<AppointmentStatus, 'BOOKED'>;\n\nexport type AppointmentTiming = 'SCHEDULED' | 'COME_NOW';\n\nexport interface ServiceAppointment {\n id: string;\n providerId: string;\n offeringId: string;\n customerId: string;\n orderId: string | null;\n timing: AppointmentTiming;\n status: AppointmentStatus;\n scheduledAt: string;\n endsAt: string;\n durationMinutes: number;\n serviceAddress: Record<string, unknown> | null;\n contactPhone: string | null;\n notes: string | null;\n rescheduleCount: number;\n cancellationReason: string | null;\n offering: { id: string; name: string; price: number } | null;\n}\n\nexport interface AppointmentSlot {\n startsAt: string;\n endsAt: string;\n available: boolean;\n remainingCapacity: number;\n}\n\nexport interface AvailableSlots {\n date: string;\n timezone: string;\n durationMinutes: number;\n slots: AppointmentSlot[];\n nextAvailableAt: string | null;\n}\n\nexport interface AppointmentSettings {\n providerId: string;\n slotIntervalMinutes: number;\n capacityPerSlot: number;\n bufferMinutes: number;\n minLeadMinutes: number;\n advanceBookingDays: number;\n cancellationCutoffHours: number;\n autoConfirm: boolean;\n timezone: string;\n blackoutDates: string[];\n isCustomized: boolean;\n bookableDays: string[];\n}\n\nexport type AppointmentSettingsInput = Partial<\n Omit<AppointmentSettings, 'providerId' | 'isCustomized' | 'bookableDays'>\n>;\n\nexport interface BookAppointmentInput {\n offeringId: string;\n timing: AppointmentTiming;\n scheduledAt?: string;\n serviceAddress?: Record<string, unknown>;\n contactPhone?: string;\n notes?: string;\n paymentMethod?: string;\n}\n\nconst APPOINTMENT_FIELDS = `\n id providerId offeringId customerId orderId timing status scheduledAt endsAt durationMinutes\n serviceAddress contactPhone notes rescheduleCount cancellationReason\n offering { id name price }\n`;\n\nconst SETTINGS_FIELDS = `\n providerId slotIntervalMinutes capacityPerSlot bufferMinutes minLeadMinutes advanceBookingDays\n cancellationCutoffHours autoConfirm timezone blackoutDates isCustomized bookableDays\n`;\n\n/** Statuses that still occupy the provider's calendar. */\nexport const ACTIVE_APPOINTMENT_STATUSES: readonly AppointmentStatus[] = [\n 'BOOKED',\n 'CONFIRMED',\n 'IN_PROGRESS',\n];\n\n/**\n * Format an instant in the provider's timezone so customers and providers see\n * the same wall-clock time regardless of the device timezone.\n */\nexport const formatAppointmentTime = (\n iso: string,\n timezone: string,\n options: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: '2-digit' }\n): string => new Date(iso).toLocaleString('en-IN', { ...options, timeZone: timezone });\n\n/**\n * One-line service address for display (street, landmark, instructions as\n * sent by DirectServiceBookingPage, plus area/city when present), or null.\n */\nexport const formatServiceAddress = (address: Record<string, unknown> | null): string | null => {\n if (!address) return null;\n const parts = ['street', 'area', 'city', 'landmark', 'instructions']\n .map((key) => address[key])\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .map((value) => value.trim());\n return parts.length > 0 ? parts.join(', ') : null;\n};\n\n/**\n * Whether the customer may still cancel or reschedule, mirroring the service\n * rule: a scheduled booking (BOOKED or CONFIRMED) until `cancellationCutoffHours`\n * before its start; a come-now request only while it is unconfirmed and its\n * window has not ended.\n */\nexport const customerCanChangeAppointment = (\n appointment: Pick<ServiceAppointment, 'status' | 'timing' | 'scheduledAt' | 'endsAt'>,\n cancellationCutoffHours: number,\n now: number\n): boolean => {\n if (appointment.status !== 'BOOKED' && appointment.status !== 'CONFIRMED') return false;\n if (appointment.timing === 'COME_NOW') {\n return appointment.status === 'BOOKED' && now < new Date(appointment.endsAt).getTime();\n }\n const cutoff = new Date(appointment.scheduledAt).getTime() - cancellationCutoffHours * 3_600_000;\n return now <= cutoff;\n};\n\n/** Calendar date (`YYYY-MM-DD`) of `instant` in `timezone`. */\nexport const calendarDateIn = (timezone: string, instant: Date = new Date()): string =>\n // en-CA formats dates as YYYY-MM-DD.\n new Intl.DateTimeFormat('en-CA', {\n timeZone: timezone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(instant);\n\n/** How often the provider queue polls for new bookings while it is open. */\nconst PROVIDER_QUEUE_POLL_MS = 30_000;\n/** How often a customer's active appointment is refreshed while it is on screen. */\nconst ACTIVE_APPOINTMENT_POLL_MS = 30_000;\n/** Page size for the provider queue (the service's maximum page size). */\nconst PROVIDER_QUEUE_PAGE_SIZE = 100;\n/** Upper bound on pages fetched per status and refresh (2,000 active appointments). */\nconst PROVIDER_QUEUE_MAX_PAGES = 20;\n\n// ============================================================================\n// Queries\n// ============================================================================\n\nexport const useAppointmentSettings = (providerId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'appointment-settings', providerId],\n queryFn: async () => {\n const result = await kadaikodiQuery<{ kadaikodiAppointmentSettings: AppointmentSettings }>(\n `query AppointmentSettings($providerId: ID!) {\n kadaikodiAppointmentSettings(providerId: $providerId) { ${SETTINGS_FIELDS} }\n }`,\n { providerId },\n apiGatewayUrl\n );\n return result.kadaikodiAppointmentSettings;\n },\n enabled: Boolean(providerId),\n });\n};\n\nexport const useAvailableSlots = (offeringId?: string, date?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'appointment-slots', offeringId, date],\n queryFn: async () => {\n const result = await kadaikodiQuery<{ kadaikodiListAvailableSlots: AvailableSlots }>(\n `query AvailableSlots($offeringId: ID!, $date: String!) {\n kadaikodiListAvailableSlots(offeringId: $offeringId, date: $date) {\n date timezone durationMinutes nextAvailableAt\n slots { startsAt endsAt available remainingCapacity }\n }\n }`,\n { offeringId, date },\n apiGatewayUrl\n );\n return result.kadaikodiListAvailableSlots;\n },\n enabled: Boolean(offeringId && date),\n });\n};\n\n/** The appointment booked with an order, or null when the order is not a service booking. */\nexport const useOrderAppointment = (orderId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'order-appointment', orderId],\n queryFn: async () => {\n const result = await kadaikodiQuery<{\n kadaikodiOrder: { id: string; appointment: ServiceAppointment | null } | null;\n }>(\n `query OrderAppointment($id: ID!) {\n kadaikodiOrder(id: $id) { id appointment { ${APPOINTMENT_FIELDS} } }\n }`,\n { id: orderId },\n apiGatewayUrl\n );\n return result.kadaikodiOrder?.appointment ?? null;\n },\n enabled: Boolean(orderId),\n // While the appointment is still active the provider may confirm, start,\n // cancel or complete it from another session: poll so the status and the\n // customer's actions stay current. Finished or non-appointment orders stop.\n refetchInterval: (query) => {\n const appointment = query.state.data;\n return appointment && ACTIVE_APPOINTMENT_STATUSES.includes(appointment.status)\n ? ACTIVE_APPOINTMENT_POLL_MS\n : false;\n },\n });\n};\n\n/**\n * Every active (BOOKED, CONFIRMED, IN_PROGRESS) appointment of a provider,\n * soonest first. Queried per status with no date bound, so overdue bookings\n * from earlier days (e.g. a service that ran past midnight) stay manageable.\n */\nexport const useProviderAppointments = (providerId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'provider-appointments', providerId],\n queryFn: async () => {\n const appointments: ServiceAppointment[] = [];\n for (const status of ACTIVE_APPOINTMENT_STATUSES) {\n // Walk every page (the service caps a page at 100 rows).\n for (let page = 0; page < PROVIDER_QUEUE_MAX_PAGES; page++) {\n const result = await kadaikodiQuery<{\n kadaikodiProviderAppointments: ServiceAppointment[];\n }>(\n `query ProviderAppointments($providerId: ID!, $status: KadaikodiAppointmentStatus, $pagination: KadaikodiPaginationInput) {\n kadaikodiProviderAppointments(providerId: $providerId, status: $status, pagination: $pagination) {\n ${APPOINTMENT_FIELDS}\n }\n }`,\n {\n providerId,\n status,\n pagination: {\n limit: PROVIDER_QUEUE_PAGE_SIZE,\n offset: page * PROVIDER_QUEUE_PAGE_SIZE,\n },\n },\n apiGatewayUrl\n );\n const rows = result.kadaikodiProviderAppointments;\n appointments.push(...rows);\n if (rows.length < PROVIDER_QUEUE_PAGE_SIZE) break;\n }\n }\n // An appointment can advance (e.g. BOOKED -> CONFIRMED) between the\n // per-status requests and appear twice; keep the most advanced record.\n const rank = (status: AppointmentStatus): number =>\n ACTIVE_APPOINTMENT_STATUSES.indexOf(status);\n const byId = new Map<string, ServiceAppointment>();\n for (const appointment of appointments) {\n const seen = byId.get(appointment.id);\n if (!seen || rank(appointment.status) > rank(seen.status)) {\n byId.set(appointment.id, appointment);\n }\n }\n return [...byId.values()].sort(\n (a, b) => new Date(a.scheduledAt).getTime() - new Date(b.scheduledAt).getTime()\n );\n },\n enabled: Boolean(providerId),\n // Poll so incoming bookings appear without a reload.\n refetchInterval: PROVIDER_QUEUE_POLL_MS,\n });\n};\n\n// ============================================================================\n// Mutations\n// ============================================================================\n\nconst useInvalidateAppointments = () => {\n const queryClient = useQueryClient();\n return () => {\n for (const key of [\n 'appointment-slots',\n 'order-appointment',\n 'provider-appointments',\n 'orders',\n 'order',\n ]) {\n void queryClient.invalidateQueries({ queryKey: ['kadaikodi', key] });\n }\n };\n};\n\nexport const useBookAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async (input: BookAppointmentInput) => {\n const result = await kadaikodiQuery<{ kadaikodiBookAppointment: ServiceAppointment }>(\n `mutation BookAppointment($input: KadaikodiBookAppointmentInput!) {\n kadaikodiBookAppointment(input: $input) { ${APPOINTMENT_FIELDS} }\n }`,\n { input },\n apiGatewayUrl\n );\n return result.kadaikodiBookAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useRescheduleAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({ id, scheduledAt }: { id: string; scheduledAt: string }) => {\n const result = await kadaikodiQuery<{ kadaikodiRescheduleAppointment: ServiceAppointment }>(\n `mutation RescheduleAppointment($id: ID!, $scheduledAt: DateTime!) {\n kadaikodiRescheduleAppointment(id: $id, scheduledAt: $scheduledAt) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, scheduledAt },\n apiGatewayUrl\n );\n return result.kadaikodiRescheduleAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useCancelAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({ id, reason }: { id: string; reason?: string }) => {\n const result = await kadaikodiQuery<{ kadaikodiCancelAppointment: ServiceAppointment }>(\n `mutation CancelAppointment($id: ID!, $reason: String) {\n kadaikodiCancelAppointment(id: $id, reason: $reason) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, reason },\n apiGatewayUrl\n );\n return result.kadaikodiCancelAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useUpdateAppointmentStatus = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({\n id,\n status,\n reason,\n }: {\n id: string;\n status: ProviderAppointmentStatus;\n reason?: string;\n }) => {\n const result = await kadaikodiQuery<{ kadaikodiUpdateAppointmentStatus: ServiceAppointment }>(\n `mutation UpdateAppointmentStatus($id: ID!, $status: KadaikodiAppointmentProviderStatus!, $reason: String) {\n kadaikodiUpdateAppointmentStatus(id: $id, status: $status, reason: $reason) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, status, reason },\n apiGatewayUrl\n );\n return result.kadaikodiUpdateAppointmentStatus;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useUpsertAppointmentSettings = () => {\n const queryClient = useQueryClient();\n const { apiGatewayUrl } = useKadaikodi();\n return useMutation({\n mutationFn: async ({\n providerId,\n input,\n }: {\n providerId: string;\n input: AppointmentSettingsInput;\n }) => {\n const result = await kadaikodiQuery<{\n kadaikodiUpsertAppointmentSettings: AppointmentSettings;\n }>(\n `mutation UpsertAppointmentSettings($providerId: ID!, $input: KadaikodiAppointmentSettingsInput!) {\n kadaikodiUpsertAppointmentSettings(providerId: $providerId, input: $input) { ${SETTINGS_FIELDS} }\n }`,\n { providerId, input },\n apiGatewayUrl\n );\n return result.kadaikodiUpsertAppointmentSettings;\n },\n onSuccess: (settings) => {\n queryClient.setQueryData(\n ['kadaikodi', 'appointment-settings', settings.providerId],\n settings\n );\n void queryClient.invalidateQueries({ queryKey: ['kadaikodi', 'appointment-slots'] });\n },\n });\n};\n"],"mappings":";;;;;AA2FA,IAAMA,IAAqB,4MAMrBC,IAAkB,gMAMXC,IAA4D;CACvE;CACA;CACA;AACF,GAMaC,KACX,GACA,GACA,IAAsC;CAAE,MAAM;CAAW,QAAQ;AAAU,MAChE,IAAI,KAAKC,CAAG,CAAC,CAAC,eAAe,SAAS;CAAE,GAAGC;CAAS,UAAUC;AAAS,CAAC,GAMxEC,KAAwB,MAA2D;CAC9F,IAAI,CAACC,GAAS,OAAO;CACrB,IAAMC,IAAQ;EAAC;EAAU;EAAQ;EAAQ;EAAY;CAAc,CAAC,CACjE,KAAK,MAAQD,EAAQE,EAAI,CAAC,CAC1B,QAAQ,MAA2B,OAAOC,KAAU,YAAYA,EAAM,KAAK,CAAC,CAAC,SAAS,CAAC,CAAC,CACxF,KAAK,MAAUA,EAAM,KAAK,CAAC;CAC9B,OAAOF,EAAM,SAAS,IAAIA,EAAM,KAAK,IAAI,IAAI;AAC/C,GAQaG,KACX,GACA,GACA,MAEIC,EAAY,WAAW,YAAYA,EAAY,WAAW,cAAoB,KAC9EA,EAAY,WAAW,aAClBA,EAAY,WAAW,YAAYC,IAAM,IAAI,KAAKD,EAAY,MAAM,CAAC,CAAC,QAAQ,IAGhFC,KADQ,IAAI,KAAKD,EAAY,WAAW,CAAC,CAAC,QAAQ,IAAIE,IAA0B,MAK5EC,KAAkB,GAAkB,oBAAgB,IAAI,KAAK,MAExE,IAAI,KAAK,eAAe,SAAS;CAC/B,UAAUV;CACV,MAAM;CACN,OAAO;CACP,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OAAOK,EAAY;EACjB,YAAY,OAAO,EAAE,OAAI,sBAQhB,MAPcvB,EACnB;iFACyE1B,EAAmB;YAE5F;GAAE;GAAI;EAAY,GAClB2B,CACF,EAAA,CACc;EAEhB,WAAWqB;CACb,CAAC;AACH,GAEaG,UAA6B;CACxC,IAAM,EAAE,qBAAkB5B,EAAa,GACjCyB,IAAaJ,EAA0B;CAC7C,OAAOK,EAAY;EACjB,YAAY,OAAO,EAAE,OAAI,iBAQhB,MAPcvB,EACnB;mEAC2D1B,EAAmB;YAE9E;GAAE;GAAI;EAAO,GACb2B,CACF,EAAA,CACc;EAEhB,WAAWqB;CACb,CAAC;AACH,GAEaI,UAAmC;CAC9C,IAAM,EAAE,qBAAkB7B,EAAa,GACjCyB,IAAaJ,EAA0B;CAC7C,OAAOK,EAAY;EACjB,YAAY,OAAO,EACjB,OACA,WACA,iBAaO,MAPcvB,EACnB;0FACkF1B,EAAmB;YAErG;GAAE;GAAI;GAAQ;EAAO,GACrB2B,CACF,EAAA,CACc;EAEhB,WAAWqB;CACb,CAAC;AACH,GAEaK,UAAqC;CAChD,IAAMR,IAAcC,EAAe,GAC7B,EAAE,qBAAkBvB,EAAa;CACvC,OAAO0B,EAAY;EACjB,YAAY,OAAO,EACjB,eACA,gBAcO,MATcvB,EAGnB;yFACiFzB,EAAgB;YAEjG;GAAE;GAAY;EAAM,GACpB0B,CACF,EAAA,CACc;EAEhB,YAAY,MAAa;GAKvB,AAJAkB,EAAY,aACV;IAAC;IAAa;IAAwBS,EAAS;GAAU,GACzDA,CACF,GACAT,EAAiB,kBAAkB,EAAE,UAAU,CAAC,aAAa,mBAAmB,EAAE,CAAC;EACrF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"useAppointmentsApi.js","names":["APPOINTMENT_FIELDS","SETTINGS_FIELDS","ACTIVE_APPOINTMENT_STATUSES","formatAppointmentTime","iso","options","timezone","formatServiceAddress","address","parts","key","value","customerCanChangeAppointment","appointment","now","cancellationCutoffHours","calendarDateIn","instant","PROVIDER_QUEUE_POLL_MS","ACTIVE_APPOINTMENT_POLL_MS","PROVIDER_QUEUE_PAGE_SIZE","PROVIDER_QUEUE_MAX_PAGES","useAppointmentSettings","useKadaikodi","useQuery","providerId","kadaikodiQuery","apiGatewayUrl","useAvailableSlots","offeringId","date","useOrderAppointment","orderId","query","useProviderAppointments","appointments","status","page","rows","rank","byId","seen","a","b","useInvalidateAppointments","queryClient","useQueryClient","useBookAppointment","invalidate","useMutation","useRescheduleAppointment","useCancelAppointment","useUpdateAppointmentStatus","useUpsertAppointmentSettings","clearGraphqlFetchResponseCache","settings"],"sources":["../../../src/kadaikodi/hooks/useAppointmentsApi.ts"],"sourcesContent":["/**\n * Service appointment hooks (BOFF-3965).\n *\n * Slot availability, booking, reschedule/cancel and the provider appointment\n * queue all come from wspace-kadaikodi-svc; nothing here computes slots on the\n * client. Every appointment is paired with an order, so mutations also\n * invalidate the order caches the existing pages read.\n *\n * @module kadaikodi/hooks\n */\n\nimport { clearGraphqlFetchResponseCache } from '@burdenoff/fe-libs/shared/graphql';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useKadaikodi } from '../context';\nimport { kadaikodiQuery } from './useKadaikodiApi';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type AppointmentStatus =\n 'BOOKED' | 'CONFIRMED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED' | 'NO_SHOW';\n\n/** Statuses a provider can move an appointment to. */\nexport type ProviderAppointmentStatus = Exclude<AppointmentStatus, 'BOOKED'>;\n\nexport type AppointmentTiming = 'SCHEDULED' | 'COME_NOW';\n\nexport interface ServiceAppointment {\n id: string;\n providerId: string;\n offeringId: string;\n customerId: string;\n orderId: string | null;\n timing: AppointmentTiming;\n status: AppointmentStatus;\n scheduledAt: string;\n endsAt: string;\n durationMinutes: number;\n serviceAddress: Record<string, unknown> | null;\n contactPhone: string | null;\n notes: string | null;\n rescheduleCount: number;\n cancellationReason: string | null;\n offering: { id: string; name: string; price: number } | null;\n}\n\nexport interface AppointmentSlot {\n startsAt: string;\n endsAt: string;\n available: boolean;\n remainingCapacity: number;\n}\n\nexport interface AvailableSlots {\n date: string;\n timezone: string;\n durationMinutes: number;\n slots: AppointmentSlot[];\n nextAvailableAt: string | null;\n}\n\nexport interface AppointmentSettings {\n providerId: string;\n slotIntervalMinutes: number;\n capacityPerSlot: number;\n bufferMinutes: number;\n minLeadMinutes: number;\n advanceBookingDays: number;\n cancellationCutoffHours: number;\n autoConfirm: boolean;\n timezone: string;\n blackoutDates: string[];\n isCustomized: boolean;\n bookableDays: string[];\n}\n\nexport type AppointmentSettingsInput = Partial<\n Omit<AppointmentSettings, 'providerId' | 'isCustomized' | 'bookableDays'>\n>;\n\nexport interface BookAppointmentInput {\n offeringId: string;\n timing: AppointmentTiming;\n scheduledAt?: string;\n serviceAddress?: Record<string, unknown>;\n contactPhone?: string;\n notes?: string;\n paymentMethod?: string;\n}\n\nconst APPOINTMENT_FIELDS = `\n id providerId offeringId customerId orderId timing status scheduledAt endsAt durationMinutes\n serviceAddress contactPhone notes rescheduleCount cancellationReason\n offering { id name price }\n`;\n\nconst SETTINGS_FIELDS = `\n providerId slotIntervalMinutes capacityPerSlot bufferMinutes minLeadMinutes advanceBookingDays\n cancellationCutoffHours autoConfirm timezone blackoutDates isCustomized bookableDays\n`;\n\n/** Statuses that still occupy the provider's calendar. */\nexport const ACTIVE_APPOINTMENT_STATUSES: readonly AppointmentStatus[] = [\n 'BOOKED',\n 'CONFIRMED',\n 'IN_PROGRESS',\n];\n\n/**\n * Format an instant in the provider's timezone so customers and providers see\n * the same wall-clock time regardless of the device timezone.\n */\nexport const formatAppointmentTime = (\n iso: string,\n timezone: string,\n options: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: '2-digit' }\n): string => new Date(iso).toLocaleString('en-IN', { ...options, timeZone: timezone });\n\n/**\n * One-line service address for display (street, landmark, instructions as\n * sent by DirectServiceBookingPage, plus area/city when present), or null.\n */\nexport const formatServiceAddress = (address: Record<string, unknown> | null): string | null => {\n if (!address) return null;\n const parts = ['street', 'area', 'city', 'landmark', 'instructions']\n .map((key) => address[key])\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .map((value) => value.trim());\n return parts.length > 0 ? parts.join(', ') : null;\n};\n\n/**\n * Whether the customer may still cancel or reschedule, mirroring the service\n * rule: a scheduled booking (BOOKED or CONFIRMED) until `cancellationCutoffHours`\n * before its start; a come-now request only while it is unconfirmed and its\n * window has not ended.\n */\nexport const customerCanChangeAppointment = (\n appointment: Pick<ServiceAppointment, 'status' | 'timing' | 'scheduledAt' | 'endsAt'>,\n cancellationCutoffHours: number,\n now: number\n): boolean => {\n if (appointment.status !== 'BOOKED' && appointment.status !== 'CONFIRMED') return false;\n if (appointment.timing === 'COME_NOW') {\n return appointment.status === 'BOOKED' && now < new Date(appointment.endsAt).getTime();\n }\n const cutoff = new Date(appointment.scheduledAt).getTime() - cancellationCutoffHours * 3_600_000;\n return now <= cutoff;\n};\n\n/** Calendar date (`YYYY-MM-DD`) of `instant` in `timezone`. */\nexport const calendarDateIn = (timezone: string, instant: Date = new Date()): string =>\n // en-CA formats dates as YYYY-MM-DD.\n new Intl.DateTimeFormat('en-CA', {\n timeZone: timezone,\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n }).format(instant);\n\n/** How often the provider queue polls for new bookings while it is open. */\nconst PROVIDER_QUEUE_POLL_MS = 30_000;\n/** How often a customer's active appointment is refreshed while it is on screen. */\nconst ACTIVE_APPOINTMENT_POLL_MS = 30_000;\n/** Page size for the provider queue (the service's maximum page size). */\nconst PROVIDER_QUEUE_PAGE_SIZE = 100;\n/** Upper bound on pages fetched per status and refresh (2,000 active appointments). */\nconst PROVIDER_QUEUE_MAX_PAGES = 20;\n\n// ============================================================================\n// Queries\n// ============================================================================\n\nexport const useAppointmentSettings = (providerId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'appointment-settings', providerId],\n queryFn: async () => {\n const result = await kadaikodiQuery<{ kadaikodiAppointmentSettings: AppointmentSettings }>(\n `query AppointmentSettings($providerId: ID!) {\n kadaikodiAppointmentSettings(providerId: $providerId) { ${SETTINGS_FIELDS} }\n }`,\n { providerId },\n apiGatewayUrl\n );\n return result.kadaikodiAppointmentSettings;\n },\n enabled: Boolean(providerId),\n });\n};\n\nexport const useAvailableSlots = (offeringId?: string, date?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'appointment-slots', offeringId, date],\n queryFn: async () => {\n const result = await kadaikodiQuery<{ kadaikodiListAvailableSlots: AvailableSlots }>(\n `query AvailableSlots($offeringId: ID!, $date: String!) {\n kadaikodiListAvailableSlots(offeringId: $offeringId, date: $date) {\n date timezone durationMinutes nextAvailableAt\n slots { startsAt endsAt available remainingCapacity }\n }\n }`,\n { offeringId, date },\n apiGatewayUrl\n );\n return result.kadaikodiListAvailableSlots;\n },\n enabled: Boolean(offeringId && date),\n });\n};\n\n/** The appointment booked with an order, or null when the order is not a service booking. */\nexport const useOrderAppointment = (orderId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'order-appointment', orderId],\n queryFn: async () => {\n const result = await kadaikodiQuery<{\n kadaikodiOrder: { id: string; appointment: ServiceAppointment | null } | null;\n }>(\n `query OrderAppointment($id: ID!) {\n kadaikodiOrder(id: $id) { id appointment { ${APPOINTMENT_FIELDS} } }\n }`,\n { id: orderId },\n apiGatewayUrl\n );\n return result.kadaikodiOrder?.appointment ?? null;\n },\n enabled: Boolean(orderId),\n // While the appointment is still active the provider may confirm, start,\n // cancel or complete it from another session: poll so the status and the\n // customer's actions stay current. Finished or non-appointment orders stop.\n refetchInterval: (query) => {\n const appointment = query.state.data;\n return appointment && ACTIVE_APPOINTMENT_STATUSES.includes(appointment.status)\n ? ACTIVE_APPOINTMENT_POLL_MS\n : false;\n },\n });\n};\n\n/**\n * Every active (BOOKED, CONFIRMED, IN_PROGRESS) appointment of a provider,\n * soonest first. Queried per status with no date bound, so overdue bookings\n * from earlier days (e.g. a service that ran past midnight) stay manageable.\n */\nexport const useProviderAppointments = (providerId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: ['kadaikodi', 'provider-appointments', providerId],\n queryFn: async () => {\n const appointments: ServiceAppointment[] = [];\n for (const status of ACTIVE_APPOINTMENT_STATUSES) {\n // Walk every page (the service caps a page at 100 rows).\n for (let page = 0; page < PROVIDER_QUEUE_MAX_PAGES; page++) {\n const result = await kadaikodiQuery<{\n kadaikodiProviderAppointments: ServiceAppointment[];\n }>(\n `query ProviderAppointments($providerId: ID!, $status: KadaikodiAppointmentStatus, $pagination: KadaikodiPaginationInput) {\n kadaikodiProviderAppointments(providerId: $providerId, status: $status, pagination: $pagination) {\n ${APPOINTMENT_FIELDS}\n }\n }`,\n {\n providerId,\n status,\n pagination: {\n limit: PROVIDER_QUEUE_PAGE_SIZE,\n offset: page * PROVIDER_QUEUE_PAGE_SIZE,\n },\n },\n apiGatewayUrl\n );\n const rows = result.kadaikodiProviderAppointments;\n appointments.push(...rows);\n if (rows.length < PROVIDER_QUEUE_PAGE_SIZE) break;\n }\n }\n // An appointment can advance (e.g. BOOKED -> CONFIRMED) between the\n // per-status requests and appear twice; keep the most advanced record.\n const rank = (status: AppointmentStatus): number =>\n ACTIVE_APPOINTMENT_STATUSES.indexOf(status);\n const byId = new Map<string, ServiceAppointment>();\n for (const appointment of appointments) {\n const seen = byId.get(appointment.id);\n if (!seen || rank(appointment.status) > rank(seen.status)) {\n byId.set(appointment.id, appointment);\n }\n }\n return [...byId.values()].sort(\n (a, b) => new Date(a.scheduledAt).getTime() - new Date(b.scheduledAt).getTime()\n );\n },\n enabled: Boolean(providerId),\n // Poll so incoming bookings appear without a reload.\n refetchInterval: PROVIDER_QUEUE_POLL_MS,\n });\n};\n\n// ============================================================================\n// Mutations\n// ============================================================================\n\n/**\n * After an appointment write, drop graphqlFetch's short-lived read cache before\n * invalidating: otherwise the refetches replay the pre-write responses (for up\n * to the cache TTL) and the page keeps showing the old status or slot.\n */\nconst useInvalidateAppointments = () => {\n const queryClient = useQueryClient();\n return () => {\n clearGraphqlFetchResponseCache();\n for (const key of [\n 'appointment-slots',\n 'order-appointment',\n 'provider-appointments',\n 'orders',\n 'order',\n ]) {\n void queryClient.invalidateQueries({ queryKey: ['kadaikodi', key] });\n }\n };\n};\n\nexport const useBookAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async (input: BookAppointmentInput) => {\n const result = await kadaikodiQuery<{ kadaikodiBookAppointment: ServiceAppointment }>(\n `mutation BookAppointment($input: KadaikodiBookAppointmentInput!) {\n kadaikodiBookAppointment(input: $input) { ${APPOINTMENT_FIELDS} }\n }`,\n { input },\n apiGatewayUrl\n );\n return result.kadaikodiBookAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useRescheduleAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({ id, scheduledAt }: { id: string; scheduledAt: string }) => {\n const result = await kadaikodiQuery<{ kadaikodiRescheduleAppointment: ServiceAppointment }>(\n `mutation RescheduleAppointment($id: ID!, $scheduledAt: DateTime!) {\n kadaikodiRescheduleAppointment(id: $id, scheduledAt: $scheduledAt) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, scheduledAt },\n apiGatewayUrl\n );\n return result.kadaikodiRescheduleAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useCancelAppointment = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({ id, reason }: { id: string; reason?: string }) => {\n const result = await kadaikodiQuery<{ kadaikodiCancelAppointment: ServiceAppointment }>(\n `mutation CancelAppointment($id: ID!, $reason: String) {\n kadaikodiCancelAppointment(id: $id, reason: $reason) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, reason },\n apiGatewayUrl\n );\n return result.kadaikodiCancelAppointment;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useUpdateAppointmentStatus = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const invalidate = useInvalidateAppointments();\n return useMutation({\n mutationFn: async ({\n id,\n status,\n reason,\n }: {\n id: string;\n status: ProviderAppointmentStatus;\n reason?: string;\n }) => {\n const result = await kadaikodiQuery<{ kadaikodiUpdateAppointmentStatus: ServiceAppointment }>(\n `mutation UpdateAppointmentStatus($id: ID!, $status: KadaikodiAppointmentProviderStatus!, $reason: String) {\n kadaikodiUpdateAppointmentStatus(id: $id, status: $status, reason: $reason) { ${APPOINTMENT_FIELDS} }\n }`,\n { id, status, reason },\n apiGatewayUrl\n );\n return result.kadaikodiUpdateAppointmentStatus;\n },\n onSuccess: invalidate,\n });\n};\n\nexport const useUpsertAppointmentSettings = () => {\n const queryClient = useQueryClient();\n const { apiGatewayUrl } = useKadaikodi();\n return useMutation({\n mutationFn: async ({\n providerId,\n input,\n }: {\n providerId: string;\n input: AppointmentSettingsInput;\n }) => {\n const result = await kadaikodiQuery<{\n kadaikodiUpsertAppointmentSettings: AppointmentSettings;\n }>(\n `mutation UpsertAppointmentSettings($providerId: ID!, $input: KadaikodiAppointmentSettingsInput!) {\n kadaikodiUpsertAppointmentSettings(providerId: $providerId, input: $input) { ${SETTINGS_FIELDS} }\n }`,\n { providerId, input },\n apiGatewayUrl\n );\n return result.kadaikodiUpsertAppointmentSettings;\n },\n onSuccess: (settings) => {\n // New settings change the free slots: never replay a cached slot read.\n clearGraphqlFetchResponseCache();\n queryClient.setQueryData(\n ['kadaikodi', 'appointment-settings', settings.providerId],\n settings\n );\n void queryClient.invalidateQueries({ queryKey: ['kadaikodi', 'appointment-slots'] });\n },\n });\n};\n"],"mappings":";;;;;;AA4FA,IAAMA,IAAqB,4MAMrBC,IAAkB,gMAMXC,IAA4D;CACvE;CAC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CACF,EAAA,CACc;EAEhB,WAAWqB;CACb,CAAC;AACH,GAEaI,UAAmC;CAC9C,IAAM,EAAE,qBAAkB7B,EAAa,GACjCyB,IAAaJ,EAA0B;CAC7C,OAAOK,EAAY;EACjB,YAAY,OAAO,EACjB,OACA,WACA,iBAaO,MAPcvB,EACnB;0FACkF1B,EAAmB;YAErG;GAAE;GAAI;GAAQ;EAAO,GACrB2B,CACF,EAAA,CACc;EAEhB,WAAWqB;CACb,CAAC;AACH,GAEaK,UAAqC;CAChD,IAAMR,IAAcC,EAAe,GAC7B,EAAE,qBAAkBvB,EAAa;CACvC,OAAO0B,EAAY;EACjB,YAAY,OAAO,EACjB,eACA,gBAcO,MATcvB,EAGnB;yFACiFzB,EAAgB;YAEjG;GAAE;GAAY;EAAM,GACpB0B,CACF,EAAA,CACc;EAEhB,YAAY,MAAa;GAOvB,AALA2B,EAA+B,GAC/BT,EAAY,aACV;IAAC;IAAa;IAAwBU,EAAS;GAAU,GACzDA,CACF,GACAV,EAAiB,kBAAkB,EAAE,UAAU,CAAC,aAAa,mBAAmB,EAAE,CAAC;EACrF;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Courier-side live location sharing for one order (BOFF-3962).
|
|
3
|
+
*
|
|
4
|
+
* Sharing is explicit and foreground-only: the courier switches it on, the
|
|
5
|
+
* device position is watched while the page is open, and a fix is published at
|
|
6
|
+
* most every PUBLISH_INTERVAL_MS (the service also drops fixes that arrive too
|
|
7
|
+
* close together). Leaving the page, switching it off, or the service saying
|
|
8
|
+
* the order is no longer out for delivery stops the watch.
|
|
9
|
+
*
|
|
10
|
+
* @module kadaikodi/hooks
|
|
11
|
+
*/
|
|
12
|
+
/** Minimum gap between two published fixes. */
|
|
13
|
+
export declare const PUBLISH_INTERVAL_MS = 10000;
|
|
14
|
+
export type SharingState = 'off' | 'starting' | 'sharing' | 'error';
|
|
15
|
+
/** True when a fix taken at `now` should be published after one published at `lastSentAt`. */
|
|
16
|
+
export declare const shouldPublish: (lastSentAt: number | null, now: number) => boolean;
|
|
17
|
+
export interface CourierLocationSharing {
|
|
18
|
+
state: SharingState;
|
|
19
|
+
error: string | null;
|
|
20
|
+
lastSentAt: Date | null;
|
|
21
|
+
start: () => void;
|
|
22
|
+
stop: () => void;
|
|
23
|
+
}
|
|
24
|
+
export declare function useCourierLocationSharing(orderId: string | undefined): CourierLocationSharing;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { geolocationFailureMessage as e, watchDevicePosition as t } from "../utils/deviceGeolocation.js";
|
|
2
|
+
import { usePublishCourierLocation as n } from "./useTrackingApi.js";
|
|
3
|
+
import { useCallback as r, useEffect as i, useRef as a, useState as o } from "react";
|
|
4
|
+
// src/kadaikodi/hooks/useCourierLocationSharing.ts
|
|
5
|
+
var s = 1e4, c = (e, t) => e === null || t - e >= 1e4;
|
|
6
|
+
function l(s) {
|
|
7
|
+
let l = n(), u = a(l.mutateAsync);
|
|
8
|
+
i(() => {
|
|
9
|
+
u.current = l.mutateAsync;
|
|
10
|
+
}, [l.mutateAsync]);
|
|
11
|
+
let [d, f] = o("off"), [p, m] = o(null), [h, g] = o(null), _ = a(null), v = a(null), y = a(!1), b = a(0), x = r(() => {
|
|
12
|
+
b.current += 1, _.current?.(), _.current = null, y.current = !1;
|
|
13
|
+
}, []), S = r(() => {
|
|
14
|
+
x(), f("off");
|
|
15
|
+
}, [x]), C = r((e) => {
|
|
16
|
+
x(), m(e), f("error");
|
|
17
|
+
}, [x]), w = r(() => {
|
|
18
|
+
if (!s) return;
|
|
19
|
+
x();
|
|
20
|
+
let n = b.current;
|
|
21
|
+
v.current = null, m(null), f("starting"), t((e) => {
|
|
22
|
+
if (n !== b.current || y.current) return;
|
|
23
|
+
let t = Date.now();
|
|
24
|
+
c(v.current, t) && (y.current = !0, u.current({
|
|
25
|
+
orderId: s,
|
|
26
|
+
fix: e
|
|
27
|
+
}).then(() => {
|
|
28
|
+
n === b.current && (v.current = t, g(new Date(t)), f("sharing"));
|
|
29
|
+
}).catch((e) => {
|
|
30
|
+
n === b.current && C(e instanceof Error ? e.message : "Could not share your location.");
|
|
31
|
+
}).finally(() => {
|
|
32
|
+
n === b.current && (y.current = !1);
|
|
33
|
+
}));
|
|
34
|
+
}, (t) => {
|
|
35
|
+
n === b.current && C(e(t));
|
|
36
|
+
}).then((e) => {
|
|
37
|
+
n === b.current ? _.current = e : e();
|
|
38
|
+
});
|
|
39
|
+
}, [
|
|
40
|
+
s,
|
|
41
|
+
x,
|
|
42
|
+
C
|
|
43
|
+
]);
|
|
44
|
+
return i(() => x, [s, x]), {
|
|
45
|
+
state: d,
|
|
46
|
+
error: p,
|
|
47
|
+
lastSentAt: h,
|
|
48
|
+
start: w,
|
|
49
|
+
stop: S
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export { s as PUBLISH_INTERVAL_MS, c as shouldPublish, l as useCourierLocationSharing };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=useCourierLocationSharing.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useCourierLocationSharing.js","names":["PUBLISH_INTERVAL_MS","shouldPublish","lastSentAt","now","useCourierLocationSharing","publish","usePublishCourierLocation","publishRef","useRef","state","setState","useState","error","setError","setLastSentAt","stopWatchRef","lastSentRef","inFlightRef","sessionRef","stopWatch","useCallback","stop","fail","message","start","orderId","session","watchDevicePosition","geolocationFailureMessage","failure","stopFn","useEffect"],"sources":["../../../src/kadaikodi/hooks/useCourierLocationSharing.ts"],"sourcesContent":["/**\n * Courier-side live location sharing for one order (BOFF-3962).\n *\n * Sharing is explicit and foreground-only: the courier switches it on, the\n * device position is watched while the page is open, and a fix is published at\n * most every PUBLISH_INTERVAL_MS (the service also drops fixes that arrive too\n * close together). Leaving the page, switching it off, or the service saying\n * the order is no longer out for delivery stops the watch.\n *\n * @module kadaikodi/hooks\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport {\n type DeviceFix,\n type GeolocationFailure,\n geolocationFailureMessage,\n watchDevicePosition,\n} from '../utils/deviceGeolocation';\nimport { usePublishCourierLocation } from './useTrackingApi';\n\n/** Minimum gap between two published fixes. */\nexport const PUBLISH_INTERVAL_MS = 10_000;\n\nexport type SharingState = 'off' | 'starting' | 'sharing' | 'error';\n\n/** True when a fix taken at `now` should be published after one published at `lastSentAt`. */\nexport const shouldPublish = (lastSentAt: number | null, now: number): boolean =>\n lastSentAt === null || now - lastSentAt >= PUBLISH_INTERVAL_MS;\n\nexport interface CourierLocationSharing {\n state: SharingState;\n error: string | null;\n lastSentAt: Date | null;\n start: () => void;\n stop: () => void;\n}\n\nexport function useCourierLocationSharing(orderId: string | undefined): CourierLocationSharing {\n const publish = usePublishCourierLocation();\n const publishRef = useRef(publish.mutateAsync);\n useEffect(() => {\n publishRef.current = publish.mutateAsync;\n }, [publish.mutateAsync]);\n\n const [state, setState] = useState<SharingState>('off');\n const [error, setError] = useState<string | null>(null);\n const [lastSentAt, setLastSentAt] = useState<Date | null>(null);\n const stopWatchRef = useRef<(() => void) | null>(null);\n const lastSentRef = useRef<number | null>(null);\n const inFlightRef = useRef(false);\n const sessionRef = useRef(0);\n\n const stopWatch = useCallback(() => {\n sessionRef.current += 1;\n stopWatchRef.current?.();\n stopWatchRef.current = null;\n inFlightRef.current = false;\n }, []);\n\n const stop = useCallback(() => {\n stopWatch();\n setState('off');\n }, [stopWatch]);\n\n const fail = useCallback(\n (message: string) => {\n stopWatch();\n setError(message);\n setState('error');\n },\n [stopWatch]\n );\n\n const start = useCallback(() => {\n if (!orderId) return;\n stopWatch();\n const session = sessionRef.current;\n lastSentRef.current = null;\n setError(null);\n setState('starting');\n\n const onFix = (fix: DeviceFix) => {\n if (session !== sessionRef.current || inFlightRef.current) return;\n const now = Date.now();\n if (!shouldPublish(lastSentRef.current, now)) return;\n inFlightRef.current = true;\n publishRef\n .current({ orderId, fix })\n .then(() => {\n if (session !== sessionRef.current) return;\n lastSentRef.current = now;\n setLastSentAt(new Date(now));\n setState('sharing');\n })\n .catch((e: unknown) => {\n if (session !== sessionRef.current) return;\n // The service refuses fixes once the order is not out for delivery\n // (or the task was reassigned): stop instead of retrying forever.\n fail(e instanceof Error ? e.message : 'Could not share your location.');\n })\n .finally(() => {\n if (session === sessionRef.current) inFlightRef.current = false;\n });\n };\n const onFailure = (failure: GeolocationFailure) => {\n if (session !== sessionRef.current) return;\n fail(geolocationFailureMessage(failure));\n };\n\n void watchDevicePosition(onFix, onFailure).then((stopFn) => {\n if (session === sessionRef.current) {\n stopWatchRef.current = stopFn;\n } else {\n stopFn();\n }\n });\n }, [orderId, stopWatch, fail]);\n\n // Never keep watching after the page goes away or the order changes.\n useEffect(() => stopWatch, [orderId, stopWatch]);\n\n return { state, error, lastSentAt, start, stop };\n}\n"],"mappings":";;;;AAuBA,IAAaA,IAAsB,KAKtBC,KAAiB,GAA2B,MACvDC,MAAe,QAAQC,IAAMD,KAAA;AAU/B,SAAgBE,EAA0B,GAAqD;CAC7F,IAAMC,IAAUC,EAA0B,GACpCC,IAAaC,EAAOH,EAAQ,WAAW;CAC7C,QAAgB;EACd,EAAW,UAAUA,EAAQ;CAC/B,GAAG,CAACA,EAAQ,WAAW,CAAC;CAExB,IAAM,CAACI,GAAOC,KAAYC,EAAuB,KAAK,GAChD,CAACC,GAAOC,KAAYF,EAAwB,IAAI,GAChD,CAACT,GAAYY,KAAiBH,EAAsB,IAAI,GACxDI,IAAeP,EAA4B,IAAI,GAC/CQ,IAAcR,EAAsB,IAAI,GACxCS,IAAcT,EAAO,EAAK,GAC1BU,IAAaV,EAAO,CAAC,GAErBW,IAAYC,QAAkB;EAIlC,AAHA,EAAW,WAAW,GACtBL,EAAa,UAAU,GACvB,EAAa,UAAU,MACvB,EAAY,UAAU;CACxB,GAAG,CAAC,CAAC,GAECM,IAAOD,QAAkB;EAE7B,AADAD,EAAU,GACVT,EAAS,KAAK;CAChB,GAAG,CAACS,CAAS,CAAC,GAERG,IAAOF,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pin and the ETA all come from
|
|
5
|
+
* wspace-kadaikodi-svc (`kadaikodiOrderTracking`); nothing here estimates
|
|
6
|
+
* positions on the client. The query is polled at the interval the service
|
|
7
|
+
* returns (`pollIntervalSeconds`: fast while the order is out for delivery,
|
|
8
|
+
* slow while it is being prepared, never once it is finished) — the gateway
|
|
9
|
+
* is reached over plain HTTP GraphQL, so polling is the live-update transport.
|
|
10
|
+
*
|
|
11
|
+
* @module kadaikodi/hooks
|
|
12
|
+
*/
|
|
13
|
+
export interface GeoPoint {
|
|
14
|
+
latitude: number;
|
|
15
|
+
longitude: number;
|
|
16
|
+
}
|
|
17
|
+
export interface TrackingCourier {
|
|
18
|
+
workerRefId: string;
|
|
19
|
+
name: string;
|
|
20
|
+
phone: string | null;
|
|
21
|
+
}
|
|
22
|
+
export interface CourierLocation extends GeoPoint {
|
|
23
|
+
accuracyMeters: number | null;
|
|
24
|
+
headingDegrees: number | null;
|
|
25
|
+
speedMps: number | null;
|
|
26
|
+
recordedAt: string;
|
|
27
|
+
/** True once the courier has stopped reporting for more than two minutes. */
|
|
28
|
+
stale: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface OrderTracking {
|
|
31
|
+
orderId: string;
|
|
32
|
+
status: string;
|
|
33
|
+
/** True while the order is out for delivery and the courier position is shared. */
|
|
34
|
+
active: boolean;
|
|
35
|
+
courier: TrackingCourier | null;
|
|
36
|
+
location: CourierLocation | null;
|
|
37
|
+
origin: GeoPoint | null;
|
|
38
|
+
destination: GeoPoint | null;
|
|
39
|
+
distanceMeters: number | null;
|
|
40
|
+
etaMinutes: number | null;
|
|
41
|
+
etaAt: string | null;
|
|
42
|
+
pollIntervalSeconds: number;
|
|
43
|
+
}
|
|
44
|
+
export interface CourierFixInput extends GeoPoint {
|
|
45
|
+
accuracyMeters?: number | null;
|
|
46
|
+
headingDegrees?: number | null;
|
|
47
|
+
speedMps?: number | null;
|
|
48
|
+
/** ISO-8601 device time of the fix. */
|
|
49
|
+
recordedAt?: string | null;
|
|
50
|
+
}
|
|
51
|
+
export declare const orderTrackingQueryKey: (orderId?: string) => readonly ["kadaikodi", "order-tracking", string | undefined];
|
|
52
|
+
/**
|
|
53
|
+
* Refresh interval for a tracking result: the service's suggestion, or false
|
|
54
|
+
* (stop) once it says 0 or the order is unknown.
|
|
55
|
+
*/
|
|
56
|
+
export declare const trackingRefetchInterval: (data: OrderTracking | null | undefined) => number | false;
|
|
57
|
+
/** Live tracking view for one order; null when the caller may not see it. */
|
|
58
|
+
export declare const useOrderTracking: (orderId?: string) => import('@tanstack/react-query').UseQueryResult<OrderTracking | null, Error>;
|
|
59
|
+
/** Courier side: publish one GPS fix for an order that is out for delivery. */
|
|
60
|
+
export declare const usePublishCourierLocation: () => import('@tanstack/react-query').UseMutationResult<OrderTracking, Error, {
|
|
61
|
+
orderId: string;
|
|
62
|
+
fix: CourierFixInput;
|
|
63
|
+
}, unknown>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { useKadaikodi as e } from "../context/KadaikodiContext.js";
|
|
2
|
+
import "../context/index.js";
|
|
3
|
+
import { kadaikodiQuery as t } from "./useKadaikodiApi.js";
|
|
4
|
+
import { useMutation as n, useQuery as r, useQueryClient as i } from "@tanstack/react-query";
|
|
5
|
+
// src/kadaikodi/hooks/useTrackingApi.ts
|
|
6
|
+
var a = "\n orderId status active pollIntervalSeconds distanceMeters etaMinutes etaAt\n courier { workerRefId name phone }\n location { latitude longitude accuracyMeters headingDegrees speedMps recordedAt stale }\n origin { latitude longitude }\n destination { latitude longitude }\n", o = (e) => [
|
|
7
|
+
"kadaikodi",
|
|
8
|
+
"order-tracking",
|
|
9
|
+
e
|
|
10
|
+
], s = (e) => !e || e.pollIntervalSeconds <= 0 ? !1 : e.pollIntervalSeconds * 1e3, c = (n) => {
|
|
11
|
+
let { apiGatewayUrl: i } = e();
|
|
12
|
+
return r({
|
|
13
|
+
queryKey: o(n),
|
|
14
|
+
queryFn: async () => (await t(`query OrderTracking($orderId: ID!) {
|
|
15
|
+
kadaikodiOrderTracking(orderId: $orderId) { ${a} }
|
|
16
|
+
}`, { orderId: n }, i)).kadaikodiOrderTracking,
|
|
17
|
+
enabled: !!n,
|
|
18
|
+
refetchInterval: (e) => s(e.state.data),
|
|
19
|
+
refetchIntervalInBackground: !0
|
|
20
|
+
});
|
|
21
|
+
}, l = () => {
|
|
22
|
+
let { apiGatewayUrl: r } = e(), s = i();
|
|
23
|
+
return n({
|
|
24
|
+
mutationFn: async ({ orderId: e, fix: n }) => (await t(`mutation PublishCourierLocation($orderId: ID!, $input: KadaikodiCourierLocationInput!) {
|
|
25
|
+
kadaikodiPublishCourierLocation(orderId: $orderId, input: $input) { ${a} }
|
|
26
|
+
}`, {
|
|
27
|
+
orderId: e,
|
|
28
|
+
input: n
|
|
29
|
+
}, r)).kadaikodiPublishCourierLocation,
|
|
30
|
+
onSuccess: (e) => {
|
|
31
|
+
s.setQueryData(o(e.orderId), e);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
export { o as orderTrackingQueryKey, s as trackingRefetchInterval, c as useOrderTracking, l as usePublishCourierLocation };
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=useTrackingApi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useTrackingApi.js","names":["TRACKING_FIELDS","orderTrackingQueryKey","orderId","trackingRefetchInterval","data","useOrderTracking","useKadaikodi","useQuery","kadaikodiQuery","apiGatewayUrl","query","usePublishCourierLocation","queryClient","useQueryClient","useMutation","fix","tracking"],"sources":["../../../src/kadaikodi/hooks/useTrackingApi.ts"],"sourcesContent":["/**\n * Live delivery tracking hooks (BOFF-3962).\n *\n * The courier's last-known position, the drop-off pin and the ETA all come from\n * wspace-kadaikodi-svc (`kadaikodiOrderTracking`); nothing here estimates\n * positions on the client. The query is polled at the interval the service\n * returns (`pollIntervalSeconds`: fast while the order is out for delivery,\n * slow while it is being prepared, never once it is finished) — the gateway\n * is reached over plain HTTP GraphQL, so polling is the live-update transport.\n *\n * @module kadaikodi/hooks\n */\n\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useKadaikodi } from '../context';\nimport { kadaikodiQuery } from './useKadaikodiApi';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface GeoPoint {\n latitude: number;\n longitude: number;\n}\n\nexport interface TrackingCourier {\n workerRefId: string;\n name: string;\n phone: string | null;\n}\n\nexport interface CourierLocation extends GeoPoint {\n accuracyMeters: number | null;\n headingDegrees: number | null;\n speedMps: number | null;\n recordedAt: string;\n /** True once the courier has stopped reporting for more than two minutes. */\n stale: boolean;\n}\n\nexport interface OrderTracking {\n orderId: string;\n status: string;\n /** True while the order is out for delivery and the courier position is shared. */\n active: boolean;\n courier: TrackingCourier | null;\n location: CourierLocation | null;\n origin: GeoPoint | null;\n destination: GeoPoint | null;\n distanceMeters: number | null;\n etaMinutes: number | null;\n etaAt: string | null;\n pollIntervalSeconds: number;\n}\n\nexport interface CourierFixInput extends GeoPoint {\n accuracyMeters?: number | null;\n headingDegrees?: number | null;\n speedMps?: number | null;\n /** ISO-8601 device time of the fix. */\n recordedAt?: string | null;\n}\n\nconst TRACKING_FIELDS = `\n orderId status active pollIntervalSeconds distanceMeters etaMinutes etaAt\n courier { workerRefId name phone }\n location { latitude longitude accuracyMeters headingDegrees speedMps recordedAt stale }\n origin { latitude longitude }\n destination { latitude longitude }\n`;\n\nexport const orderTrackingQueryKey = (orderId?: string) =>\n ['kadaikodi', 'order-tracking', orderId] as const;\n\n/**\n * Refresh interval for a tracking result: the service's suggestion, or false\n * (stop) once it says 0 or the order is unknown.\n */\nexport const trackingRefetchInterval = (data: OrderTracking | null | undefined): number | false => {\n if (!data || data.pollIntervalSeconds <= 0) return false;\n return data.pollIntervalSeconds * 1000;\n};\n\n// ============================================================================\n// Hooks\n// ============================================================================\n\n/** Live tracking view for one order; null when the caller may not see it. */\nexport const useOrderTracking = (orderId?: string) => {\n const { apiGatewayUrl } = useKadaikodi();\n return useQuery({\n queryKey: orderTrackingQueryKey(orderId),\n queryFn: async () => {\n const result = await kadaikodiQuery<{ kadaikodiOrderTracking: OrderTracking | null }>(\n `query OrderTracking($orderId: ID!) {\n kadaikodiOrderTracking(orderId: $orderId) { ${TRACKING_FIELDS} }\n }`,\n { orderId },\n apiGatewayUrl\n );\n return result.kadaikodiOrderTracking;\n },\n enabled: Boolean(orderId),\n refetchInterval: (query) => trackingRefetchInterval(query.state.data),\n // Keep updating while the customer glances at another tab; the interval\n // already drops to zero once the order is finished.\n refetchIntervalInBackground: true,\n });\n};\n\n/** Courier side: publish one GPS fix for an order that is out for delivery. */\nexport const usePublishCourierLocation = () => {\n const { apiGatewayUrl } = useKadaikodi();\n const queryClient = useQueryClient();\n return useMutation({\n mutationFn: async ({ orderId, fix }: { orderId: string; fix: CourierFixInput }) => {\n const result = await kadaikodiQuery<{ kadaikodiPublishCourierLocation: OrderTracking }>(\n `mutation PublishCourierLocation($orderId: ID!, $input: KadaikodiCourierLocationInput!) {\n kadaikodiPublishCourierLocation(orderId: $orderId, input: $input) { ${TRACKING_FIELDS} }\n }`,\n { orderId, input: fix },\n apiGatewayUrl\n );\n return result.kadaikodiPublishCourierLocation;\n },\n onSuccess: (tracking) => {\n queryClient.setQueryData(orderTrackingQueryKey(tracking.orderId), tracking);\n },\n });\n};\n"],"mappings":";;;;;AAiEA,IAAMA,IAAkB,2RAQXC,KAAyB,MACpC;CAAC;CAAa;CAAkBC;AAAO,GAM5BC,KAA2B,MAClC,CAACC,KAAQA,EAAK,uBAAuB,IAAU,KAC5CA,EAAK,sBAAsB,KAQvBC,KAAoB,MAAqB;CACpD,IAAM,EAAE,qBAAkBC,EAAa;CACvC,OAAOC,EAAS;EACd,UAAUN,EAAsBC,CAAO;EACvC,SAAS,aAQA,MAPcM,EACnB;wDACgDR,EAAgB;YAEhE,EAAE,WAAQ,GACVS,CACF,EAAA,CACc;EAEhB,SAAS,EAAQP;EACjB,kBAAkB,MAAUC,EAAwBO,EAAM,MAAM,IAAI;EAGpE,6BAA6B;CAC/B,CAAC;AACH,GAGaC,UAAkC;CAC7C,IAAM,EAAE,qBAAkBL,EAAa,GACjCM,IAAcC,EAAe;CACnC,OAAOC,EAAY;EACjB,YAAY,OAAO,EAAE,YAAS,cAQrB,MAPcN,EACnB;gFACwER,EAAgB;YAExF;GAAE;GAAS,OAAOe;EAAI,GACtBN,CACF,EAAA,CACc;EAEhB,YAAY,MAAa;GACvB,EAAY,aAAaR,EAAsBe,EAAS,OAAO,GAAGA,CAAQ;EAC5E;CACF,CAAC;AACH"}
|