@12-apps/marketplace 1.15.0 → 1.16.0
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 +36 -2
- package/dist/{chunk-FQI56NGC.js → chunk-DJIMUEHT.js} +2 -2
- package/dist/{chunk-B4DYPQFE.js → chunk-TICWLBSA.js} +26 -7
- package/dist/chunk-TICWLBSA.js.map +1 -0
- package/dist/{engine-BSLdhAGC.d.ts → engine-DSRj7qnC.d.ts} +9 -0
- package/dist/hono/index.d.ts +1 -1
- package/dist/hono/index.js +2 -2
- package/dist/ifood/index.d.ts +57 -1
- package/dist/ifood/index.js +103 -0
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/manifest/server.d.ts +1 -1
- package/dist/manifest/server.js +2 -2
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +2 -2
- package/package.json +1 -1
- package/src/core/ingest.ts +5 -5
- package/src/core/order-reasons.ts +46 -8
- package/src/ifood/index.ts +13 -0
- package/src/ifood/logistics.ts +195 -0
- package/src/ifood/outbound.ts +1 -1
- package/dist/chunk-B4DYPQFE.js.map +0 -1
- /package/dist/{chunk-FQI56NGC.js.map → chunk-DJIMUEHT.js.map} +0 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AvailabilityJobPayload, f as AvailabilityOutcome, g as AvailabilityRetryError, h as AvailabilitySweepResult, B as BulkProblem, i as BulkProblemCode, j as BulkResult, C as CancellationFailureReason, k as CancellationReasonsJobPayload, l as CancellationReasonsOutcome, m as CancellationReasonsRetryError, n as CancellationStatus, o as CatalogueAction, p as CatalogueActionResult, q as CatalogueDocumentResult, r as CatalogueFailedAction, s as CatalogueFailureCode, t as CatalogueJobPayload, u as CatalogueOutcome, v as CataloguePublicationView, w as CataloguePublishInput, x as CatalogueRefusalCode, y as CatalogueRetryError, z as CatalogueStatus, D as CatalogueTarget, E as DecideManyResult, F as DecidedRow, G as DecisionInput, H as DecisionProblem, I as DecisionProblemCode, J as DecisionResult, K as DeliveryOutcome, L as ExpirySweepResult, M as FetchOrderJobPayload, N as FetchOrderOutcome, O as FetchOrderRetryError, P as InformStatusInput, Q as IngestResult, R as IngestSettings, S as IngestionTarget, T as IntegrationRowInput, U as LinkFailure, V as LinkFinished, W as LinkPendingView, X as LinkRefusalCode, Y as MARKETPLACE_ACKNOWLEDGE_JOB, Z as MARKETPLACE_AVAILABILITY_JOB, _ as MARKETPLACE_CANCELLATION_REASONS_JOB, $ as MARKETPLACE_CATALOGUE_JOB, a0 as MARKETPLACE_FETCH_ORDER_JOB, a1 as MARKETPLACE_OUTBOUND_JOB, a2 as MarketplaceAdmission, a3 as MarketplaceAdmissionRequest, a4 as MarketplaceAdmissionResult, a5 as MarketplaceAuditEntry, a6 as MarketplaceAuditPort, a7 as MarketplaceAuthMode, a8 as MarketplaceCataloguePort, a9 as MarketplaceClockPort, aa as MarketplaceConformityEngine, ab as MarketplaceDb, ac as MarketplaceEngine, ad as MarketplaceEngineConfig, ae as MarketplaceEnqueuePort, af as MarketplaceIntegrationView, ag as MarketplaceLifecycleAnswer, ah as MarketplaceLifecycleFacts, ai as MarketplaceLogger, aj as MarketplaceMenuLinkView, ak as MarketplaceOrderPort, al as MarketplaceOrderState, am as MarketplaceOrderSummary, an as MarketplacePorts, ao as MarketplaceRefusal, ap as MarketplaceSecretsPort, aq as MenuLinkRowInput, ar as OUTBOUND_GIVE_UP_MS, as as OUTBOUND_STALE_MS, at as OutboundAction, au as OutboundAttempt, av as OutboundJobPayload, aw as OutboundOutcome, ax as OutboundRetryError, ay as OutboundSweepResult, az as PauseOutcome, aA as PauseStoreInput, aB as PauseStoreResult, aC as PendingAcceptance, aD as PendingInboxEvent, aE as ResolvedOrderLine, aF as ResumeOutcome, aG as STORE_PAUSE_LEASE_MS, aH as SaveMarketplaceIntegrationInput, aI as StoreAvailabilityView, aJ as StorePauseFailureCode, aK as StorePauseState, aL as StorePauseWanted, aM as availabilityDedupeKey, aN as catalogueDedupeKey, aO as createMarketplaceEngine, aP as outboundDedupeKey } from './engine-
|
|
1
|
+
export { A as AcceptanceDecision, a as AcceptanceStatus, b as AcknowledgeJobPayload, c as AcknowledgeOutcome, d as AcknowledgeRetryError, e as AvailabilityJobPayload, f as AvailabilityOutcome, g as AvailabilityRetryError, h as AvailabilitySweepResult, B as BulkProblem, i as BulkProblemCode, j as BulkResult, C as CancellationFailureReason, k as CancellationReasonsJobPayload, l as CancellationReasonsOutcome, m as CancellationReasonsRetryError, n as CancellationStatus, o as CatalogueAction, p as CatalogueActionResult, q as CatalogueDocumentResult, r as CatalogueFailedAction, s as CatalogueFailureCode, t as CatalogueJobPayload, u as CatalogueOutcome, v as CataloguePublicationView, w as CataloguePublishInput, x as CatalogueRefusalCode, y as CatalogueRetryError, z as CatalogueStatus, D as CatalogueTarget, E as DecideManyResult, F as DecidedRow, G as DecisionInput, H as DecisionProblem, I as DecisionProblemCode, J as DecisionResult, K as DeliveryOutcome, L as ExpirySweepResult, M as FetchOrderJobPayload, N as FetchOrderOutcome, O as FetchOrderRetryError, P as InformStatusInput, Q as IngestResult, R as IngestSettings, S as IngestionTarget, T as IntegrationRowInput, U as LinkFailure, V as LinkFinished, W as LinkPendingView, X as LinkRefusalCode, Y as MARKETPLACE_ACKNOWLEDGE_JOB, Z as MARKETPLACE_AVAILABILITY_JOB, _ as MARKETPLACE_CANCELLATION_REASONS_JOB, $ as MARKETPLACE_CATALOGUE_JOB, a0 as MARKETPLACE_FETCH_ORDER_JOB, a1 as MARKETPLACE_OUTBOUND_JOB, a2 as MarketplaceAdmission, a3 as MarketplaceAdmissionRequest, a4 as MarketplaceAdmissionResult, a5 as MarketplaceAuditEntry, a6 as MarketplaceAuditPort, a7 as MarketplaceAuthMode, a8 as MarketplaceCataloguePort, a9 as MarketplaceClockPort, aa as MarketplaceConformityEngine, ab as MarketplaceDb, ac as MarketplaceEngine, ad as MarketplaceEngineConfig, ae as MarketplaceEnqueuePort, af as MarketplaceIntegrationView, ag as MarketplaceLifecycleAnswer, ah as MarketplaceLifecycleFacts, ai as MarketplaceLogger, aj as MarketplaceMenuLinkView, ak as MarketplaceOrderPort, al as MarketplaceOrderState, am as MarketplaceOrderSummary, an as MarketplacePorts, ao as MarketplaceRefusal, ap as MarketplaceSecretsPort, aq as MenuLinkRowInput, ar as OUTBOUND_GIVE_UP_MS, as as OUTBOUND_STALE_MS, at as OutboundAction, au as OutboundAttempt, av as OutboundJobPayload, aw as OutboundOutcome, ax as OutboundRetryError, ay as OutboundSweepResult, az as PauseOutcome, aA as PauseStoreInput, aB as PauseStoreResult, aC as PendingAcceptance, aD as PendingInboxEvent, aE as ResolvedOrderLine, aF as ResumeOutcome, aG as STORE_PAUSE_LEASE_MS, aH as SaveMarketplaceIntegrationInput, aI as StoreAvailabilityView, aJ as StorePauseFailureCode, aK as StorePauseState, aL as StorePauseWanted, aM as availabilityDedupeKey, aN as catalogueDedupeKey, aO as createMarketplaceEngine, aP as outboundDedupeKey } from './engine-DSRj7qnC.js';
|
|
2
2
|
import { c as MarketplaceAdapter, l as MarketplaceProvider, m as CancellationReason } from './adapter-CjVdMhZ2.js';
|
|
3
3
|
export { A as AdapterCallContext, n as AdapterGrant, o as AdapterTokenCache, p as CancellationOutcome, q as CancellationRequestInput, r as CatalogueCallContext, s as CatalogueFailure, t as CatalogueImage, u as CatalogueItem, e as CatalogueItemOut, v as CatalogueItemRef, C as CatalogueMenuEntry, b as CatalogueMenuOptions, w as CataloguePublishResult, x as CatalogueReadContext, y as CatalogueReadNotice, z as CatalogueReadRefusalCode, B as CatalogueReadResult, D as CatalogueReadWarning, E as CatalogueReadWarningCode, f as CatalogueReader, G as CatalogueSnapshot, H as CatalogueSnapshotCategory, I as CatalogueSnapshotItem, J as CatalogueSnapshotOption, K as CatalogueSnapshotOptionGroup, L as CatalogueStoredImage, Q as CatalogueWarningCode, R as CourierTrackingCallResult, T as CourierTrackingResult, F as FetchOrderResult, U as LinkCallContext, V as LinkCode, W as LinkGrant, X as LinkResult, Y as LinkedMerchant, Z as MarketplaceAcknowledgement, _ as MarketplaceAppCredentialsPort, M as MarketplaceAvailability, $ as MarketplaceCapabilities, a0 as MarketplaceCatalogue, a1 as MarketplaceCourier, a2 as MarketplaceCourierAnswer, h as MarketplaceCourierApi, a3 as MarketplaceCourierEngine, a4 as MarketplaceCourierFacts, a5 as MarketplaceCourierStep, a6 as MarketplaceCourierTracking, a7 as MarketplaceCourierVehicle, a8 as MarketplaceCredentials, a9 as MarketplaceDeliveredBy, aa as MarketplaceDiscountSponsor, ab as MarketplaceHttp, ac as MarketplaceHttpRequest, ad as MarketplaceHttpResponse, ae as MarketplaceLifecycle, af as MarketplaceLinkAttemptDelegate, g as MarketplaceLinking, ag as MarketplaceOrderType, ah as MarketplacePaymentMethod, ai as NormalizedAddress, aj as NormalizedBuyer, i as NormalizedCourierEvent, N as NormalizedEvent, ak as NormalizedLineOption, a as NormalizedMarketplaceOrder, al as NormalizedOrderDiscount, am as NormalizedOrderFee, an as NormalizedOrderLine, ao as NormalizedPaymentMethod, ap as NormalizedPayments, aq as OrderCancellationReason, ar as OrderCancellationReasonsResult, as as OutboundOrderRef, O as OutboundResult, at as PROVIDER_ID_PATTERN, au as PickupCodeCallResult, av as PickupCodeValidation, aw as PresenceProbe, P as PullCatalogue, d as PushCatalogue, ax as StatusFacts, ay as StatusStep, k as StorePauseRef, S as StorePauseRequest, j as StorePauseResult, az as ValidatePickupCodeInput, aA as answered, aB as centsFromMajor, aC as normalizedLineTotalCents, aD as outboundResultOf, aE as tokenGrantResultOf } from './adapter-CjVdMhZ2.js';
|
|
4
4
|
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-
|
|
1
|
+
import { av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-DSRj7qnC.js';
|
|
2
2
|
import * as _12_apps_wiring from '@12-apps/wiring';
|
|
3
3
|
import { createApiMarketplace, MarketplaceJobDeps } from '../server/index.js';
|
|
4
4
|
import '../adapter-CjVdMhZ2.js';
|
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-DJIMUEHT.js";
|
|
5
5
|
import "../chunk-SGOTN5PX.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-TICWLBSA.js";
|
|
7
7
|
import "../chunk-H2VQRD3B.js";
|
|
8
8
|
import "../chunk-7QVYU63E.js";
|
|
9
9
|
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { I as DecisionProblemCode, i as BulkProblemCode, X as LinkRefusalCode, ac as MarketplaceEngine, ai as MarketplaceLogger, av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-
|
|
1
|
+
import { I as DecisionProblemCode, i as BulkProblemCode, X as LinkRefusalCode, ac as MarketplaceEngine, ai as MarketplaceLogger, av as OutboundJobPayload, M as FetchOrderJobPayload, b as AcknowledgeJobPayload, k as CancellationReasonsJobPayload, t as CatalogueJobPayload, e as AvailabilityJobPayload } from '../engine-DSRj7qnC.js';
|
|
2
2
|
import { WireRoute, WireJobBlueprint } from '@12-apps/wiring';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import '../adapter-CjVdMhZ2.js';
|
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-DJIMUEHT.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-SGOTN5PX.js";
|
|
23
|
-
import "../chunk-
|
|
23
|
+
import "../chunk-TICWLBSA.js";
|
|
24
24
|
import "../chunk-H2VQRD3B.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.16.0",
|
|
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/ingest.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { applyDeferredConfirmations } from "./marketplace-confirmed";
|
|
2
1
|
import { enqueueOrderReasons } from "./order-reasons";
|
|
3
2
|
import { markMarketplaceEventSeen } from "./integration";
|
|
4
3
|
import { resolveSkus } from "./menu-links";
|
|
@@ -209,10 +208,11 @@ export async function ingestMarketplaceOrder(
|
|
|
209
208
|
}
|
|
210
209
|
|
|
211
210
|
ctx.ports.publishChanged(clientId);
|
|
212
|
-
// After the commit: the order's own cancellation reasons are read
|
|
213
|
-
// confirmation on the marketplace that outran
|
|
214
|
-
|
|
215
|
-
|
|
211
|
+
// After the commit, in one job: the order's own cancellation reasons are read and,
|
|
212
|
+
// for an order nobody accepted yet, a confirmation on the marketplace that outran it
|
|
213
|
+
// is applied (FUT-5984, FUT-5653). Never inline: that read almost always finds
|
|
214
|
+
// nothing, and the expiry sweep applies what a late job has not yet.
|
|
215
|
+
await enqueueOrderReasons(ctx, { clientId, orderId, provider: order.provider, deferredConfirmations: !accepted });
|
|
216
216
|
|
|
217
217
|
return { orderId, created: true, unmappedSkus, autoAccepted: accepted };
|
|
218
218
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { CancellationReason, OrderCancellationReason } from "./adapter";
|
|
2
2
|
import { readOutboundConnection } from "./integration";
|
|
3
|
+
import { applyDeferredConfirmations } from "./marketplace-confirmed";
|
|
3
4
|
import type { EngineContext, MarketplaceDb } from "./ports";
|
|
4
5
|
import { reasonsForOrder, storedReasons } from "./registry";
|
|
5
6
|
import type { MarketplaceProvider } from "./types";
|
|
@@ -11,6 +12,13 @@ import type { MarketplaceProvider } from "./types";
|
|
|
11
12
|
* kept on the acceptance row (`cancellation_reasons`) for the order's life.
|
|
12
13
|
* The adapter's static list is the fallback while, or when, that read did not
|
|
13
14
|
* land: a refusal is never held on the marketplace.
|
|
15
|
+
*
|
|
16
|
+
* The same job, for an order the store did not auto-accept, first applies a
|
|
17
|
+
* confirmation on the marketplace that arrived before the order (FUT-5653's
|
|
18
|
+
* C5). It runs here, a few seconds after the ingest, rather than inside it, so
|
|
19
|
+
* the ingest pays no inbox read that almost always finds nothing (FUT-5984).
|
|
20
|
+
* A job that is late or lost loses nothing: the expiry sweep applies a deferred
|
|
21
|
+
* confirmation before it expires the order (`applyOwedConfirmations`).
|
|
14
22
|
*/
|
|
15
23
|
|
|
16
24
|
/** The wire name, `<namespace>.<blueprint>`. */
|
|
@@ -20,6 +28,8 @@ export const MARKETPLACE_CANCELLATION_REASONS_JOB = "marketplace.cancellation-re
|
|
|
20
28
|
export interface CancellationReasonsJobPayload {
|
|
21
29
|
clientId: string;
|
|
22
30
|
orderId: string;
|
|
31
|
+
/** Set for an order not auto-accepted: apply a confirmation that outran it first. */
|
|
32
|
+
deferredConfirmations?: true;
|
|
23
33
|
}
|
|
24
34
|
|
|
25
35
|
/** What one run did. */
|
|
@@ -36,13 +46,22 @@ export class CancellationReasonsRetryError extends Error {
|
|
|
36
46
|
}
|
|
37
47
|
}
|
|
38
48
|
|
|
39
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* Queue the job after a new order's commit, when its marketplace lists reasons per
|
|
51
|
+
* order or (for an order not auto-accepted) confirms on its own side. Never throws.
|
|
52
|
+
*/
|
|
40
53
|
export async function enqueueOrderReasons(
|
|
41
54
|
ctx: EngineContext,
|
|
42
|
-
input: { clientId: string; orderId: string; provider: MarketplaceProvider },
|
|
55
|
+
input: { clientId: string; orderId: string; provider: MarketplaceProvider; deferredConfirmations?: boolean },
|
|
43
56
|
): Promise<void> {
|
|
44
|
-
|
|
45
|
-
const
|
|
57
|
+
const adapter = ctx.registry.get(input.provider);
|
|
58
|
+
const deferred = input.deferredConfirmations === true && adapter?.capabilities.marketplaceConfirms === true;
|
|
59
|
+
if (!adapter?.orderCancellationReasons && !deferred) return;
|
|
60
|
+
const payload: CancellationReasonsJobPayload = {
|
|
61
|
+
clientId: input.clientId,
|
|
62
|
+
orderId: input.orderId,
|
|
63
|
+
...(deferred ? { deferredConfirmations: true as const } : {}),
|
|
64
|
+
};
|
|
46
65
|
const outcome = await ctx.ports.enqueue.enqueue(MARKETPLACE_CANCELLATION_REASONS_JOB, payload, {
|
|
47
66
|
dedupeKey: `${MARKETPLACE_CANCELLATION_REASONS_JOB}:${input.orderId}`,
|
|
48
67
|
});
|
|
@@ -78,6 +97,28 @@ async function keep(
|
|
|
78
97
|
return { kind: "done", count: reasons.length };
|
|
79
98
|
}
|
|
80
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Apply a confirmation deferred before this order. A failure is logged, never
|
|
102
|
+
* thrown: the reasons read still runs, and the expiry sweep applies it later.
|
|
103
|
+
*/
|
|
104
|
+
async function applyEarlyConfirmations(ctx: EngineContext, clientId: string, row: ReasonsRow): Promise<void> {
|
|
105
|
+
try {
|
|
106
|
+
await applyDeferredConfirmations(ctx, { clientId, provider: row.provider, externalOrderId: row.externalOrderId });
|
|
107
|
+
} catch (error) {
|
|
108
|
+
ctx.ports.logger.warn(`${MARKETPLACE_CANCELLATION_REASONS_JOB}: order ${row.orderId}: a deferred confirmation was not applied; the expiry sweep applies it`, error);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The order's acceptance row; for an order not auto-accepted, its early confirmations applied first. */
|
|
113
|
+
async function loadOrder(ctx: EngineContext, db: MarketplaceDb, payload: CancellationReasonsJobPayload): Promise<ReasonsRow | null> {
|
|
114
|
+
const row = (await db.marketplaceAcceptance.findFirst({
|
|
115
|
+
where: { orderId: payload.orderId, clientId: payload.clientId },
|
|
116
|
+
select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
|
|
117
|
+
})) as ReasonsRow | null;
|
|
118
|
+
if (row && payload.deferredConfirmations) await applyEarlyConfirmations(ctx, payload.clientId, row);
|
|
119
|
+
return row;
|
|
120
|
+
}
|
|
121
|
+
|
|
81
122
|
/** Run one read. Throws {@link CancellationReasonsRetryError} for a retryable answer before the last attempt. */
|
|
82
123
|
export async function runCancellationReasons(
|
|
83
124
|
ctx: EngineContext,
|
|
@@ -85,10 +126,7 @@ export async function runCancellationReasons(
|
|
|
85
126
|
attempt: { attempt: number; maxAttempts: number },
|
|
86
127
|
): Promise<CancellationReasonsOutcome> {
|
|
87
128
|
const db = await ctx.ports.db();
|
|
88
|
-
const row =
|
|
89
|
-
where: { orderId: payload.orderId, clientId: payload.clientId },
|
|
90
|
-
select: { orderId: true, provider: true, externalOrderId: true, cancellationReasons: true },
|
|
91
|
-
})) as ReasonsRow | null;
|
|
129
|
+
const row = await loadOrder(ctx, db, payload);
|
|
92
130
|
if (!row) return { kind: "skipped", reason: "no acceptance for this order" };
|
|
93
131
|
if (storedReasons(row.cancellationReasons) !== null) return { kind: "skipped", reason: "the order's reasons are already kept" };
|
|
94
132
|
const read = ctx.registry.get(row.provider)?.orderCancellationReasons;
|
package/src/ifood/index.ts
CHANGED
|
@@ -126,3 +126,16 @@ export { IFOOD_LINKING } from "./linking";
|
|
|
126
126
|
export { IFOOD_COURIER, readIfoodCourierEvent } from "./courier";
|
|
127
127
|
export { IFOOD_IMAGE_BASE_URL } from "./catalogue-snapshot";
|
|
128
128
|
export { IFOOD_AVAILABILITY, ifoodLocalTime, ifoodPause, ifoodResume } from "./pause";
|
|
129
|
+
export {
|
|
130
|
+
IFOOD_LOGISTICS_STEPS,
|
|
131
|
+
IFOOD_LOGISTICS_VEHICLES,
|
|
132
|
+
ifoodLogisticsAssignDriver,
|
|
133
|
+
ifoodLogisticsStep,
|
|
134
|
+
ifoodLogisticsStepsTo,
|
|
135
|
+
ifoodLogisticsVerifyDeliveryCode,
|
|
136
|
+
type IfoodDeliveryCodeResult,
|
|
137
|
+
type IfoodLogisticsDriver,
|
|
138
|
+
type IfoodLogisticsInvalid,
|
|
139
|
+
type IfoodLogisticsStep,
|
|
140
|
+
type IfoodLogisticsVehicle,
|
|
141
|
+
} from "./logistics";
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { answered, outboundResultOf, type AdapterCallContext, type OutboundResult } from "../core/adapter";
|
|
2
|
+
import { IFOOD_API, withIfoodToken } from "./outbound";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* iFood's LOGISTICS module (FUT-5988): the store's own motoboy carries an
|
|
6
|
+
* iFood order, and the software reports each step of that delivery to iFood,
|
|
7
|
+
* so the customer follows it in the iFood app.
|
|
8
|
+
*
|
|
9
|
+
* Wire format only, like `./outbound.ts`: the URLs, the bodies and how each
|
|
10
|
+
* answer reads. Which step is sent when, and the job that sends it, are the
|
|
11
|
+
* caller's. Read off iFood's Logistics guides on 2026-12-01 (the ticket's
|
|
12
|
+
* comment lists the pages):
|
|
13
|
+
*
|
|
14
|
+
* - base `https://merchant-api.ifood.com.br/logistics/v1.0`;
|
|
15
|
+
* - `POST /orders/{id}/assignDriver` with `workerName`, `workerPhone`,
|
|
16
|
+
* `workerVehicleType`;
|
|
17
|
+
* - `POST /orders/{id}/goingToOrigin`, `/arrivedAtOrigin`, `/dispatch`,
|
|
18
|
+
* `/arrivedAtDestination`, no body;
|
|
19
|
+
* - `POST /orders/{id}/verifyDeliveryCode` with `code`, answering `success`;
|
|
20
|
+
* - the steps go in a strict order: out of order is 409, verifying before the
|
|
21
|
+
* code was requested (`DELIVERY_DROP_CODE_REQUESTED`) is 412, a wrong code
|
|
22
|
+
* is 422. The step calls are asynchronous (202): their outcome is an event.
|
|
23
|
+
*
|
|
24
|
+
* Logistics is a SEPARATE iFood app (category Logística, centralized), so the
|
|
25
|
+
* context carries THAT app's credentials, never the store's PDV app: its
|
|
26
|
+
* token is cached under its own client id by `bearer`, apart from the PDV
|
|
27
|
+
* app's. No GPS: the guides have no endpoint for the motoboy's position.
|
|
28
|
+
*
|
|
29
|
+
* Tests never reach iFood: the HTTP client is the host's port.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
const logisticsUrl = (externalOrderId: string, action: string): string =>
|
|
33
|
+
`${IFOOD_API}/logistics/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`;
|
|
34
|
+
|
|
35
|
+
/** The vehicles iFood takes in `workerVehicleType`. */
|
|
36
|
+
export const IFOOD_LOGISTICS_VEHICLES = [
|
|
37
|
+
"BICYCLE",
|
|
38
|
+
"ONFOOT",
|
|
39
|
+
"PATINETE",
|
|
40
|
+
"EBIKE",
|
|
41
|
+
"SUPERBIKE",
|
|
42
|
+
"CAR",
|
|
43
|
+
"MOTORCYCLE",
|
|
44
|
+
"MOTORBIKE",
|
|
45
|
+
] as const;
|
|
46
|
+
|
|
47
|
+
export type IfoodLogisticsVehicle = (typeof IFOOD_LOGISTICS_VEHICLES)[number];
|
|
48
|
+
|
|
49
|
+
/** The steps after the driver is assigned, in the one order iFood accepts them. */
|
|
50
|
+
export const IFOOD_LOGISTICS_STEPS = ["GOING_TO_ORIGIN", "ARRIVED_AT_ORIGIN", "DISPATCHED", "ARRIVED_AT_DESTINATION"] as const;
|
|
51
|
+
|
|
52
|
+
export type IfoodLogisticsStep = (typeof IFOOD_LOGISTICS_STEPS)[number];
|
|
53
|
+
|
|
54
|
+
const STEP_ACTION: Readonly<Record<IfoodLogisticsStep, string>> = {
|
|
55
|
+
GOING_TO_ORIGIN: "goingToOrigin",
|
|
56
|
+
ARRIVED_AT_ORIGIN: "arrivedAtOrigin",
|
|
57
|
+
DISPATCHED: "dispatch",
|
|
58
|
+
ARRIVED_AT_DESTINATION: "arrivedAtDestination",
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The steps still owed, in order, to reach `target` when `lastSent` is the
|
|
63
|
+
* last one iFood took (null: only the driver was assigned). Empty when the
|
|
64
|
+
* target was already passed: iFood answers a repeated or earlier step with
|
|
65
|
+
* 409, so it is never sent.
|
|
66
|
+
*/
|
|
67
|
+
export function ifoodLogisticsStepsTo(lastSent: IfoodLogisticsStep | null, target: IfoodLogisticsStep): IfoodLogisticsStep[] {
|
|
68
|
+
const from = lastSent === null ? 0 : IFOOD_LOGISTICS_STEPS.indexOf(lastSent) + 1;
|
|
69
|
+
const to = IFOOD_LOGISTICS_STEPS.indexOf(target);
|
|
70
|
+
return to < from ? [] : IFOOD_LOGISTICS_STEPS.slice(from, to + 1);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Who carries the order, as iFood shows them to the customer. */
|
|
74
|
+
export interface IfoodLogisticsDriver {
|
|
75
|
+
name: string;
|
|
76
|
+
/**
|
|
77
|
+
* Digits only once sent; anything else in it (spaces, `+`, dashes) is
|
|
78
|
+
* dropped. 10 to 13 digits is this client's own bound, not iFood's.
|
|
79
|
+
*/
|
|
80
|
+
phone: string;
|
|
81
|
+
vehicle: IfoodLogisticsVehicle;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A call refused here, before reaching iFood: nothing was sent. */
|
|
85
|
+
export interface IfoodLogisticsInvalid {
|
|
86
|
+
kind: "invalid";
|
|
87
|
+
reason: "DRIVER_NAME" | "DRIVER_PHONE" | "DRIVER_VEHICLE" | "CODE";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The context a Logistics call runs on: the Logistics app's own credentials,
|
|
92
|
+
* always through a client-credentials grant. A linked store's grant is the
|
|
93
|
+
* PDV app's, so it is dropped here, never used (and never forgotten on a 401).
|
|
94
|
+
*/
|
|
95
|
+
function logisticsApp(ctx: AdapterCallContext): AdapterCallContext {
|
|
96
|
+
return { http: ctx.http, credentials: ctx.credentials, environment: ctx.environment, tokens: ctx.tokens, now: ctx.now };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* A result with iFood's answer body left out: a validation answer may echo the
|
|
101
|
+
* motoboy's phone or the customer's code, and a result's text reaches logs.
|
|
102
|
+
*/
|
|
103
|
+
function redacted(result: OutboundResult, status: number): OutboundResult {
|
|
104
|
+
if (result.kind === "refused") return { ...result, message: `iFood Logistics answered ${status}` };
|
|
105
|
+
if (result.kind === "retry") return { kind: "retry", reason: `iFood Logistics answered ${status}` };
|
|
106
|
+
return result;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function post(ctx: AdapterCallContext, url: string, body?: unknown): Promise<{ result: OutboundResult; body: string }> {
|
|
110
|
+
let answer = "";
|
|
111
|
+
return answered(async () => {
|
|
112
|
+
const response = await withIfoodToken(logisticsApp(ctx), (token) =>
|
|
113
|
+
ctx.http({
|
|
114
|
+
method: "POST",
|
|
115
|
+
url,
|
|
116
|
+
headers: { Authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "Content-Type": "application/json" }) },
|
|
117
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
118
|
+
}),
|
|
119
|
+
);
|
|
120
|
+
if (response === null) return { kind: "retry", reason: "iFood refused the token" };
|
|
121
|
+
if ("kind" in response) return response;
|
|
122
|
+
answer = response.body;
|
|
123
|
+
return redacted(outboundResultOf(response), response.status);
|
|
124
|
+
}).then((result) => ({ result, body: answer }));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* `assignDriver`: the store's motoboy takes the order. A second assignment of
|
|
129
|
+
* the same order is iFood's 409, answered as `refused` like any final 4xx.
|
|
130
|
+
*/
|
|
131
|
+
export async function ifoodLogisticsAssignDriver(
|
|
132
|
+
ctx: AdapterCallContext,
|
|
133
|
+
externalOrderId: string,
|
|
134
|
+
driver: IfoodLogisticsDriver,
|
|
135
|
+
): Promise<OutboundResult | IfoodLogisticsInvalid> {
|
|
136
|
+
const name = driver.name.trim();
|
|
137
|
+
const phone = driver.phone.replace(/\D/g, "");
|
|
138
|
+
if (name === "") return { kind: "invalid", reason: "DRIVER_NAME" };
|
|
139
|
+
if (phone.length < 10 || phone.length > 13) return { kind: "invalid", reason: "DRIVER_PHONE" };
|
|
140
|
+
if (!(IFOOD_LOGISTICS_VEHICLES as readonly string[]).includes(driver.vehicle)) return { kind: "invalid", reason: "DRIVER_VEHICLE" };
|
|
141
|
+
const { result } = await post(ctx, logisticsUrl(externalOrderId, "assignDriver"), {
|
|
142
|
+
workerName: name,
|
|
143
|
+
workerPhone: phone,
|
|
144
|
+
workerVehicleType: driver.vehicle,
|
|
145
|
+
});
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** One step of the delivery. iFood takes it asynchronously: `accepted` means the request was taken. */
|
|
150
|
+
export async function ifoodLogisticsStep(ctx: AdapterCallContext, externalOrderId: string, step: IfoodLogisticsStep): Promise<OutboundResult> {
|
|
151
|
+
const { result } = await post(ctx, logisticsUrl(externalOrderId, STEP_ACTION[step]));
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What iFood said of the customer's delivery code. */
|
|
156
|
+
export type IfoodDeliveryCodeResult =
|
|
157
|
+
| { kind: "verified" }
|
|
158
|
+
/** iFood's `success: false`, or its 422: the motoboy may type it again. */
|
|
159
|
+
| { kind: "wrong-code" }
|
|
160
|
+
/** iFood's 412: the order never asked for a code (no `DELIVERY_DROP_CODE_REQUESTED`). */
|
|
161
|
+
| { kind: "not-requested" }
|
|
162
|
+
| Exclude<OutboundResult, { kind: "accepted" }>
|
|
163
|
+
| IfoodLogisticsInvalid;
|
|
164
|
+
|
|
165
|
+
function successOf(body: string): boolean | null {
|
|
166
|
+
try {
|
|
167
|
+
const parsed = JSON.parse(body) as { success?: unknown } | null;
|
|
168
|
+
return typeof parsed?.success === "boolean" ? parsed.success : null;
|
|
169
|
+
} catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `verifyDeliveryCode`: the code the customer reads from the iFood app,
|
|
176
|
+
* typed by the motoboy at the door. The code is in the request body only, and
|
|
177
|
+
* no result carries iFood's answer body, so nothing here puts it in a log.
|
|
178
|
+
*/
|
|
179
|
+
export async function ifoodLogisticsVerifyDeliveryCode(
|
|
180
|
+
ctx: AdapterCallContext,
|
|
181
|
+
externalOrderId: string,
|
|
182
|
+
code: string,
|
|
183
|
+
): Promise<IfoodDeliveryCodeResult> {
|
|
184
|
+
const typed = code.replace(/\s/g, "");
|
|
185
|
+
if (!/^[0-9A-Za-z]{1,12}$/.test(typed)) return { kind: "invalid", reason: "CODE" };
|
|
186
|
+
const { result, body } = await post(ctx, logisticsUrl(externalOrderId, "verifyDeliveryCode"), { code: typed });
|
|
187
|
+
if (result.kind === "accepted") {
|
|
188
|
+
const success = successOf(body);
|
|
189
|
+
if (success === null) return { kind: "retry", reason: "iFood answered the delivery code without `success`" };
|
|
190
|
+
return success ? { kind: "verified" } : { kind: "wrong-code" };
|
|
191
|
+
}
|
|
192
|
+
if (result.kind === "refused" && result.status === 422) return { kind: "wrong-code" };
|
|
193
|
+
if (result.kind === "refused" && result.status === 412) return { kind: "not-requested" };
|
|
194
|
+
return result;
|
|
195
|
+
}
|
package/src/ifood/outbound.ts
CHANGED
|
@@ -96,7 +96,7 @@ export async function bearer(ctx: AdapterCallContext): Promise<{ token: string }
|
|
|
96
96
|
* (iFood: "Prepare seu aplicativo para solicitar um novo token quando receber
|
|
97
97
|
* status 401"). A second 401 forgets that one too and answers `null`.
|
|
98
98
|
*/
|
|
99
|
-
async function withIfoodToken(
|
|
99
|
+
export async function withIfoodToken(
|
|
100
100
|
ctx: AdapterCallContext,
|
|
101
101
|
call: (token: string) => Promise<MarketplaceHttpResponse>,
|
|
102
102
|
): Promise<MarketplaceHttpResponse | OutboundResult | null> {
|