@12-apps/marketplace 1.13.0 → 1.14.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.
Files changed (60) hide show
  1. package/ADOPTING.md +143 -3
  2. package/README.md +27 -2
  3. package/dist/99food/index.d.ts +2 -2
  4. package/dist/99food/index.js +2 -2
  5. package/dist/{adapter-CQ4QiZPi.d.ts → adapter-szxo9ohc.d.ts} +82 -2
  6. package/dist/{chunk-NFJQQWG4.js → chunk-BNWRIR5J.js} +2 -2
  7. package/dist/{chunk-4J2KJ3ZW.js → chunk-BTKVZAJI.js} +1 -1
  8. package/dist/chunk-BTKVZAJI.js.map +1 -0
  9. package/dist/{chunk-CEWTV2TC.js → chunk-MDXSVE7Q.js} +652 -246
  10. package/dist/chunk-MDXSVE7Q.js.map +1 -0
  11. package/dist/{chunk-W57TITU4.js → chunk-R3BUW5PX.js} +53 -6
  12. package/dist/chunk-R3BUW5PX.js.map +1 -0
  13. package/dist/{client-CCSnylou.d.ts → client-CaZiG7Lw.d.ts} +1 -1
  14. package/dist/{engine-1KlJ_8jK.d.ts → engine-CgKBbk9J.d.ts} +127 -3
  15. package/dist/hono/index.d.ts +2 -2
  16. package/dist/hono/index.js +2 -2
  17. package/dist/ifood/index.d.ts +13 -3
  18. package/dist/ifood/index.js +114 -23
  19. package/dist/ifood/index.js.map +1 -1
  20. package/dist/index.d.ts +29 -5
  21. package/dist/index.js +54 -6
  22. package/dist/index.js.map +1 -1
  23. package/dist/keeta/index.d.ts +2 -2
  24. package/dist/keeta/index.js +2 -2
  25. package/dist/manifest/server.d.ts +4 -2
  26. package/dist/manifest/server.js +2 -2
  27. package/dist/rappi/index.d.ts +1 -1
  28. package/dist/rappi/index.js +1 -1
  29. package/dist/server/index.d.ts +14 -5
  30. package/dist/server/index.js +2 -2
  31. package/package.json +1 -1
  32. package/prisma/marketplace.prisma +17 -3
  33. package/prisma/migrations/20261202120000_marketplace_ifood_conformity/migration.sql +25 -0
  34. package/src/core/acceptance.ts +12 -6
  35. package/src/core/acknowledge.ts +189 -0
  36. package/src/core/adapter.ts +74 -1
  37. package/src/core/cancellation.ts +10 -6
  38. package/src/core/conformity.ts +63 -0
  39. package/src/core/engine.ts +3 -2
  40. package/src/core/ingest.ts +6 -0
  41. package/src/core/link-store.ts +2 -4
  42. package/src/core/marketplace-confirmed.ts +229 -0
  43. package/src/core/order-reasons.ts +119 -0
  44. package/src/core/outbound.ts +5 -1
  45. package/src/core/pipeline.ts +27 -1
  46. package/src/core/ports.ts +2 -0
  47. package/src/core/registry.ts +28 -2
  48. package/src/core/state.ts +10 -0
  49. package/src/core/status-job.ts +86 -3
  50. package/src/core/types.ts +6 -0
  51. package/src/ifood/index.ts +27 -4
  52. package/src/ifood/normalize.ts +16 -0
  53. package/src/ifood/outbound.ts +131 -27
  54. package/src/index.ts +18 -0
  55. package/src/server/jobs.ts +57 -4
  56. package/src/server/webhook.ts +27 -4
  57. package/dist/chunk-4J2KJ3ZW.js.map +0 -1
  58. package/dist/chunk-CEWTV2TC.js.map +0 -1
  59. package/dist/chunk-W57TITU4.js.map +0 -1
  60. /package/dist/{chunk-NFJQQWG4.js.map → chunk-BNWRIR5J.js.map} +0 -0
@@ -17,7 +17,7 @@ import {
17
17
  answered,
18
18
  outboundResultOf,
19
19
  tokenGrantResultOf
20
- } from "../chunk-4J2KJ3ZW.js";
20
+ } from "../chunk-BTKVZAJI.js";
21
21
  import {
22
22
  __name
23
23
  } from "../chunk-7QVYU63E.js";
@@ -43,7 +43,6 @@ var IFOOD_API = "https://merchant-api.ifood.com.br";
43
43
  var TOKEN_URL = `${IFOOD_API}/authentication/v1.0/oauth/token`;
44
44
  var orderUrl = /* @__PURE__ */ __name((externalOrderId, action) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}/${action}`, "orderUrl");
45
45
  var IFOOD_PORTAL_URL = "https://portal.ifood.com.br/";
46
- var TOKEN_MARGIN_MS = 6e4;
47
46
  var ifoodTokenKey = /* @__PURE__ */ __name((ctx) => ctx.grant ? ctx.grant.key : `IFOOD:${ctx.environment}:${ctx.credentials.clientId}`, "ifoodTokenKey");
48
47
  function tokenOf(body) {
49
48
  try {
@@ -60,7 +59,7 @@ async function bearer(ctx) {
60
59
  if (ctx.grant) return ctx.grant.accessToken();
61
60
  const key = ifoodTokenKey(ctx);
62
61
  const cached = ctx.tokens.get(key);
63
- if (cached && cached.expiresAt > ctx.now.getTime() + TOKEN_MARGIN_MS) return { token: cached.token };
62
+ if (cached && cached.expiresAt > ctx.now.getTime()) return { token: cached.token };
64
63
  const response = await ctx.http({
65
64
  method: "POST",
66
65
  url: TOKEN_URL,
@@ -78,39 +77,109 @@ async function bearer(ctx) {
78
77
  return { token: token.token };
79
78
  }
80
79
  __name(bearer, "bearer");
81
- function postOrder(ctx, externalOrderId, action, body) {
82
- return answered(async () => {
80
+ async function withIfoodToken(ctx, call5) {
81
+ for (let round = 0; round < 2; round += 1) {
83
82
  const auth = await bearer(ctx);
84
83
  if (!("token" in auth)) return auth;
85
- const response = await ctx.http({
86
- method: "POST",
87
- url: orderUrl(externalOrderId, action),
88
- headers: {
89
- Authorization: `Bearer ${auth.token}`,
90
- ...body === void 0 ? {} : { "Content-Type": "application/json" }
91
- },
92
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
93
- });
94
- if (response.status === 401) ctx.tokens.delete(ifoodTokenKey(ctx));
95
- return response.status === 401 ? { kind: "retry", reason: "iFood refused the token" } : outboundResultOf(response);
84
+ const response = await call5(auth.token);
85
+ if (response.status !== 401) return response;
86
+ ctx.tokens.delete(ifoodTokenKey(ctx));
87
+ }
88
+ return null;
89
+ }
90
+ __name(withIfoodToken, "withIfoodToken");
91
+ function callOrder(ctx, externalOrderId, action, body, method = "POST") {
92
+ return answered(async () => {
93
+ const response = await withIfoodToken(
94
+ ctx,
95
+ (token) => ctx.http({
96
+ method,
97
+ url: orderUrl(externalOrderId, action),
98
+ headers: {
99
+ Authorization: `Bearer ${token}`,
100
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
101
+ },
102
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
103
+ })
104
+ );
105
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
106
+ return "kind" in response ? response : outboundResultOf(response);
96
107
  });
97
108
  }
109
+ __name(callOrder, "callOrder");
110
+ function postOrder(ctx, externalOrderId, action, body) {
111
+ return callOrder(ctx, externalOrderId, action, body);
112
+ }
98
113
  __name(postOrder, "postOrder");
99
114
  function ifoodConfirm(ctx, order) {
100
115
  return postOrder(ctx, order.externalOrderId, "confirm");
101
116
  }
102
117
  __name(ifoodConfirm, "ifoodConfirm");
103
118
  function ifoodRequestCancellation(ctx, order, input) {
104
- return postOrder(ctx, order.externalOrderId, "requestCancellation", {
105
- reason: input.text === "" ? input.reason.label : input.text,
106
- cancellationCode: input.reason.code
107
- });
119
+ return postOrder(ctx, order.externalOrderId, "requestCancellation", { reason: input.reason.code });
108
120
  }
109
121
  __name(ifoodRequestCancellation, "ifoodRequestCancellation");
122
+ function reasonsOf(body) {
123
+ try {
124
+ const parsed2 = JSON.parse(body);
125
+ const list2 = Array.isArray(parsed2) ? parsed2 : parsed2?.reasons;
126
+ if (!Array.isArray(list2)) return null;
127
+ return list2.flatMap((entry) => {
128
+ const { code, description } = entry ?? {};
129
+ if (typeof code !== "string" && typeof code !== "number") return [];
130
+ return [{ code: String(code), description: typeof description === "string" ? description : String(code) }];
131
+ });
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+ __name(reasonsOf, "reasonsOf");
137
+ async function ifoodOrderCancellationReasons(ctx, order) {
138
+ let body = "";
139
+ const result = await answered(async () => {
140
+ const response = await withIfoodToken(
141
+ ctx,
142
+ (token) => ctx.http({ method: "GET", url: orderUrl(order.externalOrderId, "cancellationReasons"), headers: { Authorization: `Bearer ${token}` } })
143
+ );
144
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
145
+ if ("kind" in response) return response;
146
+ body = response.body;
147
+ return outboundResultOf(response);
148
+ });
149
+ if (result.kind !== "accepted") return result;
150
+ const reasons = reasonsOf(body);
151
+ return reasons ? { kind: "reasons", reasons } : { kind: "retry", reason: "iFood answered the reasons with no list" };
152
+ }
153
+ __name(ifoodOrderCancellationReasons, "ifoodOrderCancellationReasons");
154
+ var IFOOD_EVENT_RETENTION_MS = 8 * 60 * 6e4;
155
+ var IFOOD_ACKNOWLEDGEMENT = {
156
+ batchSize: 2e3,
157
+ retentionMs: IFOOD_EVENT_RETENTION_MS,
158
+ send: /* @__PURE__ */ __name((ctx, eventIds) => answered(async () => {
159
+ const body = JSON.stringify(eventIds.map((id) => ({ id })));
160
+ const response = await withIfoodToken(
161
+ ctx,
162
+ (token) => ctx.http({
163
+ method: "POST",
164
+ url: `${IFOOD_API}/events/v1.0/events/acknowledgment`,
165
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
166
+ body
167
+ })
168
+ );
169
+ if (response === null) return { kind: "retry", reason: "iFood refused the token" };
170
+ return "kind" in response ? response : outboundResultOf(response);
171
+ }), "send")
172
+ };
110
173
  var STATUS_ACTION = {
111
- READY: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? null : "readyToPickup", "READY"),
174
+ // Every order, the merchant's own bag included (FUT-5984, `endpoints.md`: "Para entrega própria,
175
+ // notifique o pedido pronto via `POST /orders/{id}/readyToPickup` antes de despachar via `/dispatch`").
176
+ READY: /* @__PURE__ */ __name(() => "readyToPickup", "READY"),
112
177
  DISPATCHED: /* @__PURE__ */ __name((facts) => facts.deliveredBy === "MERCHANT" ? "dispatch" : null, "DISPATCHED")
113
178
  };
179
+ function ifoodStatusPrerequisite(facts) {
180
+ return facts.step === "DISPATCHED" && facts.deliveredBy === "MERCHANT" ? "READY" : null;
181
+ }
182
+ __name(ifoodStatusPrerequisite, "ifoodStatusPrerequisite");
114
183
  function ifoodStatusSupported(facts) {
115
184
  return STATUS_ACTION[facts.step]?.(facts) != null;
116
185
  }
@@ -705,6 +774,8 @@ var IFOOD_COURIER = { validatePickupCode, tracking };
705
774
  // src/ifood/normalize.ts
706
775
  var ORDER_PLACED = /* @__PURE__ */ new Set(["PLC", "PLACED", "ORDER_PLACED"]);
707
776
  var ORDER_CANCELLED = /* @__PURE__ */ new Set(["CAN", "CANCELLED", "ORDER_CANCELLED"]);
777
+ var ORDER_CONFIRMED = /* @__PURE__ */ new Set(["CFM", "CONFIRMED"]);
778
+ var KEEPALIVE = "KEEPALIVE";
708
779
  var CANCELLATION_REQUEST_FAILED = /* @__PURE__ */ new Set(["CARF", "CANCELLATION_REQUEST_FAILED"]);
709
780
  var LIFECYCLE_OF = {
710
781
  DSP: "DISPATCHED",
@@ -862,10 +933,18 @@ function normalizeIfoodEvent(payload, options) {
862
933
  cancelled,
863
934
  cancellationOutcome: cancelled ? "CONFIRMED" : refusedRequest ? "FAILED" : null,
864
935
  ...LIFECYCLE_OF[eventType.toUpperCase()] ? { lifecycle: LIFECYCLE_OF[eventType.toUpperCase()] } : {},
865
- ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? void 0)
936
+ ...optional("courier", readIfoodCourierEvent(payload, eventType) ?? void 0),
937
+ ...ORDER_CONFIRMED.has(eventType.toUpperCase()) ? { marketplaceConfirmed: true } : {}
866
938
  };
867
939
  }
868
940
  __name(normalizeIfoodEvent, "normalizeIfoodEvent");
941
+ function readIfoodPresence(payload) {
942
+ const code = firstString(payload, [["fullCode"], ["code"]]);
943
+ if (code?.toUpperCase() !== KEEPALIVE) return null;
944
+ const ids = pick(payload, "merchantIds");
945
+ return { merchantIds: Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : null };
946
+ }
947
+ __name(readIfoodPresence, "readIfoodPresence");
869
948
 
870
949
  // src/ifood/fetch-order.ts
871
950
  var orderResourceUrl = /* @__PURE__ */ __name((externalOrderId) => `${IFOOD_API}/order/v1.0/orders/${encodeURIComponent(externalOrderId)}`, "orderResourceUrl");
@@ -1228,7 +1307,13 @@ function createIfoodAdapter(config) {
1228
1307
  // Told what iFood has an endpoint for (ESTIMATED, see `./outbound.ts`): ready for
1229
1308
  // pickup, and dispatched for a merchant bag. Never "handed over": iFood's own
1230
1309
  // CONCLUDED is that.
1231
- statusSteps: ["READY", "DISPATCHED"]
1310
+ statusSteps: ["READY", "DISPATCHED"],
1311
+ // "Retorne `202 Accepted` em até 5 segundos" (Events `webhook-overview`, FUT-5984).
1312
+ webhookAnswerStatus: 202,
1313
+ // CFM: the store accepted on iFood's own app (FUT-5653).
1314
+ marketplaceConfirms: true,
1315
+ // A step is told only once iFood took the confirm (FUT-5673).
1316
+ statusAfterConfirm: true
1232
1317
  },
1233
1318
  normalize: /* @__PURE__ */ __name((payload) => normalizeIfoodEvent(payload, normalizeOptions), "normalize"),
1234
1319
  readSignature: /* @__PURE__ */ __name((header) => header("x-ifood-signature") ?? header("x-signature"), "readSignature"),
@@ -1244,6 +1329,11 @@ function createIfoodAdapter(config) {
1244
1329
  fetchOrder: /* @__PURE__ */ __name((ctx, order) => ifoodFetchOrder(ctx, order, normalizeOptions), "fetchOrder"),
1245
1330
  statusSupported: ifoodStatusSupported,
1246
1331
  informStatus: ifoodInformStatus,
1332
+ statusPrerequisite: ifoodStatusPrerequisite,
1333
+ // The presence heartbeat, the events' acknowledgment and each order's own reasons (FUT-5984).
1334
+ presence: readIfoodPresence,
1335
+ acknowledgement: IFOOD_ACKNOWLEDGEMENT,
1336
+ orderCancellationReasons: ifoodOrderCancellationReasons,
1247
1337
  // The Merchant API's interruptions: an id and an end per closure (FUT-4851).
1248
1338
  availability: IFOOD_AVAILABILITY,
1249
1339
  // The distributed-app authorization: a store links the software's own app (FUT-5613).
@@ -1277,6 +1367,7 @@ export {
1277
1367
  normalizeIfoodEvent,
1278
1368
  readIfoodCourierEvent,
1279
1369
  readIfoodOrder,
1370
+ readIfoodPresence,
1280
1371
  verifyIfoodSignature
1281
1372
  };
1282
1373
  //# sourceMappingURL=index.js.map