@12-apps/marketplace 1.19.1 → 1.20.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/ADOPTING.md +61 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/{adapter-ZpAWKoCk.d.ts → adapter-lXWwuQQh.d.ts} +1 -1
- package/dist/{chunk-RS2QKQ6S.js → chunk-C2MFGZ3H.js} +2 -2
- package/dist/{chunk-S2ISELNJ.js → chunk-T6A46MH3.js} +52 -43
- package/dist/chunk-T6A46MH3.js.map +1 -0
- package/dist/{client-DpEq0yXb.d.ts → client-CSHcYu3w.d.ts} +1 -1
- package/dist/{engine-CaiVufoP.d.ts → engine-DH7H8m0B.d.ts} +1 -1
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +365 -2
- package/dist/ifood/index.js +509 -9
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/manifest/server.d.ts +2 -2
- package/dist/manifest/server.js +2 -2
- package/dist/rappi/index.d.ts +1 -1
- package/dist/server/index.d.ts +2 -2
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/src/core/acknowledge.ts +16 -1
- package/src/core/order-fetch-marks.ts +9 -2
- package/src/ifood/courier.ts +4 -3
- package/src/ifood/index.ts +49 -0
- package/src/ifood/shipping-address.ts +190 -0
- package/src/ifood/shipping-events.ts +126 -0
- package/src/ifood/shipping-orders.ts +213 -0
- package/src/ifood/shipping-wire.ts +274 -0
- package/src/ifood/shipping.ts +184 -0
- package/dist/chunk-S2ISELNJ.js.map +0 -1
- /package/dist/{chunk-RS2QKQ6S.js.map → chunk-C2MFGZ3H.js.map} +0 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AnswerDisputeResult, f as AvailabilityJobPayload, g as AvailabilityOutcome, h as AvailabilityRetryError, i as AvailabilitySweepResult, B as BulkProblem, j as BulkProblemCode, k as BulkResult, C as CancellationFailureReason, l as CancellationReasonsJobPayload, m as CancellationReasonsOutcome, n as CancellationReasonsRetryError, o as CancellationStatus, p as CatalogueAction, q as CatalogueActionResult, r as CatalogueDocumentResult, s as CatalogueFailedAction, t as CatalogueFailureCode, u as CatalogueJobPayload, v as CatalogueOutcome, w as CataloguePublicationView, x as CataloguePublishInput, y as CatalogueRefusalCode, z as CatalogueRetryError, D as CatalogueStatus, E as CatalogueTarget, F as DecideManyResult, G as DecidedRow, H as DecisionInput, I as DecisionProblem, J as DecisionProblemCode, K as DecisionResult, L as DeliveryOutcome, M as DisputeAnswerInput, N as DisputeAnswerJobPayload, O as DisputeAnswerOutcome, P as DisputeAnswerRetryError, Q as DisputeAnswerView, R as DisputeRefusalCode, S as DisputeRow, T as DisputeStatus, U as ExpirySweepResult, V as FetchOrderJobPayload, W as FetchOrderOutcome, X as FetchOrderRetryError, Y as InformStatusInput, Z as IngestResult, _ as IngestSettings, $ as IngestionTarget, a0 as IntegrationRowInput, a1 as LinkFailure, a2 as LinkFinished, a3 as LinkPendingView, a4 as LinkRefusalCode, a5 as LinkTargetOrderPort, a6 as MARKETPLACE_ACKNOWLEDGE_JOB, a7 as MARKETPLACE_AVAILABILITY_JOB, a8 as MARKETPLACE_CANCELLATION_REASONS_JOB, a9 as MARKETPLACE_CATALOGUE_JOB, aa as MARKETPLACE_DISPUTE_ANSWER_JOB, ab as MARKETPLACE_FETCH_ORDER_JOB, ac as MARKETPLACE_OUTBOUND_JOB, ad as MarketplaceAdmission, ae as MarketplaceAdmissionRequest, af as MarketplaceAdmissionResult, ag as MarketplaceAuditEntry, ah as MarketplaceAuditPort, ai as MarketplaceAuthMode, aj as MarketplaceCataloguePort, ak as MarketplaceClockPort, al as MarketplaceConformityEngine, am as MarketplaceDb, an as MarketplaceDeliveryCodeEngine, ao as MarketplaceDisputeEngine, ap as MarketplaceDisputeView, aq as MarketplaceEngine, ar as MarketplaceEngineConfig, as as MarketplaceEnqueuePort, at as MarketplaceIntegrationView, au as MarketplaceLifecycleAnswer, av as MarketplaceLifecycleFacts, aw as MarketplaceLinkTarget, ax as MarketplaceLogger, ay as MarketplaceMenuLinkView, az as MarketplaceOrderPort, aA as MarketplaceOrderState, aB as MarketplaceOrderSummary, aC as MarketplacePorts, aD as MarketplaceRefusal, aE as MarketplaceSecretsPort, aF as MenuLinkRowInput, aG as OUTBOUND_GIVE_UP_MS, aH as OUTBOUND_STALE_MS, aI as OutboundAction, aJ as OutboundAttempt, aK as OutboundJobPayload, aL as OutboundOutcome, aM as OutboundRetryError, aN as OutboundSweepResult, aO as PauseOutcome, aP as PauseStoreInput, aQ as PauseStoreResult, aR as PendingAcceptance, aS as PendingInboxEvent, aT as ResolvedOrderLine, aU as ResumeOutcome, aV as STORE_PAUSE_LEASE_MS, aW as SaveMarketplaceIntegrationInput, aX as StoreAvailabilityView, aY as StorePauseFailureCode, aZ as StorePauseState, a_ as StorePauseWanted, a$ as VerifyDeliveryCodeInput, b0 as availabilityDedupeKey, b1 as catalogueDedupeKey, b2 as createMarketplaceEngine, b3 as disputeView, b4 as outboundDedupeKey } from './engine-
|
|
2
|
-
import { c as MarketplaceAdapter,
|
|
3
|
-
export { A as AdapterCallContext,
|
|
1
|
+
export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AnswerDisputeResult, f as AvailabilityJobPayload, g as AvailabilityOutcome, h as AvailabilityRetryError, i as AvailabilitySweepResult, B as BulkProblem, j as BulkProblemCode, k as BulkResult, C as CancellationFailureReason, l as CancellationReasonsJobPayload, m as CancellationReasonsOutcome, n as CancellationReasonsRetryError, o as CancellationStatus, p as CatalogueAction, q as CatalogueActionResult, r as CatalogueDocumentResult, s as CatalogueFailedAction, t as CatalogueFailureCode, u as CatalogueJobPayload, v as CatalogueOutcome, w as CataloguePublicationView, x as CataloguePublishInput, y as CatalogueRefusalCode, z as CatalogueRetryError, D as CatalogueStatus, E as CatalogueTarget, F as DecideManyResult, G as DecidedRow, H as DecisionInput, I as DecisionProblem, J as DecisionProblemCode, K as DecisionResult, L as DeliveryOutcome, M as DisputeAnswerInput, N as DisputeAnswerJobPayload, O as DisputeAnswerOutcome, P as DisputeAnswerRetryError, Q as DisputeAnswerView, R as DisputeRefusalCode, S as DisputeRow, T as DisputeStatus, U as ExpirySweepResult, V as FetchOrderJobPayload, W as FetchOrderOutcome, X as FetchOrderRetryError, Y as InformStatusInput, Z as IngestResult, _ as IngestSettings, $ as IngestionTarget, a0 as IntegrationRowInput, a1 as LinkFailure, a2 as LinkFinished, a3 as LinkPendingView, a4 as LinkRefusalCode, a5 as LinkTargetOrderPort, a6 as MARKETPLACE_ACKNOWLEDGE_JOB, a7 as MARKETPLACE_AVAILABILITY_JOB, a8 as MARKETPLACE_CANCELLATION_REASONS_JOB, a9 as MARKETPLACE_CATALOGUE_JOB, aa as MARKETPLACE_DISPUTE_ANSWER_JOB, ab as MARKETPLACE_FETCH_ORDER_JOB, ac as MARKETPLACE_OUTBOUND_JOB, ad as MarketplaceAdmission, ae as MarketplaceAdmissionRequest, af as MarketplaceAdmissionResult, ag as MarketplaceAuditEntry, ah as MarketplaceAuditPort, ai as MarketplaceAuthMode, aj as MarketplaceCataloguePort, ak as MarketplaceClockPort, al as MarketplaceConformityEngine, am as MarketplaceDb, an as MarketplaceDeliveryCodeEngine, ao as MarketplaceDisputeEngine, ap as MarketplaceDisputeView, aq as MarketplaceEngine, ar as MarketplaceEngineConfig, as as MarketplaceEnqueuePort, at as MarketplaceIntegrationView, au as MarketplaceLifecycleAnswer, av as MarketplaceLifecycleFacts, aw as MarketplaceLinkTarget, ax as MarketplaceLogger, ay as MarketplaceMenuLinkView, az as MarketplaceOrderPort, aA as MarketplaceOrderState, aB as MarketplaceOrderSummary, aC as MarketplacePorts, aD as MarketplaceRefusal, aE as MarketplaceSecretsPort, aF as MenuLinkRowInput, aG as OUTBOUND_GIVE_UP_MS, aH as OUTBOUND_STALE_MS, aI as OutboundAction, aJ as OutboundAttempt, aK as OutboundJobPayload, aL as OutboundOutcome, aM as OutboundRetryError, aN as OutboundSweepResult, aO as PauseOutcome, aP as PauseStoreInput, aQ as PauseStoreResult, aR as PendingAcceptance, aS as PendingInboxEvent, aT as ResolvedOrderLine, aU as ResumeOutcome, aV as STORE_PAUSE_LEASE_MS, aW as SaveMarketplaceIntegrationInput, aX as StoreAvailabilityView, aY as StorePauseFailureCode, aZ as StorePauseState, a_ as StorePauseWanted, a$ as VerifyDeliveryCodeInput, b0 as availabilityDedupeKey, b1 as catalogueDedupeKey, b2 as createMarketplaceEngine, b3 as disputeView, b4 as outboundDedupeKey } from './engine-DH7H8m0B.js';
|
|
2
|
+
import { c as MarketplaceAdapter, p as MarketplaceProvider, q as CancellationReason } from './adapter-lXWwuQQh.js';
|
|
3
|
+
export { A as AdapterCallContext, r as AdapterGrant, s as AdapterTokenCache, t as AppLinkCallContext, u as CancellationOutcome, v as CancellationRequestInput, w as CatalogueCallContext, x as CatalogueFailure, y as CatalogueImage, z as CatalogueItem, e as CatalogueItemOut, B as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, D as CataloguePublishResult, E as CatalogueReadContext, G as CatalogueReadNotice, H as CatalogueReadRefusalCode, I as CatalogueReadResult, J as CatalogueReadWarning, K as CatalogueReadWarningCode, f as CatalogueReader, L as CatalogueSnapshot, Q as CatalogueSnapshotCategory, R as CatalogueSnapshotItem, T as CatalogueSnapshotOption, U as CatalogueSnapshotOptionGroup, V as CatalogueStoredImage, W as CatalogueWarningCode, X as CourierTrackingCallResult, Y as CourierTrackingResult, Z as DeliveryCodeAnswer, _ as DisputeAlternative, $ as DisputeAlternativeType, a0 as DisputeAnswer, a1 as DisputeAnswerResult, a2 as DisputeFailureCode, a3 as DisputeItem, a4 as DisputeOutcome, a5 as DisputeReason, F as FetchOrderResult, a6 as InformLogisticsInput, a7 as LOGISTICS_STEPS, a8 as LinkCallContext, a9 as LinkCode, aa as LinkGrant, ab as LinkResult, ac as LinkedMerchant, ad as LogisticsDriver, ae as LogisticsStep, af as LogisticsVehicle, ag as MarketplaceAcknowledgement, ah as MarketplaceAppCredentialsPort, h as MarketplaceAppLinking, M as MarketplaceAvailability, ai as MarketplaceCapabilities, aj as MarketplaceCatalogue, ak as MarketplaceCourier, al as MarketplaceCourierAnswer, i as MarketplaceCourierApi, am as MarketplaceCourierEngine, an as MarketplaceCourierFacts, ao as MarketplaceCourierStep, n as MarketplaceCourierTracking, ap as MarketplaceCourierVehicle, aq as MarketplaceCredentials, ar as MarketplaceDeliveredBy, as as MarketplaceDiscountSponsor, at as MarketplaceDisputeApi, au as MarketplaceDisputeChange, av as MarketplaceDisputeDelegate, aw as MarketplaceHttp, ax as MarketplaceHttpRequest, ay as MarketplaceHttpResponse, az as MarketplaceLifecycle, aA as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, m as MarketplaceLogistics, aB as MarketplaceOrderType, aC as MarketplacePaymentMethod, aD as NormalizedAddress, aE as NormalizedBuyer, j as NormalizedCourierEvent, aF as NormalizedDisputeEvent, aG as NormalizedDisputeOpened, aH as NormalizedDisputeSettled, N as NormalizedEvent, aI as NormalizedLineOption, a as NormalizedMarketplaceOrder, aJ as NormalizedOrderDiscount, aK as NormalizedOrderFee, aL as NormalizedOrderLine, aM as NormalizedPaymentMethod, aN as NormalizedPayments, o as OrderCancellationReason, aO as OrderCancellationReasonsResult, aP as OutboundOrderRef, O as OutboundResult, aQ as PROVIDER_ID_PATTERN, aR as PickupCodeCallResult, aS as PickupCodeValidation, aT as PresenceProbe, P as PullCatalogue, d as PushCatalogue, aU as StatusFacts, aV as StatusStep, l as StorePauseRef, S as StorePauseRequest, k as StorePauseResult, aW as ValidatePickupCodeInput, aX as answered, aY as centsFromMajor, aZ as normalizedLineTotalCents, a_ as outboundResultOf, a$ as tokenGrantResultOf } from './adapter-lXWwuQQh.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* The adapter registry: the ONE place a provider id becomes a marketplace.
|
package/dist/index.js
CHANGED
package/dist/keeta/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-
|
|
2
|
-
import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-
|
|
1
|
+
import { A as AdapterCallContext, N as NormalizedEvent, a as NormalizedMarketplaceOrder, c as MarketplaceAdapter } from '../adapter-lXWwuQQh.js';
|
|
2
|
+
import { a as OpenDeliveryStop, O as OpenDeliveryApiBaseUrls } from '../client-CSHcYu3w.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Keeta's MERCHANT AUTHORIZATION, automated from the software (Keeta's
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-
|
|
1
|
+
import { aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DH7H8m0B.js';
|
|
2
2
|
import * as _12_apps_wiring from '@12-apps/wiring';
|
|
3
3
|
import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-lXWwuQQh.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
|
|
7
7
|
declare const marketplaceServerManifest: {
|
package/dist/manifest/server.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
MARKETPLACE_JOBS,
|
|
3
3
|
createApiMarketplace
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-C2MFGZ3H.js";
|
|
5
5
|
import "../chunk-LO7OKO6V.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-T6A46MH3.js";
|
|
7
7
|
import "../chunk-Q5RMVNU5.js";
|
|
8
8
|
import "../chunk-7QVYU63E.js";
|
|
9
9
|
|
package/dist/rappi/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-
|
|
1
|
+
import { N as NormalizedEvent, a as NormalizedMarketplaceOrder, M as MarketplaceAvailability, A as AdapterCallContext, O as OutboundResult, c as MarketplaceAdapter } from '../adapter-lXWwuQQh.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The words the Rappi adapter needs from its host, and nothing else.
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, aq as MarketplaceEngine, ax as MarketplaceLogger, aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-
|
|
1
|
+
import { J as DecisionProblemCode, j as BulkProblemCode, a4 as LinkRefusalCode, aq as MarketplaceEngine, ax as MarketplaceLogger, aK as OutboundJobPayload, V as FetchOrderJobPayload, b as AcknowledgeJobPayload, l as CancellationReasonsJobPayload, u as CatalogueJobPayload, f as AvailabilityJobPayload, N as DisputeAnswerJobPayload } from '../engine-DH7H8m0B.js';
|
|
2
2
|
import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
-
import '../adapter-
|
|
4
|
+
import '../adapter-lXWwuQQh.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Every problem code a route words from `problems`, decisions and bulk writes
|
package/dist/server/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
MARKETPLACE_SWEEP_QUEUE,
|
|
7
7
|
ORDER_NOT_PENDING_CODE,
|
|
8
8
|
createApiMarketplace
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-C2MFGZ3H.js";
|
|
10
10
|
import {
|
|
11
11
|
MARKETPLACE_DECIDE,
|
|
12
12
|
MARKETPLACE_MANAGE,
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
upsertMarketplaceIntegrationsBody,
|
|
21
21
|
upsertMarketplaceMenuLinksBody
|
|
22
22
|
} from "../chunk-LO7OKO6V.js";
|
|
23
|
-
import "../chunk-
|
|
23
|
+
import "../chunk-T6A46MH3.js";
|
|
24
24
|
import "../chunk-Q5RMVNU5.js";
|
|
25
25
|
import "../chunk-7QVYU63E.js";
|
|
26
26
|
export {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/marketplace",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.20.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "One marketplace integration engine for every marketplace: the durable inbox, the ingest pipeline, the acceptance clock and its sweep, the SKU map, the integration settings with sealed credentials, and the outbound engine (confirm, cancellation request, retries), behind an adapter port. Each marketplace is an adapter at its own subpath (./ifood, ./99food and ./keeta on Open Delivery, ./rappi). Framework-neutral wiring route descriptors (./server) with a Hono adapter (./hono), dep-free job blueprints, MCP tools and the package-owned Prisma partial + migrations.",
|
package/src/core/acknowledge.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { MarketplaceAdapter, OutboundResult } from "./adapter";
|
|
2
2
|
import { readOutboundConnection } from "./integration";
|
|
3
|
+
import { CANCELLED_BEFORE_INGEST_EVENT_TYPE } from "./order-fetch-marks";
|
|
3
4
|
import type { EngineContext } from "./ports";
|
|
4
5
|
import type { MarketplaceProvider } from "./types";
|
|
5
6
|
|
|
@@ -45,6 +46,13 @@ function acknowledgementOf(ctx: EngineContext, provider: string): NonNullable<Ma
|
|
|
45
46
|
return ctx.registry.get(provider)?.acknowledgement ?? null;
|
|
46
47
|
}
|
|
47
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Only rows the marketplace sent are owed: the engine's own marker
|
|
51
|
+
* (`engine:cancelled:<id>`) is never sent, even one an older release left
|
|
52
|
+
* unstamped, or the marketplace refuses the whole batch (FUT-6315).
|
|
53
|
+
*/
|
|
54
|
+
const SENT_BY_THE_MARKETPLACE = { eventType: { not: CANCELLED_BEFORE_INGEST_EVENT_TYPE } } as const;
|
|
55
|
+
|
|
48
56
|
/** How many stores one pass re-queues, per marketplace. */
|
|
49
57
|
const SWEEP_STORES = 500;
|
|
50
58
|
|
|
@@ -94,6 +102,7 @@ export async function runAcknowledge(
|
|
|
94
102
|
provider: payload.provider,
|
|
95
103
|
acknowledgedAt: null,
|
|
96
104
|
receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) },
|
|
105
|
+
...SENT_BY_THE_MARKETPLACE,
|
|
97
106
|
},
|
|
98
107
|
orderBy: { receivedAt: "asc" },
|
|
99
108
|
take: acknowledgement.batchSize,
|
|
@@ -164,7 +173,13 @@ export async function sweepAcknowledgements(ctx: EngineContext): Promise<{ reque
|
|
|
164
173
|
const acknowledgement = acknowledgementOf(ctx, provider);
|
|
165
174
|
if (!acknowledgement) continue;
|
|
166
175
|
const rows = (await db.marketplaceInboxEvent.findMany({
|
|
167
|
-
where: {
|
|
176
|
+
where: {
|
|
177
|
+
provider,
|
|
178
|
+
acknowledgedAt: null,
|
|
179
|
+
clientId: { not: null },
|
|
180
|
+
receivedAt: { gte: windowStart(ctx, acknowledgement.retentionMs) },
|
|
181
|
+
...SENT_BY_THE_MARKETPLACE,
|
|
182
|
+
},
|
|
168
183
|
// One row per store, bounded: the next pass takes the rest.
|
|
169
184
|
distinct: ["clientId"],
|
|
170
185
|
take: SWEEP_STORES,
|
|
@@ -22,7 +22,13 @@ import type { MarketplaceProvider } from "./types";
|
|
|
22
22
|
/** The settled reason of a row that was not ingested because its order was cancelled first. */
|
|
23
23
|
export const CANCELLED_BEFORE_INGEST_REASON = "cancelled before its order body arrived";
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* The marker row's `eventType`. The row is the engine's own, not an event the
|
|
27
|
+
* marketplace sent, so nothing is owed for it: it is written acknowledged, and
|
|
28
|
+
* the acknowledgment job never reads one (FUT-6315: iFood refused a whole batch
|
|
29
|
+
* that carried `engine:cancelled:<id>` as "an invalid event id").
|
|
30
|
+
*/
|
|
31
|
+
export const CANCELLED_BEFORE_INGEST_EVENT_TYPE = "ENGINE_CANCELLED_BEFORE_INGEST";
|
|
26
32
|
|
|
27
33
|
const markerId = (externalOrderId: string): string => `engine:cancelled:${externalOrderId}`;
|
|
28
34
|
|
|
@@ -38,13 +44,14 @@ export async function markCancelledBeforeIngest(
|
|
|
38
44
|
clientId: input.clientId,
|
|
39
45
|
provider: input.provider,
|
|
40
46
|
eventId: markerId(input.externalOrderId),
|
|
41
|
-
eventType:
|
|
47
|
+
eventType: CANCELLED_BEFORE_INGEST_EVENT_TYPE,
|
|
42
48
|
externalOrderId: input.externalOrderId,
|
|
43
49
|
payload: {},
|
|
44
50
|
status: "IGNORED",
|
|
45
51
|
error: "cancelled before the order was ingested",
|
|
46
52
|
receivedAt: ctx.ports.clock.now(),
|
|
47
53
|
processedAt: ctx.ports.clock.now(),
|
|
54
|
+
acknowledgedAt: ctx.ports.clock.now(),
|
|
48
55
|
},
|
|
49
56
|
select: { id: true },
|
|
50
57
|
});
|
package/src/ifood/courier.ts
CHANGED
|
@@ -176,9 +176,10 @@ function plusSeconds(base: Date, seconds: number | null): Date | null {
|
|
|
176
176
|
* The tracking body. Confirmed: latitude, longitude, `expectedDelivery`,
|
|
177
177
|
* `trackDate`, and seconds to the pickup and to the delivery. ESTIMATED: the
|
|
178
178
|
* names of the two second counts (`pickupEtaStart`, `deliveryEtaEnd`, or
|
|
179
|
-
* `pickupEta`, `deliveryEta`), counted from `trackDate`.
|
|
179
|
+
* `pickupEta`, `deliveryEta`), counted from `trackDate`. The Shipping
|
|
180
|
+
* module's tracking (`./shipping.ts`) documents the same body, so it reads it too.
|
|
180
181
|
*/
|
|
181
|
-
function
|
|
182
|
+
export function readIfoodTracking(body: unknown, now: Date): MarketplaceCourierTracking {
|
|
182
183
|
const trackedAt = firstDate(body, [["trackDate"]]);
|
|
183
184
|
const base = trackedAt ?? now;
|
|
184
185
|
const pickupSeconds = numberAt(body, "pickupEtaStart") ?? numberAt(body, "pickupEta");
|
|
@@ -200,7 +201,7 @@ async function tracking(ctx: AdapterCallContext, order: OutboundOrderRef): Promi
|
|
|
200
201
|
if (response.status === 404) return { kind: "notYet" };
|
|
201
202
|
const read = outboundResultOf(response);
|
|
202
203
|
if (read.kind !== "accepted") return read;
|
|
203
|
-
return { kind: "tracking", tracking:
|
|
204
|
+
return { kind: "tracking", tracking: readIfoodTracking(parsed(response.body), ctx.now) };
|
|
204
205
|
} catch (error) {
|
|
205
206
|
return retryOf(error);
|
|
206
207
|
}
|
package/src/ifood/index.ts
CHANGED
|
@@ -153,3 +153,52 @@ export {
|
|
|
153
153
|
type IfoodLogisticsStep,
|
|
154
154
|
type IfoodLogisticsVehicle,
|
|
155
155
|
} from "./logistics";
|
|
156
|
+
// iFood Shipping, "Entrega Sob Demanda" (FUT-5667, FUT-5666): wire calls the host's jobs make.
|
|
157
|
+
export {
|
|
158
|
+
IFOOD_SHIPPING_API,
|
|
159
|
+
IFOOD_SHIPPING_ERROR_CODES,
|
|
160
|
+
IFOOD_SHIPPING_TOKEN_REFRESH_AHEAD_MS,
|
|
161
|
+
ifoodCancelRequestDriver,
|
|
162
|
+
ifoodRequestDriver,
|
|
163
|
+
ifoodShippingQuoteForAddress,
|
|
164
|
+
ifoodShippingQuoteForOrder,
|
|
165
|
+
ifoodShippingRetryDelayMs,
|
|
166
|
+
ifoodShippingTracking,
|
|
167
|
+
type IfoodShippingErrorCode,
|
|
168
|
+
type IfoodShippingFailure,
|
|
169
|
+
type IfoodShippingInvalid,
|
|
170
|
+
type IfoodShippingPaymentMethod,
|
|
171
|
+
type IfoodShippingQuote,
|
|
172
|
+
type IfoodShippingQuoteRef,
|
|
173
|
+
type IfoodShippingQuoteResult,
|
|
174
|
+
type IfoodShippingRequested,
|
|
175
|
+
type IfoodShippingTrackingResult,
|
|
176
|
+
} from "./shipping";
|
|
177
|
+
export {
|
|
178
|
+
ifoodShippingCancel,
|
|
179
|
+
ifoodShippingCancellationReasons,
|
|
180
|
+
ifoodShippingCreateOrder,
|
|
181
|
+
type IfoodShippingCreateResult,
|
|
182
|
+
type IfoodShippingItem,
|
|
183
|
+
type IfoodShippingOrderInput,
|
|
184
|
+
type IfoodShippingReasonsResult,
|
|
185
|
+
} from "./shipping-orders";
|
|
186
|
+
export {
|
|
187
|
+
IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS,
|
|
188
|
+
ifoodShippingAcceptAddressChange,
|
|
189
|
+
ifoodShippingConfirmAddress,
|
|
190
|
+
ifoodShippingDenyAddressChange,
|
|
191
|
+
ifoodShippingRequestAddressChange,
|
|
192
|
+
ifoodShippingSafeDelivery,
|
|
193
|
+
type IfoodAddressChangeResult,
|
|
194
|
+
type IfoodSafeDeliveryResult,
|
|
195
|
+
type IfoodSafeDeliveryScore,
|
|
196
|
+
type IfoodShippingAddress,
|
|
197
|
+
} from "./shipping-address";
|
|
198
|
+
export {
|
|
199
|
+
IFOOD_SHIPPING_EVENT_TYPES,
|
|
200
|
+
readIfoodShippingEvent,
|
|
201
|
+
type IfoodShippingEvent,
|
|
202
|
+
type IfoodShippingEventAddress,
|
|
203
|
+
type IfoodShippingEventType,
|
|
204
|
+
} from "./shipping-events";
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { AdapterCallContext } from "../core/adapter";
|
|
2
|
+
import { pick } from "../core/payload-read";
|
|
3
|
+
import {
|
|
4
|
+
IFOOD_SHIPPING_API,
|
|
5
|
+
coordinatesValid,
|
|
6
|
+
parsedBody,
|
|
7
|
+
shippingCall,
|
|
8
|
+
shippingPost,
|
|
9
|
+
type IfoodShippingErrorCode,
|
|
10
|
+
type IfoodShippingFailure,
|
|
11
|
+
type IfoodShippingRequested,
|
|
12
|
+
} from "./shipping-wire";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The address half of an order on demand (FUT-5667): the address an order
|
|
16
|
+
* carries, the customer's address flow (confirm, change, accept, deny) and the
|
|
17
|
+
* safe-delivery score, per the `outside` guide (sources in `./shipping-wire.ts`).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const orderUrl = (orderId: string, action: string): string => `${IFOOD_SHIPPING_API}/orders/${encodeURIComponent(orderId)}/${action}`;
|
|
21
|
+
|
|
22
|
+
/** A delivery address, as the order and an address change carry it. */
|
|
23
|
+
export interface IfoodShippingAddress {
|
|
24
|
+
/** 8 digits once sent; anything else in it is dropped. Not sent with a change request. */
|
|
25
|
+
postalCode: string;
|
|
26
|
+
/** Required on an order; optional on a change request. */
|
|
27
|
+
streetNumber: string;
|
|
28
|
+
/** At most 50 characters. */
|
|
29
|
+
streetName: string;
|
|
30
|
+
/** At most 50 characters. */
|
|
31
|
+
complement?: string;
|
|
32
|
+
/** At most 70 characters. */
|
|
33
|
+
reference?: string;
|
|
34
|
+
/** At most 50 characters. */
|
|
35
|
+
neighborhood: string;
|
|
36
|
+
/** 2 to 50 characters. */
|
|
37
|
+
city: string;
|
|
38
|
+
/** Two letters, e.g. SP. */
|
|
39
|
+
state: string;
|
|
40
|
+
/** Two letters, e.g. BR. */
|
|
41
|
+
country: string;
|
|
42
|
+
latitude: number;
|
|
43
|
+
longitude: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const trimmed = (value: string | undefined): string => (value ?? "").trim();
|
|
47
|
+
|
|
48
|
+
/** Every field within the `outside` guide's documented lengths. Never cut: a cut street can send the courier elsewhere. */
|
|
49
|
+
function withinLengths(address: IfoodShippingAddress): boolean {
|
|
50
|
+
const max: [string | undefined, number][] = [
|
|
51
|
+
[address.streetName, 50],
|
|
52
|
+
[address.neighborhood, 50],
|
|
53
|
+
[address.city, 50],
|
|
54
|
+
[address.complement, 50],
|
|
55
|
+
[address.reference, 70],
|
|
56
|
+
];
|
|
57
|
+
return max.every(([value, limit]) => trimmed(value).length <= limit) && trimmed(address.city).length !== 1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The fields both kinds require, in range: street, neighbourhood, city, state, country and the point. */
|
|
61
|
+
function requiredValid(address: IfoodShippingAddress): boolean {
|
|
62
|
+
const present = [address.streetName, address.neighborhood, address.city].every((v) => trimmed(v) !== "");
|
|
63
|
+
const letters = /^[A-Za-z]{2}$/.test(address.state) && /^[A-Za-z]{2}$/.test(address.country);
|
|
64
|
+
return present && letters && withinLengths(address) && coordinatesValid(address);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Only the fields that hold something. */
|
|
68
|
+
function optionalFields(address: IfoodShippingAddress): Record<string, string> {
|
|
69
|
+
const fields: Record<string, string> = {};
|
|
70
|
+
for (const key of ["streetNumber", "complement", "reference"] as const) {
|
|
71
|
+
const value = trimmed(address[key]);
|
|
72
|
+
if (value !== "") fields[key] = value;
|
|
73
|
+
}
|
|
74
|
+
return fields;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The address body, or null when iFood would refuse it. `order`: the order's
|
|
79
|
+
* `deliveryAddress` (postal code and street number required). `change`: the
|
|
80
|
+
* change request's body (`streetNumber` optional, no postal code).
|
|
81
|
+
*/
|
|
82
|
+
export function ifoodShippingAddressBody(address: IfoodShippingAddress, kind: "order" | "change"): Record<string, unknown> | null {
|
|
83
|
+
const postalCode = address.postalCode.replace(/\D/g, "");
|
|
84
|
+
const orderValid = postalCode.length === 8 && trimmed(address.streetNumber) !== "";
|
|
85
|
+
if ((kind === "order" && !orderValid) || !requiredValid(address)) return null;
|
|
86
|
+
return {
|
|
87
|
+
...(kind === "order" ? { postalCode } : {}),
|
|
88
|
+
...optionalFields(address),
|
|
89
|
+
streetName: trimmed(address.streetName),
|
|
90
|
+
neighborhood: trimmed(address.neighborhood),
|
|
91
|
+
city: trimmed(address.city),
|
|
92
|
+
state: address.state.toUpperCase(),
|
|
93
|
+
country: address.country.toUpperCase(),
|
|
94
|
+
coordinates: { latitude: address.latitude, longitude: address.longitude },
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** An address answer iFood refused: no change pending, another pending, too far, or another region. */
|
|
99
|
+
export type IfoodAddressChangeResult =
|
|
100
|
+
| IfoodShippingRequested
|
|
101
|
+
| { kind: "address-change-refused"; status: number; code: IfoodShippingErrorCode }
|
|
102
|
+
| IfoodShippingFailure;
|
|
103
|
+
|
|
104
|
+
const ADDRESS_REFUSALS: ReadonlySet<string> = new Set([
|
|
105
|
+
"ChangeAddressOperationConflict",
|
|
106
|
+
"ChangeAddressOperationNotStarted",
|
|
107
|
+
"MaxDistanceHigherThanAllowed",
|
|
108
|
+
"RegionMismatch",
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
async function addressPost(ctx: AdapterCallContext, url: string, idempotencyKey: string, body?: unknown): Promise<IfoodAddressChangeResult> {
|
|
112
|
+
const result = await shippingPost(ctx, url, idempotencyKey, body);
|
|
113
|
+
if (result.kind === "unavailable" && ADDRESS_REFUSALS.has(result.code)) {
|
|
114
|
+
return { kind: "address-change-refused", status: result.status, code: result.code };
|
|
115
|
+
}
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** `POST …/userConfirmAddress`: the customer confirmed the original address. */
|
|
120
|
+
export function ifoodShippingConfirmAddress(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
|
|
121
|
+
return addressPost(ctx, orderUrl(orderId, "userConfirmAddress"), idempotencyKey);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** iFood's limit on a changed address: "máximo 500m da coordenada original". */
|
|
125
|
+
export const IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS = 500;
|
|
126
|
+
|
|
127
|
+
/** Great-circle distance in metres. */
|
|
128
|
+
function metersBetween(a: { latitude: number; longitude: number }, b: { latitude: number; longitude: number }): number {
|
|
129
|
+
const rad = Math.PI / 180;
|
|
130
|
+
const dLat = (b.latitude - a.latitude) * rad;
|
|
131
|
+
const dLon = (b.longitude - a.longitude) * rad;
|
|
132
|
+
const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.latitude * rad) * Math.cos(b.latitude * rad) * Math.sin(dLon / 2) ** 2;
|
|
133
|
+
return 2 * 6_371_000 * Math.asin(Math.sqrt(h));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* `POST …/deliveryAddressChangeRequest`: a change asked through the
|
|
138
|
+
* integrator's own screen. Its body has no postal code and an optional street
|
|
139
|
+
* number. Given the `original` point, a move past 500 m is refused here,
|
|
140
|
+
* before iFood would (`MaxDistanceHigherThanAllowed`).
|
|
141
|
+
*/
|
|
142
|
+
export function ifoodShippingRequestAddressChange(
|
|
143
|
+
ctx: AdapterCallContext,
|
|
144
|
+
orderId: string,
|
|
145
|
+
address: IfoodShippingAddress,
|
|
146
|
+
idempotencyKey: string,
|
|
147
|
+
original?: { latitude: number; longitude: number },
|
|
148
|
+
): Promise<IfoodAddressChangeResult> {
|
|
149
|
+
const body = ifoodShippingAddressBody(address, "change");
|
|
150
|
+
if (body === null) return Promise.resolve({ kind: "invalid", reason: "ADDRESS" });
|
|
151
|
+
if (original && metersBetween(original, address) > IFOOD_SHIPPING_ADDRESS_CHANGE_MAX_METERS) {
|
|
152
|
+
return Promise.resolve({ kind: "invalid", reason: "ADDRESS_TOO_FAR" });
|
|
153
|
+
}
|
|
154
|
+
return addressPost(ctx, orderUrl(orderId, "deliveryAddressChangeRequest"), idempotencyKey, body);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** `POST …/acceptDeliveryAddressChange` (200): within 15 minutes of the request, or iFood rejects it. */
|
|
158
|
+
export function ifoodShippingAcceptAddressChange(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
|
|
159
|
+
return addressPost(ctx, orderUrl(orderId, "acceptDeliveryAddressChange"), idempotencyKey);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** `POST …/denyDeliveryAddressChange` (202). */
|
|
163
|
+
export function ifoodShippingDenyAddressChange(ctx: AdapterCallContext, orderId: string, idempotencyKey: string): Promise<IfoodAddressChangeResult> {
|
|
164
|
+
return addressPost(ctx, orderUrl(orderId, "denyDeliveryAddressChange"), idempotencyKey);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** iFood's confidence in the delivery. */
|
|
168
|
+
export type IfoodSafeDeliveryScore = "LOW" | "MODERATE" | "HIGH" | "VERY_HIGH";
|
|
169
|
+
const SCORES: readonly string[] = ["LOW", "MODERATE", "HIGH", "VERY_HIGH"];
|
|
170
|
+
|
|
171
|
+
export type IfoodSafeDeliveryResult =
|
|
172
|
+
| { kind: "score"; score: IfoodSafeDeliveryScore; rules: Record<string, boolean> }
|
|
173
|
+
/** 400 `OrderWithoutSafeDelivery`: the order has no score. */
|
|
174
|
+
| { kind: "none" }
|
|
175
|
+
| IfoodShippingFailure;
|
|
176
|
+
|
|
177
|
+
/** `GET /shipping/v1.0/orders/{orderId}/safeDelivery`. */
|
|
178
|
+
export async function ifoodShippingSafeDelivery(ctx: AdapterCallContext, orderId: string): Promise<IfoodSafeDeliveryResult> {
|
|
179
|
+
const answer = await shippingCall(ctx, { method: "GET", url: orderUrl(orderId, "safeDelivery") });
|
|
180
|
+
if (answer.kind === "unavailable" && answer.code === "OrderWithoutSafeDelivery") return { kind: "none" };
|
|
181
|
+
if (answer.kind !== "answer") return answer;
|
|
182
|
+
const parsed = parsedBody(answer.body);
|
|
183
|
+
const score = pick(parsed, "score");
|
|
184
|
+
if (typeof score !== "string" || !SCORES.includes(score)) return { kind: "retry", reason: "iFood Shipping answered no score" };
|
|
185
|
+
const rawRules = pick(parsed, "rules");
|
|
186
|
+
const rules = Object.fromEntries(
|
|
187
|
+
Object.entries(rawRules !== null && typeof rawRules === "object" ? rawRules : {}).filter((entry): entry is [string, boolean] => typeof entry[1] === "boolean"),
|
|
188
|
+
);
|
|
189
|
+
return { kind: "score", score: score as IfoodSafeDeliveryScore, rules };
|
|
190
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { firstDate, firstString, pick } from "../core/payload-read";
|
|
2
|
+
import type { NormalizedCourierEvent } from "../core/types";
|
|
3
|
+
import { readIfoodCourierEvent } from "./courier";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The Shipping events iFood's stream carries (FUT-5667, FUT-5666), read off
|
|
7
|
+
* the `inside` and `outside` Shipping guides and the Order module's events page
|
|
8
|
+
* (https://developer.ifood.com.br/pt-BR/docs/food/guides/modules/order/events),
|
|
9
|
+
* 2026-12-04. The stream, its polling every 30 s, the acknowledgement and the
|
|
10
|
+
* deduplication by event id are the engine's existing ones; this only reads an
|
|
11
|
+
* event the host already has.
|
|
12
|
+
*
|
|
13
|
+
* `salesChannel` tells the two kinds apart: `POS` for an order placed off the
|
|
14
|
+
* platform, `IFOOD` for one placed on it. It is returned as it came; the host
|
|
15
|
+
* filters.
|
|
16
|
+
*
|
|
17
|
+
* `DELIVERY_DROP_CODE_REQUESTED` carries the customer's code in
|
|
18
|
+
* `metadata.CODE`; it is NOT read: the code stays on iFood's tracking page,
|
|
19
|
+
* and never reaches a result a log could print.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** The Shipping events that carry nothing past the order and the time. */
|
|
23
|
+
export const IFOOD_SHIPPING_EVENT_TYPES = [
|
|
24
|
+
"REQUEST_DRIVER",
|
|
25
|
+
"REQUEST_DRIVER_SUCCESS",
|
|
26
|
+
"REQUEST_DRIVER_FAILED",
|
|
27
|
+
"DELIVERY_DROP_CODE_REQUESTED",
|
|
28
|
+
"DELIVERY_IN_TRANSIT",
|
|
29
|
+
"DELIVERY_CONCLUDED",
|
|
30
|
+
"DELIVERY_CANCELLED",
|
|
31
|
+
"DELIVERY_CANCELLATION_REQUESTED",
|
|
32
|
+
"DELIVERY_CANCELLATION_REQUEST_ACCEPTED",
|
|
33
|
+
"DELIVERY_CANCELLATION_REQUEST_REJECTED",
|
|
34
|
+
"CANCELLATION_REQUESTED",
|
|
35
|
+
"CANCELLED",
|
|
36
|
+
"DELIVERY_ADDRESS_CHANGE_USER_CONFIRMED",
|
|
37
|
+
"DELIVERY_ADDRESS_CHANGE_ACCEPTED",
|
|
38
|
+
] as const;
|
|
39
|
+
|
|
40
|
+
export type IfoodShippingEventType = (typeof IFOOD_SHIPPING_EVENT_TYPES)[number];
|
|
41
|
+
|
|
42
|
+
/** The address a change request names. */
|
|
43
|
+
export interface IfoodShippingEventAddress {
|
|
44
|
+
streetName: string | null;
|
|
45
|
+
streetNumber: string | null;
|
|
46
|
+
complement: string | null;
|
|
47
|
+
reference: string | null;
|
|
48
|
+
neighborhood: string | null;
|
|
49
|
+
city: string | null;
|
|
50
|
+
state: string | null;
|
|
51
|
+
country: string | null;
|
|
52
|
+
latitude: number | null;
|
|
53
|
+
longitude: number | null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface EventBase {
|
|
57
|
+
eventId: string;
|
|
58
|
+
orderId: string;
|
|
59
|
+
salesChannel: string | null;
|
|
60
|
+
at: Date | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type IfoodShippingEvent =
|
|
64
|
+
| (EventBase & { type: IfoodShippingEventType })
|
|
65
|
+
| (EventBase & { type: "DELIVERY_ADDRESS_CHANGE_REQUESTED"; address: IfoodShippingEventAddress })
|
|
66
|
+
/**
|
|
67
|
+
* The order's cancel failed; `reason` is iFood's code from
|
|
68
|
+
* `metadata.CANCELLATION_REQUEST_FAILED_REASON` (e.g.
|
|
69
|
+
* `ACCOUNT_IS_NOT_LINKED_TO_THE_STORE`), a code, never customer data.
|
|
70
|
+
*/
|
|
71
|
+
| (EventBase & { type: "CANCELLATION_REQUEST_FAILED"; reason: string | null })
|
|
72
|
+
/** `action` is `region-mismatch` when iFood denied it itself. */
|
|
73
|
+
| (EventBase & { type: "DELIVERY_ADDRESS_CHANGE_DENIED"; action: string | null })
|
|
74
|
+
/** The `ASSIGN_DRIVER` family, read by the courier reader (FUT-5665). */
|
|
75
|
+
| (EventBase & { type: "COURIER"; courier: NormalizedCourierEvent });
|
|
76
|
+
|
|
77
|
+
const SIMPLE: ReadonlySet<string> = new Set(IFOOD_SHIPPING_EVENT_TYPES);
|
|
78
|
+
|
|
79
|
+
function metadataOf(payload: unknown): unknown {
|
|
80
|
+
const raw = pick(payload, "metadata");
|
|
81
|
+
if (typeof raw !== "string") return raw;
|
|
82
|
+
try {
|
|
83
|
+
return JSON.parse(raw) as unknown;
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function numberAt(source: unknown, ...path: string[]): number | null {
|
|
90
|
+
const value = pick(source, ...path);
|
|
91
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function addressOf(metadata: unknown): IfoodShippingEventAddress {
|
|
95
|
+
const address = pick(metadata, "address");
|
|
96
|
+
const field = (key: string): string | null => firstString(address, [[key]]);
|
|
97
|
+
return {
|
|
98
|
+
streetName: field("streetName"),
|
|
99
|
+
streetNumber: field("streetNumber"),
|
|
100
|
+
complement: field("complement"),
|
|
101
|
+
reference: field("reference"),
|
|
102
|
+
neighborhood: field("neighborhood"),
|
|
103
|
+
city: field("city"),
|
|
104
|
+
state: field("state"),
|
|
105
|
+
country: field("country"),
|
|
106
|
+
latitude: numberAt(address, "coordinates", "latitude"),
|
|
107
|
+
longitude: numberAt(address, "coordinates", "longitude"),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A Shipping event, or null for any other event, or one with no id or order. */
|
|
112
|
+
export function readIfoodShippingEvent(payload: unknown): IfoodShippingEvent | null {
|
|
113
|
+
const type = (firstString(payload, [["fullCode"], ["code"]]) ?? "").toUpperCase();
|
|
114
|
+
const eventId = firstString(payload, [["id"], ["eventId"]]);
|
|
115
|
+
const orderId = firstString(payload, [["orderId"]]);
|
|
116
|
+
if (eventId === null || orderId === null) return null;
|
|
117
|
+
const base: EventBase = { eventId, orderId, salesChannel: firstString(payload, [["salesChannel"]]), at: firstDate(payload, [["createdAt"]]) };
|
|
118
|
+
if (SIMPLE.has(type)) return { ...base, type: type as IfoodShippingEventType };
|
|
119
|
+
if (type === "DELIVERY_ADDRESS_CHANGE_REQUESTED") return { ...base, type, address: addressOf(metadataOf(payload)) };
|
|
120
|
+
if (type === "CANCELLATION_REQUEST_FAILED") {
|
|
121
|
+
return { ...base, type, reason: firstString(metadataOf(payload), [["CANCELLATION_REQUEST_FAILED_REASON"]]) };
|
|
122
|
+
}
|
|
123
|
+
if (type === "DELIVERY_ADDRESS_CHANGE_DENIED") return { ...base, type, action: firstString(metadataOf(payload), [["action"]]) };
|
|
124
|
+
const courier = readIfoodCourierEvent(payload, type);
|
|
125
|
+
return courier ? { ...base, type: "COURIER", courier } : null;
|
|
126
|
+
}
|