@swan-io/shared-business 18.2.0 → 18.4.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.
@@ -0,0 +1,366 @@
1
+ import { Future, Option, Result } from "@bloodyowl/boxed";
2
+ import { match } from "ts-pattern";
3
+ const MAX_TRANSACTIONS = 100;
4
+ const DRAFT_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000;
5
+ const isDefined = (value) => value !== undefined;
6
+ const unique = (values) => [...new Set(values)];
7
+ const firstOf = (...checks) => {
8
+ for (const check of checks) {
9
+ const result = check();
10
+ if (result.isSome()) {
11
+ return result;
12
+ }
13
+ }
14
+ return Option.None();
15
+ };
16
+ const toFraudDetails = (input) => { var _a, _b, _c, _d, _e; return ({
17
+ reportedReason: input.reportedReason,
18
+ reportedTypology: input.reportedTypology,
19
+ description: input.description,
20
+ discoveredAt: (_a = input.discoveredAt) !== null && _a !== void 0 ? _a : null,
21
+ discoveryDetails: (_b = input.discoveryDetails) !== null && _b !== void 0 ? _b : null,
22
+ fraudsterChannels: (_c = input.fraudsterChannels) !== null && _c !== void 0 ? _c : [],
23
+ sharedInformationWithFraudster: (_d = input.sharedInformationWithFraudster) !== null && _d !== void 0 ? _d : [],
24
+ hasFiledPoliceComplaint: (_e = input.hasFiledPoliceComplaint) !== null && _e !== void 0 ? _e : null,
25
+ }); };
26
+ const toPublicCase = ({ sentVictim: _, ...rest }) => rest;
27
+ const rejection = (value) => ({
28
+ kind: "rejection",
29
+ rejection: value,
30
+ });
31
+ const badUserInput = (message) => ({
32
+ kind: "error",
33
+ error: new Error(`BAD_USER_INPUT: ${message}`),
34
+ });
35
+ export const createFakeFraudReportApi = (config) => {
36
+ var _a, _b, _c;
37
+ const now = (_a = config.now) !== null && _a !== void 0 ? _a : (() => new Date());
38
+ const delay = (_b = config.delay) !== null && _b !== void 0 ? _b : 0;
39
+ const respond = (result) => delay > 0
40
+ ? Future.make(resolve => {
41
+ const timeout = setTimeout(() => resolve(result), delay);
42
+ return () => clearTimeout(timeout);
43
+ })
44
+ : Future.value(result);
45
+ const findTransaction = (id) => config.transactions.find(item => item.id === id);
46
+ const getTransactions = (ids) => ids.map(findTransaction).filter(isDefined);
47
+ const getIds = (item) => item.transactions.map(({ id }) => id);
48
+ const getCardholder = (ids) => { var _a; var _b; return (_b = (_a = getTransactions(ids).flatMap(item => (item.rail === "Card" ? [item] : []))[0]) === null || _a === void 0 ? void 0 : _a.cardholderAccountMembershipId) !== null && _b !== void 0 ? _b : null; };
49
+ const cases = new Map(((_c = config.cases) !== null && _c !== void 0 ? _c : []).map(item => [
50
+ item.id,
51
+ {
52
+ ...item,
53
+ sentVictim: item.hasVictim && !item.transactions.some(({ rail }) => rail === "Card")
54
+ ? { id: item.victimAccountMembershipId }
55
+ : null,
56
+ },
57
+ ]));
58
+ // A draft past its expiry date reads as expired, as the API does.
59
+ const getStoredCase = (id) => Option.fromUndefined(cases.get(id)).map(item => item.statusInfo.status === "Draft" && now().getTime() >= Date.parse(item.statusInfo.expiresAt)
60
+ ? {
61
+ ...item,
62
+ statusInfo: { status: "Expired", expiredAt: item.statusInfo.expiresAt },
63
+ supportingDocumentCollection: {
64
+ ...item.supportingDocumentCollection,
65
+ status: "Canceled",
66
+ },
67
+ }
68
+ : item);
69
+ const save = (item) => {
70
+ cases.set(item.id, item);
71
+ return toPublicCase(item);
72
+ };
73
+ const notFound = (disputeCaseId) => rejection({
74
+ __typename: "DisputeCaseNotFoundRejection",
75
+ message: "Dispute case not found",
76
+ disputeCaseId,
77
+ });
78
+ const wrongStatus = (item, expectedStatuses) => rejection({
79
+ __typename: "DisputeCaseWrongStatusRejection",
80
+ message: "Dispute case has the wrong status",
81
+ disputeCaseId: item.id,
82
+ currentStatus: item.statusInfo.status,
83
+ expectedStatuses,
84
+ });
85
+ const checkTransactionsFound = (ids) => {
86
+ const missing = ids.filter(id => findTransaction(id) == null);
87
+ return missing.length > 0
88
+ ? Option.Some({
89
+ __typename: "DisputeCaseTransactionsNotFoundRejection",
90
+ message: "Some transactions were not found",
91
+ transactionIds: missing,
92
+ })
93
+ : Option.None();
94
+ };
95
+ const checkReportable = (ids) => {
96
+ const transactions = getTransactions(ids).flatMap(({ id, notReportableReason }) => notReportableReason == null ? [] : [{ transactionId: id, reason: notReportableReason }]);
97
+ return transactions.length > 0
98
+ ? Option.Some({
99
+ __typename: "DisputeCaseTransactionsNotReportableRejection",
100
+ message: "Some transactions can't be reported",
101
+ transactions,
102
+ })
103
+ : Option.None();
104
+ };
105
+ const checkSingleAccount = (ids) => {
106
+ const accountIds = unique(getTransactions(ids).map(item => item.accountId));
107
+ return accountIds.length > 1
108
+ ? Option.Some({
109
+ __typename: "DisputeCaseMultipleAccountsRejection",
110
+ message: "Transactions belong to several accounts",
111
+ accountIds,
112
+ })
113
+ : Option.None();
114
+ };
115
+ const checkSingleCardholder = (ids) => {
116
+ const accountMembershipIds = unique(getTransactions(ids).flatMap(item => item.rail === "Card" ? [item.cardholderAccountMembershipId] : []));
117
+ return accountMembershipIds.length > 1
118
+ ? Option.Some({
119
+ __typename: "DisputeCaseMultipleCardHoldersRejection",
120
+ message: "Card transactions belong to several cardholders",
121
+ accountMembershipIds,
122
+ })
123
+ : Option.None();
124
+ };
125
+ const checkReportingWindow = (ids) => {
126
+ const transactions = getTransactions(ids).flatMap(({ id, reportingWindowEndsAt }) => reportingWindowEndsAt != null && now().getTime() >= Date.parse(reportingWindowEndsAt)
127
+ ? [{ transactionId: id, reportingWindowEndedAt: reportingWindowEndsAt }]
128
+ : []);
129
+ return transactions.length > 0
130
+ ? Option.Some({
131
+ __typename: "DisputeCaseTransactionsOutsideReportingWindowRejection",
132
+ message: "Some transactions are outside the reporting window",
133
+ transactions,
134
+ })
135
+ : Option.None();
136
+ };
137
+ const checkInputFormat = (input) => {
138
+ const { transactionIds } = input;
139
+ if (transactionIds == null) {
140
+ return Option.None();
141
+ }
142
+ if (transactionIds.length === 0) {
143
+ return Option.Some(badUserInput("transactionIds must not be empty"));
144
+ }
145
+ if (unique(transactionIds).length !== transactionIds.length) {
146
+ return Option.Some(badUserInput("transactionIds must not contain duplicates"));
147
+ }
148
+ return Option.None();
149
+ };
150
+ // Draft and update checks, from the transaction limit on, run on the case as it would stand
151
+ // after the call.
152
+ const write = (existing, input) => {
153
+ var _a;
154
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
155
+ const transactionIds = (_b = input.transactionIds) !== null && _b !== void 0 ? _b : (existing != null ? getIds(existing) : []);
156
+ const transactions = getTransactions(transactionIds);
157
+ const hasCard = transactions.some(item => item.rail === "Card");
158
+ const hasTransfer = transactions.some(item => item.rail === "Transfer");
159
+ const accountId = (_d = (_c = (_a = transactions[0]) === null || _a === void 0 ? void 0 : _a.accountId) !== null && _c !== void 0 ? _c : existing === null || existing === void 0 ? void 0 : existing.accountId) !== null && _d !== void 0 ? _d : "";
160
+ const sentVictim = input.victimAccountMembershipId;
161
+ const checkLimit = () => input.transactionIds != null && input.transactionIds.length > MAX_TRANSACTIONS
162
+ ? Option.Some({
163
+ __typename: "DisputeCaseTransactionsLimitExceededRejection",
164
+ message: "Too many transactions",
165
+ transactionCount: input.transactionIds.length,
166
+ maxTransactionCount: MAX_TRANSACTIONS,
167
+ })
168
+ : Option.None();
169
+ const checkDetailsApplicable = () => {
170
+ const fields = [
171
+ input.fraudCardDetails != null && !hasCard ? ["fraudCardDetails"] : undefined,
172
+ input.fraudTransferDetails != null && !hasTransfer ? ["fraudTransferDetails"] : undefined,
173
+ sentVictim != null && hasCard ? ["victimAccountMembershipId"] : undefined,
174
+ ]
175
+ .filter(isDefined)
176
+ .map(path => ({ path }));
177
+ return fields.length > 0
178
+ ? Option.Some({
179
+ __typename: "DisputeCaseDetailsNotApplicableRejection",
180
+ message: "Some details don't apply to this case",
181
+ fields,
182
+ })
183
+ : Option.None();
184
+ };
185
+ const checkVictim = () => sentVictim != null &&
186
+ !config.accountMemberships.some(item => item.id === sentVictim && item.accountId === accountId)
187
+ ? Option.Some({
188
+ __typename: "AccountMembershipNotFoundRejection",
189
+ message: "Account membership not found",
190
+ id: sentVictim,
191
+ })
192
+ : Option.None();
193
+ const failure = firstOf(checkLimit, () => checkTransactionsFound(transactionIds), () => checkReportable(transactionIds), () => checkSingleAccount(transactionIds), () => checkSingleCardholder(transactionIds), () => checkReportingWindow(transactionIds), checkDetailsApplicable, checkVictim);
194
+ if (failure.isSome()) {
195
+ return Result.Error(rejection(failure.get()));
196
+ }
197
+ // A stored victim is dropped when the case gets card transactions or moves to another
198
+ // account, unless one is sent in this call.
199
+ const victim = hasCard
200
+ ? null
201
+ : sentVictim !== undefined
202
+ ? sentVictim === null
203
+ ? null
204
+ : { id: sentVictim }
205
+ : (existing === null || existing === void 0 ? void 0 : existing.accountId) === accountId
206
+ ? existing.sentVictim
207
+ : null;
208
+ const cardholder = getCardholder(transactionIds);
209
+ const keep = (key) => { var _a; return (input[key] === undefined ? ((_a = existing === null || existing === void 0 ? void 0 : existing[key]) !== null && _a !== void 0 ? _a : null) : input[key]); };
210
+ const fraudCardDetails = hasCard ? keep("fraudCardDetails") : null;
211
+ const fraudTransferDetails = hasTransfer ? keep("fraudTransferDetails") : null;
212
+ const date = now();
213
+ const windowEnds = transactions
214
+ .map(item => item.reportingWindowEndsAt)
215
+ .filter(isDefined)
216
+ .map(value => Date.parse(value));
217
+ const expiresAt = Math.min(date.getTime() + DRAFT_LIFETIME_MS, ...windowEnds);
218
+ return Result.Ok({
219
+ id: (_e = existing === null || existing === void 0 ? void 0 : existing.id) !== null && _e !== void 0 ? _e : crypto.randomUUID(),
220
+ accountId,
221
+ statusInfo: { status: "Draft", expiresAt: new Date(expiresAt).toISOString() },
222
+ transactions: transactions.map(({ id, rail }) => ({ id, rail })),
223
+ fraudDetails: input.fraudDetails === undefined
224
+ ? ((_f = existing === null || existing === void 0 ? void 0 : existing.fraudDetails) !== null && _f !== void 0 ? _f : null)
225
+ : input.fraudDetails === null
226
+ ? null
227
+ : toFraudDetails(input.fraudDetails),
228
+ fraudCardDetails: fraudCardDetails == null
229
+ ? null
230
+ : {
231
+ isLostOrStolen: (_g = fraudCardDetails.isLostOrStolen) !== null && _g !== void 0 ? _g : null,
232
+ lostOrStolenNoticedAt: (_h = fraudCardDetails.lostOrStolenNoticedAt) !== null && _h !== void 0 ? _h : null,
233
+ hasContactedMerchant: (_j = fraudCardDetails.hasContactedMerchant) !== null && _j !== void 0 ? _j : null,
234
+ },
235
+ fraudTransferDetails: fraudTransferDetails == null
236
+ ? null
237
+ : {
238
+ hasContactedBankOrBeneficiary: (_k = fraudTransferDetails.hasContactedBankOrBeneficiary) !== null && _k !== void 0 ? _k : null,
239
+ },
240
+ victimAccountMembershipId: hasCard ? cardholder : ((_l = victim === null || victim === void 0 ? void 0 : victim.id) !== null && _l !== void 0 ? _l : null),
241
+ hasVictim: hasCard ? cardholder != null : victim != null,
242
+ sentVictim: victim,
243
+ externalReference: keep("externalReference"),
244
+ supportingDocumentCollection: (_m = existing === null || existing === void 0 ? void 0 : existing.supportingDocumentCollection) !== null && _m !== void 0 ? _m : {
245
+ id: crypto.randomUUID(),
246
+ status: "WaitingForDocument",
247
+ },
248
+ createdAt: (_o = existing === null || existing === void 0 ? void 0 : existing.createdAt) !== null && _o !== void 0 ? _o : date.toISOString(),
249
+ updatedAt: date.toISOString(),
250
+ });
251
+ };
252
+ const checkNotAlreadyReported = (item) => {
253
+ const transactions = getIds(item).flatMap(transactionId => {
254
+ var _a;
255
+ const external = (_a = config.alreadyReported) === null || _a === void 0 ? void 0 : _a.find(entry => entry.transactionId === transactionId);
256
+ if (external != null) {
257
+ return [external];
258
+ }
259
+ const submitted = [...cases.values()].find(other => other.id !== item.id &&
260
+ other.statusInfo.status === "Submitted" &&
261
+ getIds(other).includes(transactionId));
262
+ return submitted == null ? [] : [{ transactionId, disputeCaseId: submitted.id }];
263
+ });
264
+ return transactions.length > 0
265
+ ? Option.Some({
266
+ __typename: "DisputeCaseTransactionsAlreadyReportedRejection",
267
+ message: "Some transactions are already reported",
268
+ transactions,
269
+ })
270
+ : Option.None();
271
+ };
272
+ const checkComplete = (item) => {
273
+ const isTransferOnly = item.transactions.every(({ rail }) => rail === "Transfer");
274
+ const missingFields = [
275
+ item.fraudDetails == null ? ["fraudDetails"] : undefined,
276
+ isTransferOnly && !item.hasVictim ? ["victimAccountMembershipId"] : undefined,
277
+ ]
278
+ .filter(isDefined)
279
+ .map(path => ({ path }));
280
+ return missingFields.length > 0
281
+ ? Option.Some({
282
+ __typename: "DisputeCaseIncompleteRejection",
283
+ message: "The case is incomplete",
284
+ missingFields,
285
+ })
286
+ : Option.None();
287
+ };
288
+ const submitDraft = (item) => {
289
+ const ids = getIds(item);
290
+ const failure = firstOf(() => checkTransactionsFound(ids), () => checkReportable(ids), () => checkReportingWindow(ids), () => checkNotAlreadyReported(item), () => checkComplete(item));
291
+ if (failure.isSome()) {
292
+ return Result.Error(rejection(failure.get()));
293
+ }
294
+ const date = now().toISOString();
295
+ return Result.Ok(save({
296
+ ...item,
297
+ statusInfo: { status: "Submitted", submittedAt: date },
298
+ supportingDocumentCollection: {
299
+ ...item.supportingDocumentCollection,
300
+ status: "PendingReview",
301
+ },
302
+ updatedAt: date,
303
+ }));
304
+ };
305
+ const cancelDraft = (item) => {
306
+ const date = now().toISOString();
307
+ return save({
308
+ ...item,
309
+ statusInfo: { status: "Canceled", canceledAt: date },
310
+ supportingDocumentCollection: { ...item.supportingDocumentCollection, status: "Canceled" },
311
+ updatedAt: date,
312
+ });
313
+ };
314
+ return {
315
+ draft: input => respond(checkInputFormat(input).match({
316
+ Some: error => Result.Error(error),
317
+ None: () => write(undefined, input).map(save),
318
+ })),
319
+ update: ({ disputeCaseId, ...input }) => respond(checkInputFormat(input).match({
320
+ Some: error => Result.Error(error),
321
+ None: () => getStoredCase(disputeCaseId)
322
+ .toResult(notFound(disputeCaseId))
323
+ .flatMap((existing) => existing.statusInfo.status === "Draft"
324
+ ? write(existing, input)
325
+ : Result.Error(wrongStatus(existing, ["Draft"])))
326
+ .map(save),
327
+ })),
328
+ submit: ({ disputeCaseId }) => respond(getStoredCase(disputeCaseId)
329
+ .toResult(notFound(disputeCaseId))
330
+ .flatMap(item => match(item.statusInfo.status)
331
+ .with("Submitted", () => Result.Ok(toPublicCase(item)))
332
+ .with("Draft", () => submitDraft(item))
333
+ .with("Expired", "Canceled", () => Result.Error(wrongStatus(item, ["Draft"])))
334
+ .exhaustive())),
335
+ cancel: ({ disputeCaseId }) => respond(getStoredCase(disputeCaseId)
336
+ .toResult(notFound(disputeCaseId))
337
+ .flatMap(item => match(item.statusInfo.status)
338
+ .with("Canceled", () => Result.Ok(toPublicCase(item)))
339
+ .with("Draft", () => Result.Ok(cancelDraft(item)))
340
+ .with("Submitted", "Expired", () => Result.Error(wrongStatus(item, ["Draft"])))
341
+ .exhaustive())),
342
+ getCase: ({ disputeCaseId }) => respond(Result.Ok(getStoredCase(disputeCaseId).map(toPublicCase))),
343
+ findDrafts: ({ accountId, transactionIds }) => respond(Result.Ok([...cases.keys()]
344
+ // Insertion order breaks createdAt ties.
345
+ .reverse()
346
+ .map(id => getStoredCase(id).toUndefined())
347
+ .filter(isDefined)
348
+ .filter(item => item.statusInfo.status === "Draft" &&
349
+ item.accountId === accountId &&
350
+ getIds(item).some(id => transactionIds.includes(id)))
351
+ .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))
352
+ .map(toPublicCase))),
353
+ generateUpload: () => respond(Result.Ok({
354
+ id: crypto.randomUUID(),
355
+ upload: { url: "https://example.org/upload", fields: [] },
356
+ })),
357
+ uploadFile: () => respond(Result.Ok({
358
+ headers: new Headers(),
359
+ status: 200,
360
+ ok: true,
361
+ url: "https://example.org/upload",
362
+ response: Option.None(),
363
+ })),
364
+ removeFile: () => respond(Result.Ok(undefined)),
365
+ };
366
+ };
@@ -0,0 +1,5 @@
1
+ import { Option } from "@bloodyowl/boxed";
2
+ import type { FraudReportRail, FraudReportTransaction } from "./types";
3
+ export type FraudReportCaseRail = "CardOnly" | "TransferOnly" | "Mixed";
4
+ export declare const getTransactionRail: (transactionType: string) => Option<FraudReportRail>;
5
+ export declare const getCaseRail: (transactions: Pick<FraudReportTransaction, "rail">[]) => Option<FraudReportCaseRail>;
@@ -0,0 +1,14 @@
1
+ import { Option } from "@bloodyowl/boxed";
2
+ import { match } from "ts-pattern";
3
+ export const getTransactionRail = (transactionType) => match(transactionType)
4
+ .with("CardOutDebit", () => Option.Some("Card"))
5
+ .with("SepaCreditTransferOut", "SepaInstantCreditTransferOut", "InternationalCreditTransferOut", "InternalCreditTransferOut", () => Option.Some("Transfer"))
6
+ .otherwise(() => Option.None());
7
+ export const getCaseRail = (transactions) => match({
8
+ hasCard: transactions.some(({ rail }) => rail === "Card"),
9
+ hasTransfer: transactions.some(({ rail }) => rail === "Transfer"),
10
+ })
11
+ .with({ hasCard: true, hasTransfer: true }, () => Option.Some("Mixed"))
12
+ .with({ hasCard: true }, () => Option.Some("CardOnly"))
13
+ .with({ hasTransfer: true }, () => Option.Some("TransferOnly"))
14
+ .otherwise(() => Option.None());
@@ -0,0 +1,21 @@
1
+ import type { DraftFraudDisputeCaseInput, FraudReason, FraudReportCase, FraudReportTransaction, FraudsterChannel, FraudTypology, SharedInformationWithFraudster, UpdateDraftFraudDisputeCaseInput } from "./types";
2
+ export type FraudReportFormValues = {
3
+ transactions: FraudReportTransaction[];
4
+ victimAccountMembershipId?: string;
5
+ reportedReason?: FraudReason;
6
+ reportedTypology?: FraudTypology;
7
+ description?: string;
8
+ discoveredAt?: string;
9
+ discoveryDetails?: string;
10
+ fraudsterChannels?: FraudsterChannel[];
11
+ sharedInformationWithFraudster?: SharedInformationWithFraudster[];
12
+ isLostOrStolen?: boolean;
13
+ lostOrStolenNoticedAt?: string;
14
+ externalReference?: string;
15
+ };
16
+ export declare const toDraftInput: (values: FraudReportFormValues) => DraftFraudDisputeCaseInput;
17
+ export declare const toUpdateInput: ({ savedCase, values, savedTransactionIds, }: {
18
+ savedCase: Pick<FraudReportCase, "id" | "fraudDetails" | "fraudCardDetails">;
19
+ values: FraudReportFormValues;
20
+ savedTransactionIds: string[];
21
+ }) => UpdateDraftFraudDisputeCaseInput;
@@ -0,0 +1,74 @@
1
+ import { Option } from "@bloodyowl/boxed";
2
+ import { match, P } from "ts-pattern";
3
+ import { getCaseRail } from "./rail";
4
+ const toFilled = (value) => Option.fromNullable(value).filter(item => item.trim() !== "");
5
+ const toFilledList = (values) => Option.fromNullable(values).filter(items => items.length > 0);
6
+ const toFraudDetails = (values, savedDetails) => Option.allFromDict({
7
+ reportedReason: Option.fromNullable(values.reportedReason),
8
+ reportedTypology: Option.fromNullable(values.reportedTypology),
9
+ description: toFilled(values.description),
10
+ }).map(required => { var _a; var _b; return ({
11
+ ...required,
12
+ discoveredAt: toFilled(values.discoveredAt).toNull(),
13
+ discoveryDetails: toFilled(values.discoveryDetails).toNull(),
14
+ fraudsterChannels: toFilledList(values.fraudsterChannels).toNull(),
15
+ sharedInformationWithFraudster: toFilledList(values.sharedInformationWithFraudster).toNull(),
16
+ hasFiledPoliceComplaint: (_b = (_a = savedDetails === null || savedDetails === void 0 ? void 0 : savedDetails.fraudDetails) === null || _a === void 0 ? void 0 : _a.hasFiledPoliceComplaint) !== null && _b !== void 0 ? _b : null,
17
+ }); });
18
+ const toFraudCardDetails = (values, savedDetails) => {
19
+ var _a;
20
+ var _b;
21
+ const isLostOrStolen = Option.fromNullable(values.isLostOrStolen);
22
+ const lostOrStolenNoticedAt = toFilled(values.lostOrStolenNoticedAt);
23
+ return isLostOrStolen.isNone() && lostOrStolenNoticedAt.isNone()
24
+ ? Option.None()
25
+ : Option.Some({
26
+ isLostOrStolen: isLostOrStolen.toNull(),
27
+ lostOrStolenNoticedAt: lostOrStolenNoticedAt.toNull(),
28
+ hasContactedMerchant: (_b = (_a = savedDetails === null || savedDetails === void 0 ? void 0 : savedDetails.fraudCardDetails) === null || _a === void 0 ? void 0 : _a.hasContactedMerchant) !== null && _b !== void 0 ? _b : null,
29
+ });
30
+ };
31
+ const toDetails = (values, savedDetails) => {
32
+ const fraudDetails = toFraudDetails(values, savedDetails)
33
+ .map(value => ({ fraudDetails: value }))
34
+ .toUndefined();
35
+ return match(getCaseRail(values.transactions))
36
+ .with(Option.P.Some(P.union("CardOnly", "Mixed")), () => ({
37
+ ...fraudDetails,
38
+ ...toFraudCardDetails(values, savedDetails)
39
+ .map(value => ({ fraudCardDetails: value }))
40
+ .toUndefined(),
41
+ }))
42
+ .with(Option.P.Some("TransferOnly"), () => ({
43
+ ...fraudDetails,
44
+ ...toFilled(values.victimAccountMembershipId)
45
+ .map(value => ({ victimAccountMembershipId: value }))
46
+ .toUndefined(),
47
+ }))
48
+ .with(Option.P.None, () => ({ ...fraudDetails }))
49
+ .exhaustive();
50
+ };
51
+ const toTransactionIds = (values) => values.transactions.map(({ id }) => id);
52
+ const isSameSelection = (transactionIds, savedTransactionIds) => {
53
+ const savedIds = new Set(savedTransactionIds);
54
+ return (new Set(transactionIds).size === savedIds.size && transactionIds.every(id => savedIds.has(id)));
55
+ };
56
+ export const toDraftInput = (values) => ({
57
+ transactionIds: toTransactionIds(values),
58
+ ...toDetails(values),
59
+ ...match(values.externalReference)
60
+ .with(P.union(undefined, ""), () => undefined)
61
+ .otherwise(externalReference => ({ externalReference })),
62
+ });
63
+ export const toUpdateInput = ({ savedCase, values, savedTransactionIds, }) => {
64
+ const transactionIds = toTransactionIds(values);
65
+ return {
66
+ disputeCaseId: savedCase.id,
67
+ ...(isSameSelection(transactionIds, savedTransactionIds) ? undefined : { transactionIds }),
68
+ ...toDetails(values, savedCase),
69
+ ...match(values.externalReference)
70
+ .with(undefined, () => undefined)
71
+ .with("", () => ({ externalReference: null }))
72
+ .otherwise(externalReference => ({ externalReference })),
73
+ };
74
+ };
@@ -0,0 +1,187 @@
1
+ export type FraudReason = "Unauthorized" | "Manipulated";
2
+ export type FraudTypology = "FakeAdvisor" | "ImpersonationOrPhishing" | "FakeWebsite" | "FakeSupplierOrInvoice" | "InvestmentScam" | "RomanceScam" | "Other";
3
+ export type FraudsterChannel = "Email" | "Sms" | "Phone" | "Website" | "Application" | "Other";
4
+ export type SharedInformationWithFraudster = "SwanPasscode" | "PartnerPassword" | "VerificationCode" | "PersonalInformation" | "CardDetails" | "BankDetails" | "Other" | "None";
5
+ export type DisputeCaseStatus = "Draft" | "Expired" | "Canceled" | "Submitted";
6
+ export type DisputeCaseTransactionNotReportableReason = "TransactionTypeNotReportable" | "TransactionStatusNotReportable";
7
+ export type FraudReportDocumentPurpose = "PoliceReport" | "FraudEvidence" | "DisputeCorrespondence" | "CardFraudDeclaration" | "Other";
8
+ export type SupportingDocumentCollectionStatus = "WaitingForDocument" | "PendingReview" | "Approved" | "Canceled" | "Rejected";
9
+ export type FraudDetailsInput = {
10
+ reportedReason: FraudReason;
11
+ reportedTypology: FraudTypology;
12
+ description: string;
13
+ discoveredAt?: string | null;
14
+ discoveryDetails?: string | null;
15
+ fraudsterChannels?: FraudsterChannel[] | null;
16
+ sharedInformationWithFraudster?: SharedInformationWithFraudster[] | null;
17
+ hasFiledPoliceComplaint?: boolean | null;
18
+ };
19
+ export type FraudCardDetailsInput = {
20
+ isLostOrStolen?: boolean | null;
21
+ lostOrStolenNoticedAt?: string | null;
22
+ hasContactedMerchant?: boolean | null;
23
+ };
24
+ export type FraudTransferDetailsInput = {
25
+ hasContactedBankOrBeneficiary?: boolean | null;
26
+ };
27
+ export type DraftFraudDisputeCaseInput = {
28
+ transactionIds: string[];
29
+ fraudDetails?: FraudDetailsInput | null;
30
+ fraudCardDetails?: FraudCardDetailsInput | null;
31
+ fraudTransferDetails?: FraudTransferDetailsInput | null;
32
+ victimAccountMembershipId?: string | null;
33
+ externalReference?: string | null;
34
+ };
35
+ export type UpdateDraftFraudDisputeCaseInput = {
36
+ disputeCaseId: string;
37
+ transactionIds?: string[];
38
+ fraudDetails?: FraudDetailsInput | null;
39
+ fraudCardDetails?: FraudCardDetailsInput | null;
40
+ fraudTransferDetails?: FraudTransferDetailsInput | null;
41
+ victimAccountMembershipId?: string | null;
42
+ externalReference?: string | null;
43
+ };
44
+ export type SubmitDisputeCaseInput = {
45
+ disputeCaseId: string;
46
+ };
47
+ export type CancelDisputeCaseInput = {
48
+ disputeCaseId: string;
49
+ };
50
+ export type FraudDetails = {
51
+ reportedReason: FraudReason;
52
+ reportedTypology: FraudTypology;
53
+ description: string;
54
+ discoveredAt: string | null;
55
+ discoveryDetails: string | null;
56
+ fraudsterChannels: FraudsterChannel[];
57
+ sharedInformationWithFraudster: SharedInformationWithFraudster[];
58
+ hasFiledPoliceComplaint: boolean | null;
59
+ };
60
+ export type FraudCardDetails = {
61
+ isLostOrStolen: boolean | null;
62
+ lostOrStolenNoticedAt: string | null;
63
+ hasContactedMerchant: boolean | null;
64
+ };
65
+ export type FraudTransferDetails = {
66
+ hasContactedBankOrBeneficiary: boolean | null;
67
+ };
68
+ export type DisputeCaseStatusInfo = {
69
+ status: "Draft";
70
+ expiresAt: string;
71
+ } | {
72
+ status: "Expired";
73
+ expiredAt: string;
74
+ } | {
75
+ status: "Canceled";
76
+ canceledAt: string;
77
+ } | {
78
+ status: "Submitted";
79
+ submittedAt: string;
80
+ };
81
+ export type FraudReportRail = "Card" | "Transfer";
82
+ export type FraudReportTransaction = {
83
+ id: string;
84
+ rail: FraudReportRail;
85
+ };
86
+ export type FraudReportCase = {
87
+ id: string;
88
+ accountId: string;
89
+ statusInfo: DisputeCaseStatusInfo;
90
+ transactions: FraudReportTransaction[];
91
+ fraudDetails: FraudDetails | null;
92
+ fraudCardDetails: FraudCardDetails | null;
93
+ fraudTransferDetails: FraudTransferDetails | null;
94
+ victimAccountMembershipId: string | null;
95
+ hasVictim: boolean;
96
+ externalReference: string | null;
97
+ supportingDocumentCollection: {
98
+ id: string;
99
+ status: SupportingDocumentCollectionStatus;
100
+ };
101
+ createdAt: string;
102
+ updatedAt: string;
103
+ };
104
+ export type DisputeCaseFieldPath = {
105
+ path: string[];
106
+ };
107
+ export type DisputeCaseNotFoundRejection = {
108
+ __typename: "DisputeCaseNotFoundRejection";
109
+ message: string;
110
+ disputeCaseId: string;
111
+ };
112
+ export type DisputeCaseWrongStatusRejection = {
113
+ __typename: "DisputeCaseWrongStatusRejection";
114
+ message: string;
115
+ disputeCaseId: string;
116
+ currentStatus: DisputeCaseStatus;
117
+ expectedStatuses: DisputeCaseStatus[];
118
+ };
119
+ export type DisputeCaseTransactionsNotFoundRejection = {
120
+ __typename: "DisputeCaseTransactionsNotFoundRejection";
121
+ message: string;
122
+ transactionIds: string[];
123
+ };
124
+ export type DisputeCaseTransactionsLimitExceededRejection = {
125
+ __typename: "DisputeCaseTransactionsLimitExceededRejection";
126
+ message: string;
127
+ transactionCount: number;
128
+ maxTransactionCount: number;
129
+ };
130
+ export type DisputeCaseMultipleAccountsRejection = {
131
+ __typename: "DisputeCaseMultipleAccountsRejection";
132
+ message: string;
133
+ accountIds: string[];
134
+ };
135
+ export type DisputeCaseMultipleCardHoldersRejection = {
136
+ __typename: "DisputeCaseMultipleCardHoldersRejection";
137
+ message: string;
138
+ accountMembershipIds: string[];
139
+ };
140
+ export type DisputeCaseTransactionsNotReportableRejection = {
141
+ __typename: "DisputeCaseTransactionsNotReportableRejection";
142
+ message: string;
143
+ transactions: {
144
+ transactionId: string;
145
+ reason: DisputeCaseTransactionNotReportableReason;
146
+ }[];
147
+ };
148
+ export type DisputeCaseTransactionsOutsideReportingWindowRejection = {
149
+ __typename: "DisputeCaseTransactionsOutsideReportingWindowRejection";
150
+ message: string;
151
+ transactions: {
152
+ transactionId: string;
153
+ reportingWindowEndedAt: string;
154
+ }[];
155
+ };
156
+ export type DisputeCaseDetailsNotApplicableRejection = {
157
+ __typename: "DisputeCaseDetailsNotApplicableRejection";
158
+ message: string;
159
+ fields: DisputeCaseFieldPath[];
160
+ };
161
+ export type AccountMembershipNotFoundRejection = {
162
+ __typename: "AccountMembershipNotFoundRejection";
163
+ message: string;
164
+ id: string;
165
+ };
166
+ export type DisputeCaseIncompleteRejection = {
167
+ __typename: "DisputeCaseIncompleteRejection";
168
+ message: string;
169
+ missingFields: DisputeCaseFieldPath[];
170
+ };
171
+ export type DisputeCaseTransactionsAlreadyReportedRejection = {
172
+ __typename: "DisputeCaseTransactionsAlreadyReportedRejection";
173
+ message: string;
174
+ transactions: {
175
+ transactionId: string;
176
+ disputeCaseId: string | null;
177
+ }[];
178
+ };
179
+ export type DraftFraudDisputeCaseRejection = DisputeCaseTransactionsNotFoundRejection | DisputeCaseTransactionsLimitExceededRejection | DisputeCaseMultipleAccountsRejection | DisputeCaseMultipleCardHoldersRejection | DisputeCaseTransactionsNotReportableRejection | DisputeCaseTransactionsOutsideReportingWindowRejection | DisputeCaseDetailsNotApplicableRejection | AccountMembershipNotFoundRejection;
180
+ export type UpdateDraftFraudDisputeCaseRejection = DisputeCaseNotFoundRejection | DisputeCaseWrongStatusRejection | DraftFraudDisputeCaseRejection;
181
+ export type SubmitDisputeCaseRejection = DisputeCaseNotFoundRejection | DisputeCaseIncompleteRejection | DisputeCaseTransactionsAlreadyReportedRejection | DisputeCaseTransactionsNotFoundRejection | DisputeCaseTransactionsNotReportableRejection | DisputeCaseTransactionsOutsideReportingWindowRejection | DisputeCaseWrongStatusRejection;
182
+ export type CancelDisputeCaseRejection = DisputeCaseNotFoundRejection | DisputeCaseWrongStatusRejection;
183
+ export type FraudReportRejection = UpdateDraftFraudDisputeCaseRejection | SubmitDisputeCaseRejection | CancelDisputeCaseRejection;
184
+ export declare const fraudReportSteps: readonly ["Intro", "Victim", "Transactions", "Incident", "Details", "Documents", "Submitted"];
185
+ export type FraudReportStep = (typeof fraudReportSteps)[number];
186
+ export declare const fraudReportDetailsSteps: readonly ["Card", "Transfer", "Fraudster"];
187
+ export type FraudReportDetailsStep = (typeof fraudReportDetailsSteps)[number];