@12-apps/marketplace 1.16.0 → 1.17.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 +115 -0
- package/dist/99food/index.d.ts +2 -2
- package/dist/99food/index.js +2 -2
- package/dist/{adapter-CjVdMhZ2.d.ts → adapter-CxzF-qGx.d.ts} +185 -2
- package/dist/{chunk-TRUK5ZBE.js → chunk-7IYUO2KC.js} +2 -2
- package/dist/{chunk-BTKVZAJI.js → chunk-CF5BSXE5.js} +1 -1
- package/dist/chunk-CF5BSXE5.js.map +1 -0
- package/dist/{chunk-DJIMUEHT.js → chunk-EABVLQKK.js} +79 -7
- package/dist/chunk-EABVLQKK.js.map +1 -0
- package/dist/{chunk-H2VQRD3B.js → chunk-KKFMDV5K.js} +1 -1
- package/dist/chunk-KKFMDV5K.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-UZO2NILN.js} +365 -6
- package/dist/chunk-UZO2NILN.js.map +1 -0
- package/dist/{client-DgzCkl8u.d.ts → client-C-4QvVq3.d.ts} +1 -1
- package/dist/{engine-DSRj7qnC.d.ts → engine-Y6Rpf5p7.d.ts} +430 -185
- package/dist/hono/index.d.ts +2 -2
- package/dist/hono/index.js +4 -4
- package/dist/ifood/index.d.ts +9 -2
- package/dist/ifood/index.js +271 -23
- package/dist/ifood/index.js.map +1 -1
- package/dist/index.d.ts +21 -4
- package/dist/index.js +381 -42
- 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 +69 -1
- package/prisma/migrations/20261203180000_marketplace_app_link_check/migration.sql +14 -0
- package/prisma/migrations/20261203190000_marketplace_disputes/migration.sql +96 -0
- package/src/core/adapter.ts +12 -1
- package/src/core/app-linking.ts +396 -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 +4 -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/outbound-sweep.ts +9 -1
- package/src/core/pipeline.ts +8 -3
- package/src/core/ports.ts +15 -0
- package/src/core/types.ts +8 -0
- package/src/ifood/app-linking.ts +119 -0
- package/src/ifood/disputes.ts +209 -0
- package/src/ifood/index.ts +12 -1
- package/src/ifood/normalize.ts +3 -0
- package/src/index.ts +34 -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-7IYUO2KC.js.map} +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { DisputeAlternative, MarketplaceDisputeChange, NormalizedDisputeOpened, NormalizedDisputeSettled } from "./dispute-port";
|
|
2
|
+
import {
|
|
3
|
+
MARKETPLACE_DISPUTE_ANSWER_JOB,
|
|
4
|
+
alternativesOf,
|
|
5
|
+
disputeTable,
|
|
6
|
+
disputeView,
|
|
7
|
+
findDispute,
|
|
8
|
+
reasonsOf,
|
|
9
|
+
type DisputeRow,
|
|
10
|
+
type MarketplaceDisputeView,
|
|
11
|
+
} from "./dispute-store";
|
|
12
|
+
import { deferInboxEvent, settleInboxEvent } from "./inbox";
|
|
13
|
+
import type { DeliveryOutcome } from "./pipeline";
|
|
14
|
+
import type { EngineContext } from "./ports";
|
|
15
|
+
import type { NormalizedEvent } from "./types";
|
|
16
|
+
|
|
17
|
+
export type { MarketplaceDisputeChange } from "./dispute-port";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A marketplace's disputes (FUT-6099), the engine's half: the event that opens
|
|
21
|
+
* or closes one is kept per order, and the store's answer is claimed here and
|
|
22
|
+
* sent by the `marketplace.dispute-answer` job, never inside the request.
|
|
23
|
+
*
|
|
24
|
+
* A dispute never touches the order or its acceptance: it may arrive for an
|
|
25
|
+
* order in any state (delivered, in preparation, late), and what the store
|
|
26
|
+
* does about it is an answer to the marketplace, not a move of the order.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** The answer a person gives, before the engine judges it. */
|
|
30
|
+
export type DisputeAnswerInput =
|
|
31
|
+
| { kind: "ACCEPT" }
|
|
32
|
+
| { kind: "REJECT"; reasonCode: string }
|
|
33
|
+
| { kind: "ALTERNATIVE"; alternativeId: string; amountCents?: number | null; minutes?: number | null };
|
|
34
|
+
|
|
35
|
+
/** Why an answer is refused locally, before anything is queued. */
|
|
36
|
+
export type DisputeRefusalCode =
|
|
37
|
+
| "NOT_FOUND"
|
|
38
|
+
| "ALREADY_ANSWERED"
|
|
39
|
+
| "EXPIRED"
|
|
40
|
+
| "UNSUPPORTED"
|
|
41
|
+
| "INVALID_REASON"
|
|
42
|
+
| "INVALID_ALTERNATIVE"
|
|
43
|
+
| "INVALID_AMOUNT"
|
|
44
|
+
| "INVALID_MINUTES";
|
|
45
|
+
|
|
46
|
+
export type AnswerDisputeResult =
|
|
47
|
+
| { kind: "queued"; dispute: MarketplaceDisputeView }
|
|
48
|
+
| { kind: "refused"; code: DisputeRefusalCode };
|
|
49
|
+
|
|
50
|
+
interface HeldOrder {
|
|
51
|
+
orderId: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The order the event names, as the engine holds it. */
|
|
55
|
+
async function heldOrder(ctx: EngineContext, clientId: string, event: NormalizedEvent): Promise<HeldOrder | null> {
|
|
56
|
+
const db = await ctx.ports.db();
|
|
57
|
+
return (await db.marketplaceAcceptance.findFirst({
|
|
58
|
+
where: { clientId, provider: event.provider, externalOrderId: event.externalOrderId },
|
|
59
|
+
select: { orderId: true },
|
|
60
|
+
})) as HeldOrder | null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Tell the host after the commit; a throw is logged and changes nothing. */
|
|
64
|
+
async function tellHost(ctx: EngineContext, clientId: string, orderId: string, change: MarketplaceDisputeChange): Promise<void> {
|
|
65
|
+
ctx.ports.publishChanged(clientId);
|
|
66
|
+
const hook = ctx.ports.order.onDispute;
|
|
67
|
+
if (!hook) return;
|
|
68
|
+
try {
|
|
69
|
+
await hook.call(ctx.ports.order, clientId, orderId, change);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
ctx.ports.logger.error(`marketplace.dispute: the host's onDispute failed for order ${orderId}`, error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function openedData(clientId: string, orderId: string, event: NormalizedEvent, dispute: NormalizedDisputeOpened, now: Date) {
|
|
76
|
+
return {
|
|
77
|
+
clientId,
|
|
78
|
+
orderId,
|
|
79
|
+
provider: event.provider,
|
|
80
|
+
externalOrderId: event.externalOrderId,
|
|
81
|
+
disputeId: dispute.disputeId,
|
|
82
|
+
status: "OPEN",
|
|
83
|
+
action: dispute.action,
|
|
84
|
+
handshakeType: dispute.handshakeType,
|
|
85
|
+
reason: dispute.reason,
|
|
86
|
+
message: dispute.message,
|
|
87
|
+
evidences: dispute.evidenceUrls,
|
|
88
|
+
items: dispute.items,
|
|
89
|
+
requestedAmountCents: dispute.requestedAmountCents,
|
|
90
|
+
expiresAt: dispute.expiresAt,
|
|
91
|
+
openedAt: dispute.openedAt ?? now,
|
|
92
|
+
timeoutAction: dispute.timeoutAction,
|
|
93
|
+
alternatives: dispute.alternatives,
|
|
94
|
+
rejectReasons: dispute.rejectReasons,
|
|
95
|
+
acceptReasons: dispute.acceptReasons,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Keep an opened dispute once: a second event for the same dispute changes nothing. */
|
|
100
|
+
async function keepOpened(
|
|
101
|
+
ctx: EngineContext,
|
|
102
|
+
clientId: string,
|
|
103
|
+
order: HeldOrder,
|
|
104
|
+
event: NormalizedEvent,
|
|
105
|
+
dispute: NormalizedDisputeOpened,
|
|
106
|
+
): Promise<"opened" | "unchanged"> {
|
|
107
|
+
const table = await disputeTable(ctx);
|
|
108
|
+
if (!table) throw new Error("marketplace disputes need migration 20261203190000_marketplace_disputes");
|
|
109
|
+
const existing = await table.findFirst({ where: { provider: event.provider, disputeId: dispute.disputeId } });
|
|
110
|
+
if (existing) return "unchanged";
|
|
111
|
+
await table.create({ data: openedData(clientId, order.orderId, event, dispute, ctx.ports.clock.now()) });
|
|
112
|
+
return "opened";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Close a kept dispute with the marketplace's outcome; null when it is not kept (yet). */
|
|
116
|
+
async function keepSettled(
|
|
117
|
+
ctx: EngineContext,
|
|
118
|
+
clientId: string,
|
|
119
|
+
event: NormalizedEvent,
|
|
120
|
+
settlement: NormalizedDisputeSettled,
|
|
121
|
+
): Promise<{ orderId: string; changed: boolean } | null> {
|
|
122
|
+
const table = await disputeTable(ctx);
|
|
123
|
+
const row = table ? await findDispute(table, clientId, settlement.disputeId) : null;
|
|
124
|
+
if (!table || !row || row.provider !== event.provider) return null;
|
|
125
|
+
if (row.status === "SETTLED") return { orderId: row.orderId, changed: false };
|
|
126
|
+
await table.updateMany({
|
|
127
|
+
where: { id: row.id },
|
|
128
|
+
data: {
|
|
129
|
+
status: "SETTLED",
|
|
130
|
+
settlement: settlement.outcome,
|
|
131
|
+
settledAt: settlement.at ?? ctx.ports.clock.now(),
|
|
132
|
+
settledAmountCents: settlement.amountCents,
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
return { orderId: row.orderId, changed: true };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function deferred(ctx: EngineContext, inboxId: string, reason: string): Promise<DeliveryOutcome> {
|
|
139
|
+
await deferInboxEvent(ctx, inboxId, reason);
|
|
140
|
+
return { kind: "ignored", reason };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Act on a dispute event (HSD / HSS): kept, the inbox row PROCESSED, the host
|
|
145
|
+
* told. One that outran its order, or a close that outran its open, waits
|
|
146
|
+
* PENDING for the reconcile pass.
|
|
147
|
+
*/
|
|
148
|
+
export async function applyDisputeEvent(
|
|
149
|
+
ctx: EngineContext,
|
|
150
|
+
inboxId: string,
|
|
151
|
+
clientId: string,
|
|
152
|
+
event: NormalizedEvent,
|
|
153
|
+
): Promise<DeliveryOutcome | null> {
|
|
154
|
+
const dispute = event.dispute;
|
|
155
|
+
if (!dispute || !event.externalOrderId) return null;
|
|
156
|
+
if (dispute.kind === "settled") {
|
|
157
|
+
const settled = await keepSettled(ctx, clientId, event, dispute.settlement);
|
|
158
|
+
if (!settled) return deferred(ctx, inboxId, "settlement before its dispute");
|
|
159
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
160
|
+
const disputeId = dispute.settlement.disputeId;
|
|
161
|
+
if (settled.changed) await tellHost(ctx, clientId, settled.orderId, { kind: "settled", disputeId });
|
|
162
|
+
return { kind: "dispute", orderId: settled.orderId, disputeId, change: settled.changed ? "settled" : "unchanged" };
|
|
163
|
+
}
|
|
164
|
+
const order = await heldOrder(ctx, clientId, event);
|
|
165
|
+
if (!order) return deferred(ctx, inboxId, "dispute before its order");
|
|
166
|
+
const change = await keepOpened(ctx, clientId, order, event, dispute.dispute);
|
|
167
|
+
await settleInboxEvent(ctx, inboxId, "PROCESSED");
|
|
168
|
+
const disputeId = dispute.dispute.disputeId;
|
|
169
|
+
if (change === "opened") await tellHost(ctx, clientId, order.orderId, { kind: "opened", disputeId });
|
|
170
|
+
return { kind: "dispute", orderId: order.orderId, disputeId, change };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The columns an answer stamps. */
|
|
174
|
+
interface AnswerColumns {
|
|
175
|
+
answer: "ACCEPT" | "REJECT" | "ALTERNATIVE";
|
|
176
|
+
answerReasonCode: string | null;
|
|
177
|
+
answerAlternativeId: string | null;
|
|
178
|
+
answerAmountCents: number | null;
|
|
179
|
+
answerMinutes: number | null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const NONE = { answerReasonCode: null, answerAlternativeId: null, answerAmountCents: null, answerMinutes: null };
|
|
183
|
+
|
|
184
|
+
function isPositiveInteger(value: number | null | undefined): value is number {
|
|
185
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** An alternative's amount or minutes, judged against what the marketplace allows. */
|
|
189
|
+
function judgeAlternative(
|
|
190
|
+
alternative: DisputeAlternative,
|
|
191
|
+
input: { amountCents?: number | null; minutes?: number | null },
|
|
192
|
+
): AnswerColumns | DisputeRefusalCode {
|
|
193
|
+
const base = { ...NONE, answer: "ALTERNATIVE" as const, answerAlternativeId: alternative.id };
|
|
194
|
+
if (alternative.type === "ADDITIONAL_TIME") {
|
|
195
|
+
const minutes = input.minutes;
|
|
196
|
+
if (!isPositiveInteger(minutes)) return "INVALID_MINUTES";
|
|
197
|
+
if (alternative.allowedMinutes.length > 0 && !alternative.allowedMinutes.includes(minutes)) return "INVALID_MINUTES";
|
|
198
|
+
return { ...base, answerMinutes: minutes };
|
|
199
|
+
}
|
|
200
|
+
const amount = input.amountCents;
|
|
201
|
+
if (!isPositiveInteger(amount)) return "INVALID_AMOUNT";
|
|
202
|
+
if (alternative.maxAmountCents !== null && amount > alternative.maxAmountCents) return "INVALID_AMOUNT";
|
|
203
|
+
return { ...base, answerAmountCents: amount };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The person's answer against what the marketplace sent for this dispute. */
|
|
207
|
+
function judgeAnswer(row: DisputeRow, input: DisputeAnswerInput): AnswerColumns | DisputeRefusalCode {
|
|
208
|
+
if (input.kind === "ACCEPT") {
|
|
209
|
+
// No reason from the person (D5, owner 2026-12-03); the first the marketplace lists, when it lists any (R16).
|
|
210
|
+
return { ...NONE, answer: "ACCEPT", answerReasonCode: reasonsOf(row.acceptReasons)[0]?.code ?? null };
|
|
211
|
+
}
|
|
212
|
+
if (input.kind === "REJECT") {
|
|
213
|
+
const known = reasonsOf(row.rejectReasons).some((reason) => reason.code === input.reasonCode);
|
|
214
|
+
return known ? { ...NONE, answer: "REJECT", answerReasonCode: input.reasonCode } : "INVALID_REASON";
|
|
215
|
+
}
|
|
216
|
+
const alternative = alternativesOf(row.alternatives).find((entry) => entry.id === input.alternativeId);
|
|
217
|
+
return alternative ? judgeAlternative(alternative, input) : "INVALID_ALTERNATIVE";
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Why this dispute takes no answer now, or null. */
|
|
221
|
+
function closedFor(ctx: EngineContext, row: DisputeRow, now: Date): DisputeRefusalCode | null {
|
|
222
|
+
if (row.status !== "OPEN") return "ALREADY_ANSWERED";
|
|
223
|
+
if (row.expiresAt !== null && now.getTime() >= row.expiresAt.getTime()) return "EXPIRED";
|
|
224
|
+
return ctx.registry.get(row.provider)?.disputes ? null : "UNSUPPORTED";
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Queue the send; a refused enqueue is the outbound sweep's to re-queue. */
|
|
228
|
+
export async function enqueueDisputeAnswer(ctx: EngineContext, row: { clientId: string; disputeId: string }, key: string): Promise<boolean> {
|
|
229
|
+
const outcome = await ctx.ports.enqueue.enqueue(
|
|
230
|
+
MARKETPLACE_DISPUTE_ANSWER_JOB,
|
|
231
|
+
{ clientId: row.clientId, disputeId: row.disputeId },
|
|
232
|
+
{ dedupeKey: `${MARKETPLACE_DISPUTE_ANSWER_JOB}:${row.disputeId}:${key}` },
|
|
233
|
+
);
|
|
234
|
+
if (!outcome.enqueued) {
|
|
235
|
+
ctx.ports.logger.warn(`${MARKETPLACE_DISPUTE_ANSWER_JOB}: dispute ${row.disputeId} not queued; the sweep re-queues it` + (outcome.reason ? ` (${outcome.reason})` : ""));
|
|
236
|
+
}
|
|
237
|
+
return outcome.enqueued;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* The store answers one dispute: judged against what the marketplace sent,
|
|
242
|
+
* claimed (OPEN → SENDING, so two tablets never both answer) and queued. No
|
|
243
|
+
* call to the marketplace here; the job sends it.
|
|
244
|
+
*/
|
|
245
|
+
export async function answerDispute(
|
|
246
|
+
ctx: EngineContext,
|
|
247
|
+
input: { clientId: string; disputeId: string; orderId?: string; answer: DisputeAnswerInput; now?: Date },
|
|
248
|
+
): Promise<AnswerDisputeResult> {
|
|
249
|
+
const now = input.now ?? ctx.ports.clock.now();
|
|
250
|
+
const table = await disputeTable(ctx);
|
|
251
|
+
const row = table ? await findDispute(table, input.clientId, input.disputeId, input.orderId) : null;
|
|
252
|
+
if (!table || !row) return { kind: "refused", code: "NOT_FOUND" };
|
|
253
|
+
const closed = closedFor(ctx, row, now);
|
|
254
|
+
if (closed) return { kind: "refused", code: closed };
|
|
255
|
+
const judged = judgeAnswer(row, input.answer);
|
|
256
|
+
if (typeof judged === "string") return { kind: "refused", code: judged };
|
|
257
|
+
const data = { ...judged, status: "SENDING", answeredAt: now, answerFailure: null };
|
|
258
|
+
const claimed = await table.updateMany({ where: { id: row.id, status: "OPEN" }, data });
|
|
259
|
+
if (claimed.count === 0) return { kind: "refused", code: "ALREADY_ANSWERED" };
|
|
260
|
+
await enqueueDisputeAnswer(ctx, row, String(now.getTime()));
|
|
261
|
+
ctx.ports.publishChanged(input.clientId);
|
|
262
|
+
return { kind: "queued", dispute: disputeView({ ...row, ...data }) };
|
|
263
|
+
}
|