@12-apps/marketplace 1.16.0 → 1.18.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 +185 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-ZpAWKoCk.d.ts} +300 -3
- package/dist/{chunk-TRUK5ZBE.js → chunk-3B5EULS6.js} +2 -2
- package/dist/{chunk-DJIMUEHT.js → chunk-BLHZ3MRB.js} +79 -7
- package/dist/chunk-BLHZ3MRB.js.map +1 -0
- package/dist/{chunk-SGOTN5PX.js → chunk-LO7OKO6V.js} +45 -4
- package/dist/chunk-LO7OKO6V.js.map +1 -0
- package/dist/{chunk-TICWLBSA.js → chunk-MDEIRGNL.js} +1372 -823
- package/dist/chunk-MDEIRGNL.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-Q5RMVNU5.js} +1 -1
- package/dist/chunk-Q5RMVNU5.js.map +1 -0
- package/dist/{chunk-BTKVZAJI.js → chunk-ZT6TZTLD.js} +1 -1
- package/dist/chunk-ZT6TZTLD.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-DpEq0yXb.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-DRRhAjZK.d.ts} +566 -293
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +14 -2
- package/dist/ifood/index.js +406 -120
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +453 -43
- package/dist/index.js.map +1 -1
- package/dist/keeta/index.d.ts +2 -2
- package/dist/keeta/index.js +2 -2
- package/dist/manifest/index.d.ts +78 -0
- package/dist/manifest/index.js +1 -1
- package/dist/manifest/server.d.ts +6 -2
- package/dist/manifest/server.js +4 -4
- package/dist/rappi/index.d.ts +1 -1
- package/dist/rappi/index.js +1 -1
- package/dist/server/index.d.ts +93 -7
- package/dist/server/index.js +4 -4
- package/package.json +1 -1
- package/prisma/marketplace.prisma +70 -2
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/prisma/migrations/20261203200000_marketplace_status_logistics_steps/migration.sql +12 -0
- package/src/core/adapter.ts +14 -2
- package/src/core/app-linking.ts +396 -0
- package/src/core/delivery-code.ts +119 -0
- package/src/core/dispute-engine.ts +32 -0
- package/src/core/dispute-job.ts +142 -0
- package/src/core/dispute-port.ts +133 -0
- package/src/core/dispute-store.ts +203 -0
- package/src/core/disputes.ts +263 -0
- package/src/core/engine.ts +12 -55
- package/src/core/integration.ts +3 -1
- package/src/core/link-engine.ts +176 -0
- package/src/core/link-store.ts +15 -0
- package/src/core/linking-port.ts +35 -1
- package/src/core/linking.ts +8 -0
- package/src/core/logistics.ts +388 -0
- package/src/core/outbound-queue.ts +6 -1
- package/src/core/outbound-sweep.ts +19 -6
- package/src/core/outbound.ts +4 -5
- package/src/core/pipeline.ts +14 -4
- package/src/core/ports.ts +20 -2
- package/src/core/status-job.ts +3 -0
- package/src/core/status-store.ts +2 -1
- package/src/core/types.ts +10 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +15 -1
- package/src/ifood/logistics.ts +38 -0
- package/src/ifood/normalize.ts +14 -1
- package/src/index.ts +44 -0
- package/src/server/jobs.ts +51 -3
- package/src/server/link-routes.ts +56 -4
- package/src/server/mcp-link.ts +44 -2
- package/src/server/mcp.ts +2 -1
- package/dist/chunk-BTKVZAJI.js.map +0 -1
- package/dist/chunk-DJIMUEHT.js.map +0 -1
- package/dist/chunk-H2VQRD3B.js.map +0 -1
- package/dist/chunk-SGOTN5PX.js.map +0 -1
- package/dist/chunk-TICWLBSA.js.map +0 -1
- /package/dist/{chunk-TRUK5ZBE.js.map → chunk-3B5EULS6.js.map} +0 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { DisputeAnswer, DisputeAnswerResult, DisputeFailureCode, MarketplaceDisputeDelegate } from "./dispute-port";
|
|
2
|
+
import { MARKETPLACE_DISPUTE_ANSWER_JOB, alternativesOf, disputeTable, findDispute, type DisputeRow } from "./dispute-store";
|
|
3
|
+
import { enqueueDisputeAnswer } from "./disputes";
|
|
4
|
+
import { readOutboundConnection } from "./integration";
|
|
5
|
+
import type { EngineContext } from "./ports";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The `marketplace.dispute-answer` job (FUT-6099): sends one claimed answer
|
|
9
|
+
* and stamps what the marketplace said. Idempotent by the row: only a SENDING
|
|
10
|
+
* row is sent, so a duplicate run calls nobody.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** The job's payload: identifiers only. */
|
|
14
|
+
export interface DisputeAnswerJobPayload {
|
|
15
|
+
clientId: string;
|
|
16
|
+
/** The marketplace's id for the dispute. */
|
|
17
|
+
disputeId: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type DisputeAnswerOutcome =
|
|
21
|
+
| { kind: "skipped"; reason: string }
|
|
22
|
+
| { kind: "answered" }
|
|
23
|
+
| { kind: "failed"; code: DisputeFailureCode };
|
|
24
|
+
|
|
25
|
+
/** Thrown so the queue retries. */
|
|
26
|
+
export class DisputeAnswerRetryError extends Error {
|
|
27
|
+
constructor(message: string) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "DisputeAnswerRetryError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The kept answer, as the adapter sends it; null when the row no longer holds one it can send. */
|
|
34
|
+
function answerToSend(row: DisputeRow): DisputeAnswer | null {
|
|
35
|
+
if (row.answer === "ACCEPT") return { kind: "ACCEPT", reasonCode: row.answerReasonCode };
|
|
36
|
+
if (row.answer === "REJECT") return row.answerReasonCode ? { kind: "REJECT", reasonCode: row.answerReasonCode } : null;
|
|
37
|
+
const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === row.answerAlternativeId);
|
|
38
|
+
if (row.answer !== "ALTERNATIVE" || !alternative) return null;
|
|
39
|
+
return { kind: "ALTERNATIVE", alternative, amountCents: row.answerAmountCents, minutes: row.answerMinutes };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Give the answer back: OPEN, with why, so a person answers again. */
|
|
43
|
+
async function giveBack(
|
|
44
|
+
ctx: EngineContext,
|
|
45
|
+
table: MarketplaceDisputeDelegate,
|
|
46
|
+
row: DisputeRow,
|
|
47
|
+
code: DisputeFailureCode,
|
|
48
|
+
): Promise<DisputeAnswerOutcome> {
|
|
49
|
+
await table.updateMany({
|
|
50
|
+
where: { id: row.id, status: "SENDING" },
|
|
51
|
+
data: {
|
|
52
|
+
status: "OPEN",
|
|
53
|
+
answerFailure: code,
|
|
54
|
+
answer: null,
|
|
55
|
+
answerReasonCode: null,
|
|
56
|
+
answerAlternativeId: null,
|
|
57
|
+
answerAmountCents: null,
|
|
58
|
+
answerMinutes: null,
|
|
59
|
+
answeredAt: null,
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not answered: ${code}`);
|
|
63
|
+
ctx.ports.publishChanged(row.clientId);
|
|
64
|
+
return { kind: "failed", code };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The marketplace took the answer, or someone else's answer stands: ANSWERED either way. */
|
|
68
|
+
async function stampAnswered(
|
|
69
|
+
ctx: EngineContext,
|
|
70
|
+
table: MarketplaceDisputeDelegate,
|
|
71
|
+
row: DisputeRow,
|
|
72
|
+
failure: DisputeFailureCode | null,
|
|
73
|
+
): Promise<DisputeAnswerOutcome> {
|
|
74
|
+
await table.updateMany({ where: { id: row.id, status: "SENDING" }, data: { status: "ANSWERED", answerFailure: failure } });
|
|
75
|
+
ctx.ports.publishChanged(row.clientId);
|
|
76
|
+
return { kind: "answered" };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** What the marketplace's answer makes of the row. */
|
|
80
|
+
async function settleSend(
|
|
81
|
+
ctx: EngineContext,
|
|
82
|
+
table: MarketplaceDisputeDelegate,
|
|
83
|
+
row: DisputeRow,
|
|
84
|
+
result: DisputeAnswerResult,
|
|
85
|
+
attempt: { attempt: number; maxAttempts: number },
|
|
86
|
+
): Promise<DisputeAnswerOutcome> {
|
|
87
|
+
if (result.kind === "accepted") return stampAnswered(ctx, table, row, null);
|
|
88
|
+
if (result.kind === "refused") {
|
|
89
|
+
return result.code === "ALREADY_ANSWERED" ? stampAnswered(ctx, table, row, "ALREADY_ANSWERED") : giveBack(ctx, table, row, result.code);
|
|
90
|
+
}
|
|
91
|
+
if (attempt.attempt < attempt.maxAttempts) throw new DisputeAnswerRetryError(`dispute ${row.disputeId}: ${result.reason}`);
|
|
92
|
+
return giveBack(ctx, table, row, "UNREACHABLE");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Run one send. Throws {@link DisputeAnswerRetryError} for a retryable answer before the last attempt. */
|
|
96
|
+
export async function runDisputeAnswer(
|
|
97
|
+
ctx: EngineContext,
|
|
98
|
+
payload: DisputeAnswerJobPayload,
|
|
99
|
+
attempt: { attempt: number; maxAttempts: number },
|
|
100
|
+
): Promise<DisputeAnswerOutcome> {
|
|
101
|
+
const table = await disputeTable(ctx);
|
|
102
|
+
const row = table ? await findDispute(table, payload.clientId, payload.disputeId) : null;
|
|
103
|
+
if (!table || !row || row.status !== "SENDING") return { kind: "skipped", reason: "no answer to send" };
|
|
104
|
+
const api = ctx.registry.get(row.provider)?.disputes;
|
|
105
|
+
const answer = answerToSend(row);
|
|
106
|
+
if (!api || !answer) return giveBack(ctx, table, row, "UNSUPPORTED");
|
|
107
|
+
const connection = await readOutboundConnection(ctx, row.clientId, row.provider).catch(() => null);
|
|
108
|
+
if (!connection) return giveBack(ctx, table, row, "NOT_CONNECTED");
|
|
109
|
+
const call = { http: ctx.ports.http, tokens: ctx.tokens, now: ctx.ports.clock.now(), ...connection };
|
|
110
|
+
const result = await api.answer(call, { externalOrderId: row.externalOrderId, disputeId: row.disputeId }, answer);
|
|
111
|
+
return settleSend(ctx, table, row, result, attempt);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** At most this many owed answers per pass: the next pass takes the rest. */
|
|
115
|
+
const SWEEP_BATCH = 100;
|
|
116
|
+
|
|
117
|
+
/** An answer still SENDING past this is owed: the job's three attempts are long over. */
|
|
118
|
+
const DISPUTE_STALE_MS = 10 * 60_000;
|
|
119
|
+
/** Past this the marketplace has long settled it on its own clock: given back OPEN, UNREACHABLE. */
|
|
120
|
+
const DISPUTE_GIVE_UP_MS = 24 * 60 * 60_000;
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The outbound sweep's dispute pass: re-queue an answer still SENDING after
|
|
124
|
+
* {@link DISPUTE_STALE_MS} (a refused enqueue, a dead process), under a key
|
|
125
|
+
* of its own per pass; give one older than a day back.
|
|
126
|
+
*/
|
|
127
|
+
export async function sweepDisputes(ctx: EngineContext, now: Date): Promise<{ requeued: number; givenUp: number }> {
|
|
128
|
+
const table = await disputeTable(ctx);
|
|
129
|
+
if (!table) return { requeued: 0, givenUp: 0 };
|
|
130
|
+
const stale = new Date(now.getTime() - DISPUTE_STALE_MS);
|
|
131
|
+
const giveUp = new Date(now.getTime() - DISPUTE_GIVE_UP_MS);
|
|
132
|
+
const rows = (await table.findMany({ where: { status: "SENDING", answeredAt: { lt: stale } }, orderBy: { answeredAt: "asc" }, take: SWEEP_BATCH })) as DisputeRow[];
|
|
133
|
+
let requeued = 0;
|
|
134
|
+
let givenUp = 0;
|
|
135
|
+
for (const row of rows) {
|
|
136
|
+
if (row.answeredAt !== null && row.answeredAt.getTime() < giveUp.getTime()) {
|
|
137
|
+
await giveBack(ctx, table, row, "UNREACHABLE");
|
|
138
|
+
givenUp += 1;
|
|
139
|
+
} else if (await enqueueDisputeAnswer(ctx, row, `sweep:${now.getTime()}`)) requeued += 1;
|
|
140
|
+
}
|
|
141
|
+
return { requeued, givenUp };
|
|
142
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { AdapterCallContext } from "./adapter";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A marketplace's disputes (FUT-6099): the buyer asks the marketplace for a
|
|
5
|
+
* refund or a change AFTER the order was placed (iFood's Negotiation Platform,
|
|
6
|
+
* "Plataforma de Negociação"), and the store answers: accept, reject with one
|
|
7
|
+
* of the marketplace's reasons, or offer one of the alternatives the
|
|
8
|
+
* marketplace sent. Provider-neutral: what a dispute carries is read by the
|
|
9
|
+
* adapter, kept by the engine, drawn and worded by the host.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The kinds of alternative a store may offer instead of what the buyer asked. */
|
|
13
|
+
export type DisputeAlternativeType = "REFUND" | "BENEFIT" | "ADDITIONAL_TIME";
|
|
14
|
+
|
|
15
|
+
/** One alternative the marketplace allows for THIS dispute. */
|
|
16
|
+
export interface DisputeAlternative {
|
|
17
|
+
/** The marketplace's id for it; sent back with the proposal. */
|
|
18
|
+
id: string;
|
|
19
|
+
type: DisputeAlternativeType;
|
|
20
|
+
/** A refund or a benefit: the most the store may offer, in cents; null when the marketplace states none. */
|
|
21
|
+
maxAmountCents: number | null;
|
|
22
|
+
/** More time: the minutes the marketplace allows, when it lists them; empty when it states none. */
|
|
23
|
+
allowedMinutes: number[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** One reason the marketplace accepts with an answer: its code and its own words. */
|
|
27
|
+
export interface DisputeReason {
|
|
28
|
+
code: string;
|
|
29
|
+
description: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** One line the buyer disputes, as the marketplace lists it. */
|
|
33
|
+
export interface DisputeItem {
|
|
34
|
+
name: string;
|
|
35
|
+
quantity: number;
|
|
36
|
+
/** What the line cost, in cents; null when unstated. */
|
|
37
|
+
amountCents: number | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A dispute the marketplace opened, normalized. */
|
|
41
|
+
export interface NormalizedDisputeOpened {
|
|
42
|
+
/** The marketplace's id for the dispute: the key of every answer. */
|
|
43
|
+
disputeId: string;
|
|
44
|
+
/** What the buyer asks, the marketplace's own code (iFood: CANCELLATION, PARTIAL_CANCELLATION, …). */
|
|
45
|
+
action: string;
|
|
46
|
+
/** When in the order's life it was opened (iFood: AFTER_DELIVERY, PREPARATION_TIME, DELAY, …); null unstated. */
|
|
47
|
+
handshakeType: string | null;
|
|
48
|
+
/** Why, in the marketplace's words ("Faltou item"); null unstated. */
|
|
49
|
+
reason: string | null;
|
|
50
|
+
/** The buyer's own words; null unstated. */
|
|
51
|
+
message: string | null;
|
|
52
|
+
/** The buyer's photos: https URLs only. */
|
|
53
|
+
evidenceUrls: string[];
|
|
54
|
+
items: DisputeItem[];
|
|
55
|
+
/** What the buyer asks back, in cents; null unstated. */
|
|
56
|
+
requestedAmountCents: number | null;
|
|
57
|
+
/** The store's deadline; null unstated. */
|
|
58
|
+
expiresAt: Date | null;
|
|
59
|
+
/** When the buyer opened it; null unstated (the engine then keeps its clock). */
|
|
60
|
+
openedAt: Date | null;
|
|
61
|
+
/** What the marketplace does when the store does not answer (iFood: ACCEPT_CANCELLATION, …); null unstated. */
|
|
62
|
+
timeoutAction: string | null;
|
|
63
|
+
alternatives: DisputeAlternative[];
|
|
64
|
+
/** The reasons a rejection may carry, as the marketplace sent them for this dispute. */
|
|
65
|
+
rejectReasons: DisputeReason[];
|
|
66
|
+
/** The reasons an acceptance may carry; sent only when the marketplace lists some. */
|
|
67
|
+
acceptReasons: DisputeReason[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** How the marketplace closed a dispute. `OTHER`: closed, with a word the engine does not know. */
|
|
71
|
+
export type DisputeOutcome = "ACCEPTED" | "REJECTED" | "EXPIRED" | "ALTERNATIVE_REPLIED" | "OTHER";
|
|
72
|
+
|
|
73
|
+
/** A dispute the marketplace closed, normalized. */
|
|
74
|
+
export interface NormalizedDisputeSettled {
|
|
75
|
+
disputeId: string;
|
|
76
|
+
outcome: DisputeOutcome;
|
|
77
|
+
/** When it closed; null unstated. */
|
|
78
|
+
at: Date | null;
|
|
79
|
+
/** What was refunded or granted, in cents; null unstated. */
|
|
80
|
+
amountCents: number | null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** What a delivery says about a dispute, when it says one. */
|
|
84
|
+
export type NormalizedDisputeEvent =
|
|
85
|
+
| { kind: "opened"; dispute: NormalizedDisputeOpened }
|
|
86
|
+
| { kind: "settled"; settlement: NormalizedDisputeSettled };
|
|
87
|
+
|
|
88
|
+
/** The store's answer, as it is sent. */
|
|
89
|
+
export type DisputeAnswer =
|
|
90
|
+
| { kind: "ACCEPT"; reasonCode: string | null }
|
|
91
|
+
| { kind: "REJECT"; reasonCode: string }
|
|
92
|
+
| { kind: "ALTERNATIVE"; alternative: DisputeAlternative; amountCents: number | null; minutes: number | null };
|
|
93
|
+
|
|
94
|
+
/** Why an answer did not land. */
|
|
95
|
+
export type DisputeFailureCode =
|
|
96
|
+
| "ALREADY_ANSWERED"
|
|
97
|
+
| "NOT_FOUND"
|
|
98
|
+
| "INVALID_REASON"
|
|
99
|
+
| "INVALID_AMOUNT"
|
|
100
|
+
| "REFUSED"
|
|
101
|
+
| "UNREACHABLE"
|
|
102
|
+
| "NOT_CONNECTED"
|
|
103
|
+
| "UNSUPPORTED";
|
|
104
|
+
|
|
105
|
+
/** One answer call's result: the outbound shapes, a refusal carrying the engine's code. */
|
|
106
|
+
export type DisputeAnswerResult =
|
|
107
|
+
| { kind: "accepted" }
|
|
108
|
+
| { kind: "refused"; status: number; message: string; code: DisputeFailureCode }
|
|
109
|
+
| { kind: "retry"; reason: string };
|
|
110
|
+
|
|
111
|
+
/** The adapter's disputes API. Present only on a marketplace with disputes (`capabilities.disputes`). */
|
|
112
|
+
export interface MarketplaceDisputeApi {
|
|
113
|
+
/** Send the store's answer to one dispute. Called only from the `marketplace.dispute-answer` job. */
|
|
114
|
+
answer(
|
|
115
|
+
ctx: AdapterCallContext,
|
|
116
|
+
target: { externalOrderId: string; disputeId: string },
|
|
117
|
+
answer: DisputeAnswer,
|
|
118
|
+
): Promise<DisputeAnswerResult>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** What the host hears after a dispute's commit (`order.onDispute`). */
|
|
122
|
+
export interface MarketplaceDisputeChange {
|
|
123
|
+
kind: "opened" | "settled";
|
|
124
|
+
disputeId: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The dispute table's delegate. OPTIONAL in `MarketplaceDb`: a host that has not composed it gets no disputes. */
|
|
128
|
+
export interface MarketplaceDisputeDelegate {
|
|
129
|
+
findFirst(args: unknown): Promise<unknown>;
|
|
130
|
+
findMany(args: unknown): Promise<unknown[]>;
|
|
131
|
+
create(args: unknown): Promise<unknown>;
|
|
132
|
+
updateMany(args: unknown): Promise<{ count: number }>;
|
|
133
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DisputeAlternative,
|
|
3
|
+
DisputeAlternativeType,
|
|
4
|
+
DisputeFailureCode,
|
|
5
|
+
DisputeItem,
|
|
6
|
+
DisputeOutcome,
|
|
7
|
+
DisputeReason,
|
|
8
|
+
MarketplaceDisputeDelegate,
|
|
9
|
+
} from "./dispute-port";
|
|
10
|
+
import type { EngineContext } from "./ports";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The dispute table (`marketplace_disputes`, FUT-6099): one row per dispute,
|
|
14
|
+
* read into the view a host draws. OPEN → SENDING (an answer claimed and
|
|
15
|
+
* queued) → ANSWERED (the marketplace took it) → SETTLED (the marketplace
|
|
16
|
+
* closed it). A failed send goes back to OPEN with its `failure` code.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The wire name, `<namespace>.<blueprint>`. */
|
|
20
|
+
export const MARKETPLACE_DISPUTE_ANSWER_JOB = "marketplace.dispute-answer";
|
|
21
|
+
|
|
22
|
+
export type DisputeStatus = "OPEN" | "SENDING" | "ANSWERED" | "SETTLED";
|
|
23
|
+
|
|
24
|
+
/** The store's answer as kept, with when it was given. */
|
|
25
|
+
export interface DisputeAnswerView {
|
|
26
|
+
kind: "ACCEPT" | "REJECT" | "ALTERNATIVE";
|
|
27
|
+
reasonCode: string | null;
|
|
28
|
+
alternativeId: string | null;
|
|
29
|
+
amountCents: number | null;
|
|
30
|
+
minutes: number | null;
|
|
31
|
+
at: Date;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** One dispute, as a host draws it. The engine writes no sentence: every word is the host's or the marketplace's. */
|
|
35
|
+
export interface MarketplaceDisputeView {
|
|
36
|
+
/** The marketplace's id for the dispute: the key `answerDispute` takes. */
|
|
37
|
+
disputeId: string;
|
|
38
|
+
orderId: string;
|
|
39
|
+
provider: string;
|
|
40
|
+
externalOrderId: string;
|
|
41
|
+
status: DisputeStatus;
|
|
42
|
+
action: string;
|
|
43
|
+
handshakeType: string | null;
|
|
44
|
+
reason: string | null;
|
|
45
|
+
message: string | null;
|
|
46
|
+
evidenceUrls: string[];
|
|
47
|
+
items: DisputeItem[];
|
|
48
|
+
requestedAmountCents: number | null;
|
|
49
|
+
expiresAt: Date | null;
|
|
50
|
+
openedAt: Date;
|
|
51
|
+
timeoutAction: string | null;
|
|
52
|
+
alternatives: DisputeAlternative[];
|
|
53
|
+
rejectReasons: DisputeReason[];
|
|
54
|
+
/** The answer sent or being sent; null while none stands (a failed one is cleared). */
|
|
55
|
+
answer: DisputeAnswerView | null;
|
|
56
|
+
/** Why the last answer did not land; with ALREADY_ANSWERED the status is ANSWERED (someone answered first). */
|
|
57
|
+
failure: DisputeFailureCode | null;
|
|
58
|
+
settlement: { outcome: DisputeOutcome; at: Date; amountCents: number | null } | null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A row as the delegate answers it. */
|
|
62
|
+
export interface DisputeRow {
|
|
63
|
+
id: string;
|
|
64
|
+
clientId: string;
|
|
65
|
+
orderId: string;
|
|
66
|
+
provider: string;
|
|
67
|
+
externalOrderId: string;
|
|
68
|
+
disputeId: string;
|
|
69
|
+
status: string;
|
|
70
|
+
action: string;
|
|
71
|
+
handshakeType: string | null;
|
|
72
|
+
reason: string | null;
|
|
73
|
+
message: string | null;
|
|
74
|
+
evidences: unknown;
|
|
75
|
+
items: unknown;
|
|
76
|
+
requestedAmountCents: number | null;
|
|
77
|
+
expiresAt: Date | null;
|
|
78
|
+
openedAt: Date;
|
|
79
|
+
timeoutAction: string | null;
|
|
80
|
+
alternatives: unknown;
|
|
81
|
+
rejectReasons: unknown;
|
|
82
|
+
acceptReasons: unknown;
|
|
83
|
+
answer: string | null;
|
|
84
|
+
answerReasonCode: string | null;
|
|
85
|
+
answerAlternativeId: string | null;
|
|
86
|
+
answerAmountCents: number | null;
|
|
87
|
+
answerMinutes: number | null;
|
|
88
|
+
answeredAt: Date | null;
|
|
89
|
+
answerFailure: string | null;
|
|
90
|
+
settlement: string | null;
|
|
91
|
+
settledAt: Date | null;
|
|
92
|
+
settledAmountCents: number | null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The delegate, or null on a host that has not composed the table. */
|
|
96
|
+
export async function disputeTable(ctx: EngineContext): Promise<MarketplaceDisputeDelegate | null> {
|
|
97
|
+
return (await ctx.ports.db()).marketplaceDispute ?? null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function arrayOf<T>(value: unknown, keep: (entry: unknown) => entry is T): T[] {
|
|
101
|
+
return Array.isArray(value) ? value.filter(keep) : [];
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const isString = (entry: unknown): entry is string => typeof entry === "string";
|
|
105
|
+
|
|
106
|
+
const isReason = (entry: unknown): entry is DisputeReason =>
|
|
107
|
+
typeof (entry as DisputeReason | null)?.code === "string" && typeof (entry as DisputeReason).description === "string";
|
|
108
|
+
|
|
109
|
+
const isItem = (entry: unknown): entry is DisputeItem => typeof (entry as DisputeItem | null)?.name === "string";
|
|
110
|
+
|
|
111
|
+
const ALTERNATIVE_TYPES: ReadonlySet<DisputeAlternativeType> = new Set(["REFUND", "BENEFIT", "ADDITIONAL_TIME"]);
|
|
112
|
+
|
|
113
|
+
const isAlternative = (entry: unknown): entry is DisputeAlternative =>
|
|
114
|
+
typeof (entry as DisputeAlternative | null)?.id === "string" &&
|
|
115
|
+
ALTERNATIVE_TYPES.has((entry as DisputeAlternative).type);
|
|
116
|
+
|
|
117
|
+
/** The reasons kept on a row (rejection or acceptance). */
|
|
118
|
+
export function reasonsOf(value: unknown): DisputeReason[] {
|
|
119
|
+
return arrayOf(value, isReason);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** The alternatives kept on a row. */
|
|
123
|
+
export function alternativesOf(value: unknown): DisputeAlternative[] {
|
|
124
|
+
return arrayOf(value, isAlternative);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function answerOf(row: DisputeRow): DisputeAnswerView | null {
|
|
128
|
+
if (row.answer === null || row.answeredAt === null) return null;
|
|
129
|
+
return {
|
|
130
|
+
kind: row.answer as DisputeAnswerView["kind"],
|
|
131
|
+
reasonCode: row.answerReasonCode,
|
|
132
|
+
alternativeId: row.answerAlternativeId,
|
|
133
|
+
amountCents: row.answerAmountCents,
|
|
134
|
+
minutes: row.answerMinutes,
|
|
135
|
+
at: row.answeredAt,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function settlementOf(row: DisputeRow): MarketplaceDisputeView["settlement"] {
|
|
140
|
+
if (row.settlement === null || row.settledAt === null) return null;
|
|
141
|
+
return { outcome: row.settlement as DisputeOutcome, at: row.settledAt, amountCents: row.settledAmountCents };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A row as a host draws it. */
|
|
145
|
+
export function disputeView(row: DisputeRow): MarketplaceDisputeView {
|
|
146
|
+
return {
|
|
147
|
+
disputeId: row.disputeId,
|
|
148
|
+
orderId: row.orderId,
|
|
149
|
+
provider: row.provider,
|
|
150
|
+
externalOrderId: row.externalOrderId,
|
|
151
|
+
status: row.status as DisputeStatus,
|
|
152
|
+
action: row.action,
|
|
153
|
+
handshakeType: row.handshakeType,
|
|
154
|
+
reason: row.reason,
|
|
155
|
+
message: row.message,
|
|
156
|
+
evidenceUrls: arrayOf(row.evidences, isString),
|
|
157
|
+
items: arrayOf(row.items, isItem),
|
|
158
|
+
requestedAmountCents: row.requestedAmountCents,
|
|
159
|
+
expiresAt: row.expiresAt,
|
|
160
|
+
openedAt: row.openedAt,
|
|
161
|
+
timeoutAction: row.timeoutAction,
|
|
162
|
+
alternatives: alternativesOf(row.alternatives),
|
|
163
|
+
rejectReasons: reasonsOf(row.rejectReasons),
|
|
164
|
+
answer: answerOf(row),
|
|
165
|
+
failure: row.answerFailure as DisputeFailureCode | null,
|
|
166
|
+
settlement: settlementOf(row),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Still the board's: open, being answered, or answered and waiting on the marketplace. */
|
|
171
|
+
const LIVE: readonly DisputeStatus[] = ["OPEN", "SENDING", "ANSWERED"];
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* The disputes a host reads, oldest first: of these orders, or, for a board,
|
|
175
|
+
* every one still live plus those settled since `settledSince` (the shift).
|
|
176
|
+
* One statement. Empty on a host that has not composed the table.
|
|
177
|
+
*/
|
|
178
|
+
export async function readDisputes(
|
|
179
|
+
ctx: EngineContext,
|
|
180
|
+
input: { clientId: string; orderIds?: readonly string[]; settledSince?: Date },
|
|
181
|
+
): Promise<MarketplaceDisputeView[]> {
|
|
182
|
+
const table = await disputeTable(ctx);
|
|
183
|
+
if (!table) return [];
|
|
184
|
+
const live = input.settledSince
|
|
185
|
+
? { OR: [{ status: { in: [...LIVE] } }, { settledAt: { gte: input.settledSince } }] }
|
|
186
|
+
: {};
|
|
187
|
+
const rows = (await table.findMany({
|
|
188
|
+
where: { clientId: input.clientId, ...(input.orderIds ? { orderId: { in: [...input.orderIds] } } : {}), ...live },
|
|
189
|
+
orderBy: { openedAt: "asc" },
|
|
190
|
+
})) as DisputeRow[];
|
|
191
|
+
return rows.map(disputeView);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** One dispute's row, by the marketplace's id, scoped to the store. */
|
|
195
|
+
export async function findDispute(
|
|
196
|
+
table: MarketplaceDisputeDelegate,
|
|
197
|
+
clientId: string,
|
|
198
|
+
disputeId: string,
|
|
199
|
+
orderId?: string,
|
|
200
|
+
): Promise<DisputeRow | null> {
|
|
201
|
+
// With `orderId`, a dispute of another order is not found: never claimed, never sent.
|
|
202
|
+
return (await table.findFirst({ where: { clientId, disputeId, ...(orderId === undefined ? {} : { orderId }) } })) as DisputeRow | null;
|
|
203
|
+
}
|