@octap/sdk 0.0.0-stage → 0.2.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/CHANGELOG.md +67 -0
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/dist/client.d.ts +150 -0
- package/dist/client.js +297 -0
- package/dist/client.js.map +1 -0
- package/dist/errors/index.d.ts +19 -0
- package/dist/errors/index.js +48 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/transports/rest.transport.d.ts +7 -0
- package/dist/transports/rest.transport.js +2 -0
- package/dist/transports/rest.transport.js.map +1 -0
- package/dist/transports/transport.d.ts +3 -0
- package/dist/transports/transport.js +2 -0
- package/dist/transports/transport.js.map +1 -0
- package/dist/voucher-csv.d.ts +57 -0
- package/dist/voucher-csv.js +343 -0
- package/dist/voucher-csv.js.map +1 -0
- package/dist/webhooks.d.ts +38 -0
- package/dist/webhooks.js +56 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +31 -4
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare class OctaSdkError extends Error {
|
|
2
|
+
constructor(message: string, options?: ErrorOptions);
|
|
3
|
+
}
|
|
4
|
+
export declare class OctaApiError extends OctaSdkError {
|
|
5
|
+
readonly statusCode: number;
|
|
6
|
+
readonly statusText: string;
|
|
7
|
+
readonly responseBody: unknown;
|
|
8
|
+
/** The `Retry-After` header, when Core sent one. */
|
|
9
|
+
readonly retryAfter?: string;
|
|
10
|
+
constructor(statusCode: number, statusText: string, responseBody: unknown, message?: string, retryAfter?: string);
|
|
11
|
+
}
|
|
12
|
+
/** A request may have reached Core; inspect state before retrying a mutation. */
|
|
13
|
+
export declare class OctaNetworkError extends OctaSdkError {
|
|
14
|
+
constructor(cause: unknown);
|
|
15
|
+
}
|
|
16
|
+
/** Cancels local waiting only, not a server-side business operation. */
|
|
17
|
+
export declare class OctaRequestAbortedError extends OctaSdkError {
|
|
18
|
+
constructor(cause?: unknown);
|
|
19
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export class OctaSdkError extends Error {
|
|
2
|
+
constructor(message, options) {
|
|
3
|
+
super(message, options);
|
|
4
|
+
this.name = 'OctaSdkError';
|
|
5
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export class OctaApiError extends OctaSdkError {
|
|
9
|
+
statusCode;
|
|
10
|
+
statusText;
|
|
11
|
+
responseBody;
|
|
12
|
+
/** The `Retry-After` header, when Core sent one. */
|
|
13
|
+
retryAfter;
|
|
14
|
+
constructor(statusCode, statusText, responseBody, message, retryAfter) {
|
|
15
|
+
let msg = message;
|
|
16
|
+
if (!msg) {
|
|
17
|
+
if (typeof responseBody === 'object' && responseBody !== null && 'message' in responseBody) {
|
|
18
|
+
const bodyMsg = responseBody.message;
|
|
19
|
+
msg = Array.isArray(bodyMsg) ? bodyMsg.join(', ') : String(bodyMsg);
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
msg = `API request failed with status ${statusCode} (${statusText})`;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
super(msg);
|
|
26
|
+
this.name = 'OctaApiError';
|
|
27
|
+
this.statusCode = statusCode;
|
|
28
|
+
this.statusText = statusText;
|
|
29
|
+
this.responseBody = responseBody;
|
|
30
|
+
this.retryAfter = retryAfter;
|
|
31
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** A request may have reached Core; inspect state before retrying a mutation. */
|
|
35
|
+
export class OctaNetworkError extends OctaSdkError {
|
|
36
|
+
constructor(cause) {
|
|
37
|
+
super('Network request failed', { cause });
|
|
38
|
+
this.name = 'OctaNetworkError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Cancels local waiting only, not a server-side business operation. */
|
|
42
|
+
export class OctaRequestAbortedError extends OctaSdkError {
|
|
43
|
+
constructor(cause) {
|
|
44
|
+
super('Request aborted', { cause });
|
|
45
|
+
this.name = 'OctaRequestAbortedError';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/errors/index.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,YAAa,SAAQ,KAAK;IACrC,YAAY,OAAe,EAAE,OAAsB;QACjD,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;CACF;AAED,MAAM,OAAO,YAAa,SAAQ,YAAY;IAC5B,UAAU,CAAS;IACnB,UAAU,CAAS;IACnB,YAAY,CAAU;IACtC,oDAAoD;IACpC,UAAU,CAAU;IAEpC,YAAY,UAAkB,EAAE,UAAkB,EAAE,YAAqB,EAAE,OAAgB,EAAE,UAAmB;QAC9G,IAAI,GAAG,GAAG,OAAO,CAAC;QAClB,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,IAAI,OAAO,YAAY,KAAK,QAAQ,IAAI,YAAY,KAAK,IAAI,IAAI,SAAS,IAAI,YAAY,EAAE,CAAC;gBAC3F,MAAM,OAAO,GAAI,YAAqC,CAAC,OAAO,CAAC;gBAC/D,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;YACtE,CAAC;iBAAM,CAAC;gBACN,GAAG,GAAG,kCAAkC,UAAU,KAAK,UAAU,GAAG,CAAC;YACvE,CAAC;QACH,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,CAAC;QACX,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpD,CAAC;CACF;AAED,iFAAiF;AACjF,MAAM,OAAO,gBAAiB,SAAQ,YAAY;IAChD,YAAY,KAAc;QACxB,KAAK,CAAC,wBAAwB,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACjC,CAAC;CACF;AAED,wEAAwE;AACxE,MAAM,OAAO,uBAAwB,SAAQ,YAAY;IACvD,YAAY,KAAe;QACzB,KAAK,CAAC,iBAAiB,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { OctaPointClient, createOctaPointClient, type OctaPointClientOptions, type RequestOptions } from './client.js';
|
|
2
|
+
export { OctaSdkError, OctaApiError, OctaNetworkError, OctaRequestAbortedError } from './errors/index.js';
|
|
3
|
+
export { verifyWebhookSignature, constructWebhookEvent } from './webhooks.js';
|
|
4
|
+
export { parseVoucherCsv, suggestVoucherCode, VOUCHER_BENEFIT_SCHEMA, VOUCHER_CSV_TEMPLATE, VOUCHER_CSV_TYPES, type ParsedVoucherCsv, type ParseVoucherCsvOptions, type VoucherBenefitKind, type VoucherCsvRow, } from './voucher-csv.js';
|
|
5
|
+
export type { Transport, RestTransport } from './transports/transport.js';
|
|
6
|
+
export type { Points, BalanceSnapshot, LoyaltyTxType, LoyaltyTxStatus, EarnPointsRequest, EarnPointsResponse, IssuanceBudgetDto, IssuanceBudgetShard, IssuanceBudgetTopUp, BudgetWarningThreshold, PosRedemptionBenefit, ReservePosRedemptionRequest, ReservePosRedemptionResponse, FinalizePosRedemptionRequest, FinalizePosRedemptionResponse, ReverseTransactionRequest, ReverseTransactionResponse, CreditBalanceSnapshot, LoyaltyTransactionDto, LoyaltyTransactionPage, VoucherRefundPolicy, VoucherRefundPolicySnapshot, SetVoucherRefundPolicyRequest, ListVoucherRefundPolicyHistoryRequest, VoucherRefundPolicyDto, VoucherStatus, VoucherOwnershipStatus, DiscountType, CreateVoucherRequest, UpdateVoucherRequest, VoucherDto, ClaimVoucherRequest, ClaimVoucherResponse, GrantVoucherRequest, PrepareVoucherUseRequest, PrepareVoucherUseResponse, FinalizeVoucherUseRequest, RedeemVoucherResponse, VoucherOwnershipDto, VoucherBatchSource, VoucherBatchItem, CreateVoucherBatchRequest, CreateVoucherBatchResponse, VoucherBatchItemErrorCode, VoucherBatchItemResult, VoucherFieldDifference, VoucherBatchDto, VoucherBatchStatusCounts, VoucherBatchDetailDto, ListVoucherBatchesRequest, VoucherBatchOutcome, VoucherBatchActivationOutcome, VoucherBatchActionResult, VoucherBatchActionResponse, WebhookEndpointStatus, WebhookDeliveryStatus, WebhookEndpointDto, WebhookEndpointWithSecretDto, RegisterWebhookEndpointRequest, WebhookDeliveryDto, WebhookEventType, WebhookEvent, CreditsEarnedEventData, CreditsChainConfirmedEventData, CreditsEarnFailedEventData, EarnFailureCode, BudgetLowEventData, } from '@octap/contracts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { OctaPointClient, createOctaPointClient } from './client.js';
|
|
2
|
+
export { OctaSdkError, OctaApiError, OctaNetworkError, OctaRequestAbortedError } from './errors/index.js';
|
|
3
|
+
export { verifyWebhookSignature, constructWebhookEvent } from './webhooks.js';
|
|
4
|
+
export { parseVoucherCsv, suggestVoucherCode, VOUCHER_BENEFIT_SCHEMA, VOUCHER_CSV_TEMPLATE, VOUCHER_CSV_TYPES, } from './voucher-csv.js';
|
|
5
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAoD,MAAM,aAAa,CAAC;AAEvH,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE1G,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAE9E,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,sBAAsB,EACtB,oBAAoB,EACpB,iBAAiB,GAKlB,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rest.transport.js","sourceRoot":"","sources":["../../src/transports/rest.transport.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/transports/transport.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type VoucherBatchItem } from '@octap/contracts';
|
|
2
|
+
/**
|
|
3
|
+
* Reads the Octap voucher CSV template, the same file the console imports, into items for
|
|
4
|
+
* `createVouchers`. It makes the same checks as the console: a row it can't read, that breaks a
|
|
5
|
+
* rule, or that repeats an earlier row's code is reported with a `problem` and left out of `items`.
|
|
6
|
+
* Core still checks every item when it is sent.
|
|
7
|
+
*/
|
|
8
|
+
/** Marks `terms` written in this shape, so the console and any reader know which fields to expect. */
|
|
9
|
+
export declare const VOUCHER_BENEFIT_SCHEMA = "octap.benefit.v1";
|
|
10
|
+
/** The reward kinds of the template, as `terms.kind`. */
|
|
11
|
+
export type VoucherBenefitKind = 'PERCENT_OFF' | 'AMOUNT_OFF' | 'FREE_ITEM' | 'BUY_X_GET_Y' | 'FREE_SHIPPING' | 'FIXED_PRICE' | 'CUSTOM';
|
|
12
|
+
/** The `type` column's values, one per kind. */
|
|
13
|
+
export declare const VOUCHER_CSV_TYPES: readonly ["percent_off", "amount_off", "free_item", "buy_x_get_y", "free_shipping", "fixed_price", "custom"];
|
|
14
|
+
/** The template with one example row per kind, the same as the console's download. */
|
|
15
|
+
export declare const VOUCHER_CSV_TEMPLATE: string;
|
|
16
|
+
/** One row of the file: the item sent to Core, or why it was left out. */
|
|
17
|
+
export interface VoucherCsvRow {
|
|
18
|
+
/** The row's line in the file; the header is line 1. */
|
|
19
|
+
line: number;
|
|
20
|
+
/** The row's code (made from its title when the cell is empty); `null` when it has none. */
|
|
21
|
+
code: string | null;
|
|
22
|
+
/** Set when the row passed every check. */
|
|
23
|
+
item?: VoucherBatchItem;
|
|
24
|
+
/** Why the row was left out, naming the CSV column: `points_cost: Enter a whole number…`. */
|
|
25
|
+
problem?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface ParsedVoucherCsv {
|
|
28
|
+
/**
|
|
29
|
+
* The rows that passed, in file order, ready for `createVouchers`. `items[i]` is the item of
|
|
30
|
+
* `rows.filter((row) => row.item)[i]`, so a result's `index` leads back to its line.
|
|
31
|
+
*/
|
|
32
|
+
items: VoucherBatchItem[];
|
|
33
|
+
/** Every row of the file, with its item or its problem. */
|
|
34
|
+
rows: VoucherCsvRow[];
|
|
35
|
+
/** Set when the whole file is refused (empty, a required column missing, too many rows). */
|
|
36
|
+
error?: string;
|
|
37
|
+
}
|
|
38
|
+
export interface ParseVoucherCsvOptions {
|
|
39
|
+
/**
|
|
40
|
+
* The UTC offset dates are read in: `claims_open_on` starts at 00:00:00 and `claims_close_on` ends
|
|
41
|
+
* at 23:59:59 of that day there. Defaults to `+07:00` (Vietnam). `Z` is UTC.
|
|
42
|
+
*/
|
|
43
|
+
utcOffset?: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Reads a CSV in the Octap voucher template into items for `createVouchers`.
|
|
47
|
+
*
|
|
48
|
+
* ```ts
|
|
49
|
+
* const { items, rows, error } = parseVoucherCsv(await readFile('rewards.csv', 'utf8'));
|
|
50
|
+
* if (error) throw new Error(error);
|
|
51
|
+
* for (const row of rows) if (row.problem) console.warn(`line ${row.line}: ${row.problem}`);
|
|
52
|
+
* const preview = await client.createVouchers(items, { dryRun: true });
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export declare function parseVoucherCsv(text: string, options?: ParseVoucherCsvOptions): ParsedVoucherCsv;
|
|
56
|
+
/** `Trà sữa trân châu!` → `TRA-SUA-TRAN-CHAU`, as the console makes a code from a title. */
|
|
57
|
+
export declare function suggestVoucherCode(title: string): string;
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { VOUCHER_BATCH_MAX_ITEMS, VOUCHER_MAX_VALID_FOR_DAYS } from '@octap/contracts';
|
|
2
|
+
/**
|
|
3
|
+
* Reads the Octap voucher CSV template, the same file the console imports, into items for
|
|
4
|
+
* `createVouchers`. It makes the same checks as the console: a row it can't read, that breaks a
|
|
5
|
+
* rule, or that repeats an earlier row's code is reported with a `problem` and left out of `items`.
|
|
6
|
+
* Core still checks every item when it is sent.
|
|
7
|
+
*/
|
|
8
|
+
/** Marks `terms` written in this shape, so the console and any reader know which fields to expect. */
|
|
9
|
+
export const VOUCHER_BENEFIT_SCHEMA = 'octap.benefit.v1';
|
|
10
|
+
/** The `type` column's values, one per kind. */
|
|
11
|
+
export const VOUCHER_CSV_TYPES = [
|
|
12
|
+
'percent_off',
|
|
13
|
+
'amount_off',
|
|
14
|
+
'free_item',
|
|
15
|
+
'buy_x_get_y',
|
|
16
|
+
'free_shipping',
|
|
17
|
+
'fixed_price',
|
|
18
|
+
'custom',
|
|
19
|
+
];
|
|
20
|
+
const COLUMNS = [
|
|
21
|
+
'type',
|
|
22
|
+
'title',
|
|
23
|
+
'code',
|
|
24
|
+
'points_cost',
|
|
25
|
+
'value',
|
|
26
|
+
'max_discount_vnd',
|
|
27
|
+
'min_order_vnd',
|
|
28
|
+
'item',
|
|
29
|
+
'buy_quantity',
|
|
30
|
+
'get_quantity',
|
|
31
|
+
'price_vnd',
|
|
32
|
+
'benefit',
|
|
33
|
+
'applies_to',
|
|
34
|
+
'total_supply',
|
|
35
|
+
'per_member_limit',
|
|
36
|
+
'claims_open_on',
|
|
37
|
+
'claims_close_on',
|
|
38
|
+
'valid_for_days',
|
|
39
|
+
'description',
|
|
40
|
+
];
|
|
41
|
+
/** Headers of earlier templates, still read so an old file keeps working. */
|
|
42
|
+
const LEGACY_HEADERS = { starts_on: 'claims_open_on', expires_on: 'claims_close_on' };
|
|
43
|
+
const KIND_ALIASES = {
|
|
44
|
+
percent_off: 'PERCENT_OFF',
|
|
45
|
+
percent: 'PERCENT_OFF',
|
|
46
|
+
amount_off: 'AMOUNT_OFF',
|
|
47
|
+
amount: 'AMOUNT_OFF',
|
|
48
|
+
free_item: 'FREE_ITEM',
|
|
49
|
+
buy_x_get_y: 'BUY_X_GET_Y',
|
|
50
|
+
free_shipping: 'FREE_SHIPPING',
|
|
51
|
+
free_delivery: 'FREE_SHIPPING',
|
|
52
|
+
fixed_price: 'FIXED_PRICE',
|
|
53
|
+
special_price: 'FIXED_PRICE',
|
|
54
|
+
custom: 'CUSTOM',
|
|
55
|
+
};
|
|
56
|
+
/** The template with one example row per kind, the same as the console's download. */
|
|
57
|
+
export const VOUCHER_CSV_TEMPLATE = [
|
|
58
|
+
COLUMNS.join(','),
|
|
59
|
+
'percent_off,20% off drinks,DRINKS-20,300,20,50000,200000,,,,,,Drinks only,100,1,,2027-12-31,14,',
|
|
60
|
+
'amount_off,30000 off,SAVE-30K,400,30000,,150000,,,,,,,,3,,2027-12-31,30,',
|
|
61
|
+
'free_item,A free latte,FREE-LATTE,500,,,,"Latte, size M",,,,,,50,,,2027-12-31,30,',
|
|
62
|
+
'buy_x_get_y,Buy 1 get 1 tea,B1G1-TEA,600,,,,Milk tea,1,1,,,,,1,,2027-12-31,,',
|
|
63
|
+
'free_shipping,Free delivery,FREE-SHIP,200,,20000,100000,,,,,,,,,,2027-12-31,,',
|
|
64
|
+
'fixed_price,Combo 99k,COMBO-99K,350,,,,Burger and drink,,,99000,,,,,,2027-12-31,7,',
|
|
65
|
+
'custom,Spa afternoon,SPA-PASS,2000,,,,,,,,One 60-minute treatment,,10,1,,2027-12-31,,Book 2 days ahead',
|
|
66
|
+
].join('\n');
|
|
67
|
+
/**
|
|
68
|
+
* Reads a CSV in the Octap voucher template into items for `createVouchers`.
|
|
69
|
+
*
|
|
70
|
+
* ```ts
|
|
71
|
+
* const { items, rows, error } = parseVoucherCsv(await readFile('rewards.csv', 'utf8'));
|
|
72
|
+
* if (error) throw new Error(error);
|
|
73
|
+
* for (const row of rows) if (row.problem) console.warn(`line ${row.line}: ${row.problem}`);
|
|
74
|
+
* const preview = await client.createVouchers(items, { dryRun: true });
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
export function parseVoucherCsv(text, options = {}) {
|
|
78
|
+
const offset = options.utcOffset ?? '+07:00';
|
|
79
|
+
if (!/^(Z|[+-](0\d|1[0-4]):[0-5]\d)$/.test(offset))
|
|
80
|
+
throw new TypeError(`utcOffset must look like +07:00, -05:00 or Z; got "${offset}"`);
|
|
81
|
+
const [header, ...body] = parseCsv(text);
|
|
82
|
+
if (!header)
|
|
83
|
+
return { items: [], rows: [], error: 'The file is empty.' };
|
|
84
|
+
const index = header.map((h) => {
|
|
85
|
+
const name = h.trim().toLowerCase();
|
|
86
|
+
return LEGACY_HEADERS[name] ?? name;
|
|
87
|
+
});
|
|
88
|
+
const missing = ['type', 'title', 'points_cost'].filter((h) => !index.includes(h));
|
|
89
|
+
if (missing.length)
|
|
90
|
+
return { items: [], rows: [], error: `Missing column(s): ${missing.join(', ')}. Use the template.` };
|
|
91
|
+
if (body.length > VOUCHER_BATCH_MAX_ITEMS)
|
|
92
|
+
return {
|
|
93
|
+
items: [],
|
|
94
|
+
rows: [],
|
|
95
|
+
error: `At most ${VOUCHER_BATCH_MAX_ITEMS} vouchers per file; this one has ${body.length}.`,
|
|
96
|
+
};
|
|
97
|
+
const seen = new Map();
|
|
98
|
+
const rows = body.map((cells, i) => {
|
|
99
|
+
const line = i + 2;
|
|
100
|
+
const cell = (column) => {
|
|
101
|
+
const at = index.indexOf(column);
|
|
102
|
+
return at < 0 ? '' : (cells[at] ?? '').trim();
|
|
103
|
+
};
|
|
104
|
+
const row = readRow(cell, offset);
|
|
105
|
+
const code = row.item?.code ?? (row.code || null);
|
|
106
|
+
const problems = [...row.problems];
|
|
107
|
+
const earlier = code ? seen.get(code) : undefined;
|
|
108
|
+
if (code && earlier && !problems.length)
|
|
109
|
+
problems.push(`code: ${code} is already used by line ${earlier}`);
|
|
110
|
+
// Only a row that is sent takes its code: a corrected copy of a bad row is not a repeat.
|
|
111
|
+
if (code && !earlier && !problems.length)
|
|
112
|
+
seen.set(code, line);
|
|
113
|
+
return problems.length || !row.item
|
|
114
|
+
? { line, code, problem: problems.join('; ') || 'This row could not be read' }
|
|
115
|
+
: { line, code, item: row.item };
|
|
116
|
+
});
|
|
117
|
+
return { items: rows.flatMap((row) => (row.item ? [row.item] : [])), rows };
|
|
118
|
+
}
|
|
119
|
+
const CODE_PATTERN = /^[A-Za-z0-9_-]{1,80}$/;
|
|
120
|
+
const whole = (value) => /^\d+$/.test(value);
|
|
121
|
+
const positiveAmount = (value) => /^\d{1,10}(\.\d{1,2})?$/.test(value) && Number(value) > 0;
|
|
122
|
+
/** `Trà sữa trân châu!` → `TRA-SUA-TRAN-CHAU`, as the console makes a code from a title. */
|
|
123
|
+
export function suggestVoucherCode(title) {
|
|
124
|
+
return title
|
|
125
|
+
.normalize('NFD')
|
|
126
|
+
.replace(/[̀-ͯ]/g, '')
|
|
127
|
+
.replace(/[đĐ]/g, 'D')
|
|
128
|
+
.toUpperCase()
|
|
129
|
+
.replace(/[^A-Z0-9]+/g, '-')
|
|
130
|
+
.replace(/^-+|-+$/g, '')
|
|
131
|
+
.slice(0, 40)
|
|
132
|
+
.replace(/-+$/g, '');
|
|
133
|
+
}
|
|
134
|
+
/** One row's checks, and its item when they all pass. Mirrors the console's form. */
|
|
135
|
+
function readRow(cell, offset) {
|
|
136
|
+
const problems = [];
|
|
137
|
+
const fail = (column, message) => problems.push(`${column}: ${message}`);
|
|
138
|
+
const typeCell = cell('type').toLowerCase();
|
|
139
|
+
const kind = KIND_ALIASES[typeCell] ?? KIND_ALIASES[typeCell.replace(/\s+/g, '_')];
|
|
140
|
+
if (!kind)
|
|
141
|
+
problems.push(`Unknown type "${cell('type')}"`);
|
|
142
|
+
const title = cell('title');
|
|
143
|
+
const code = cell('code') || suggestVoucherCode(title);
|
|
144
|
+
if (!title)
|
|
145
|
+
fail('title', 'Enter a title');
|
|
146
|
+
else if (title.length > 200)
|
|
147
|
+
fail('title', 'At most 200 characters');
|
|
148
|
+
if (!CODE_PATTERN.test(code))
|
|
149
|
+
fail('code', 'Letters, numbers, - and _ only (at most 80)');
|
|
150
|
+
const points = cell('points_cost');
|
|
151
|
+
if (!whole(points))
|
|
152
|
+
fail('points_cost', 'Enter a whole number of points (0 for free)');
|
|
153
|
+
const positiveWhole = (column, message) => {
|
|
154
|
+
const value = cell(column);
|
|
155
|
+
if (!value)
|
|
156
|
+
return null;
|
|
157
|
+
if (!(whole(value) && Number(value) > 0))
|
|
158
|
+
fail(column, message);
|
|
159
|
+
return Number(value);
|
|
160
|
+
};
|
|
161
|
+
const totalSupply = positiveWhole('total_supply', 'Enter a positive whole number, or leave empty for unlimited');
|
|
162
|
+
const perMemberLimit = positiveWhole('per_member_limit', 'Enter a positive whole number, or leave empty for no limit');
|
|
163
|
+
const days = cell('valid_for_days');
|
|
164
|
+
if (days && !(whole(days) && Number(days) >= 1 && Number(days) <= VOUCHER_MAX_VALID_FOR_DAYS))
|
|
165
|
+
fail('valid_for_days', `Enter a whole number of days from 1 to ${VOUCHER_MAX_VALID_FOR_DAYS}`);
|
|
166
|
+
const date = (column) => {
|
|
167
|
+
const value = cell(column);
|
|
168
|
+
if (!value)
|
|
169
|
+
return '';
|
|
170
|
+
const read = csvDate(value);
|
|
171
|
+
if ('problem' in read) {
|
|
172
|
+
fail(column, read.problem);
|
|
173
|
+
return '';
|
|
174
|
+
}
|
|
175
|
+
return read.day;
|
|
176
|
+
};
|
|
177
|
+
const opens = date('claims_open_on');
|
|
178
|
+
const closes = date('claims_close_on');
|
|
179
|
+
if (opens && closes && opens > closes)
|
|
180
|
+
fail('claims_close_on', 'Must be on or after the opening date');
|
|
181
|
+
const vnd = (column) => {
|
|
182
|
+
const value = cell(column);
|
|
183
|
+
if (value && !whole(value))
|
|
184
|
+
fail(column, 'Enter an amount in VND');
|
|
185
|
+
return value;
|
|
186
|
+
};
|
|
187
|
+
const minOrder = vnd('min_order_vnd');
|
|
188
|
+
const terms = { schema: VOUCHER_BENEFIT_SCHEMA, kind: kind ?? 'CUSTOM' };
|
|
189
|
+
const setNumber = (key, value) => {
|
|
190
|
+
if (value)
|
|
191
|
+
terms[key] = Number(value);
|
|
192
|
+
};
|
|
193
|
+
setNumber('minOrderVnd', minOrder);
|
|
194
|
+
if (cell('applies_to'))
|
|
195
|
+
terms.appliesTo = cell('applies_to');
|
|
196
|
+
let discountType;
|
|
197
|
+
let discountValue;
|
|
198
|
+
const value = cell('value');
|
|
199
|
+
const item = cell('item');
|
|
200
|
+
switch (kind) {
|
|
201
|
+
case 'PERCENT_OFF':
|
|
202
|
+
if (!positiveAmount(value) || Number(value) > 100)
|
|
203
|
+
fail('value', 'Enter a percentage above 0, at most 100');
|
|
204
|
+
setNumber('maxDiscountVnd', vnd('max_discount_vnd'));
|
|
205
|
+
discountType = 'PERCENTAGE';
|
|
206
|
+
discountValue = value;
|
|
207
|
+
break;
|
|
208
|
+
case 'AMOUNT_OFF':
|
|
209
|
+
if (!positiveAmount(value))
|
|
210
|
+
fail('value', 'Enter an amount in VND');
|
|
211
|
+
discountType = 'FIXED_AMOUNT';
|
|
212
|
+
discountValue = value;
|
|
213
|
+
break;
|
|
214
|
+
case 'FREE_ITEM':
|
|
215
|
+
if (!item)
|
|
216
|
+
fail('item', 'Say which item is free');
|
|
217
|
+
terms.item = item;
|
|
218
|
+
discountType = 'FREE_ITEM';
|
|
219
|
+
break;
|
|
220
|
+
case 'BUY_X_GET_Y': {
|
|
221
|
+
const buy = cell('buy_quantity') || '1';
|
|
222
|
+
const get = cell('get_quantity') || '1';
|
|
223
|
+
if (!(whole(buy) && Number(buy) > 0))
|
|
224
|
+
fail('buy_quantity', 'At least 1');
|
|
225
|
+
if (!(whole(get) && Number(get) > 0))
|
|
226
|
+
fail('get_quantity', 'At least 1');
|
|
227
|
+
if (!item)
|
|
228
|
+
fail('item', 'Say which item it applies to');
|
|
229
|
+
terms.buyQuantity = Number(buy);
|
|
230
|
+
terms.getQuantity = Number(get);
|
|
231
|
+
terms.item = item;
|
|
232
|
+
break;
|
|
233
|
+
}
|
|
234
|
+
case 'FREE_SHIPPING':
|
|
235
|
+
setNumber('maxDiscountVnd', vnd('max_discount_vnd'));
|
|
236
|
+
break;
|
|
237
|
+
case 'FIXED_PRICE': {
|
|
238
|
+
const price = vnd('price_vnd');
|
|
239
|
+
if (!price)
|
|
240
|
+
fail('price_vnd', 'Enter the special price');
|
|
241
|
+
if (!item)
|
|
242
|
+
fail('item', 'Say what the price is for');
|
|
243
|
+
setNumber('priceVnd', price);
|
|
244
|
+
terms.item = item;
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
case 'CUSTOM':
|
|
248
|
+
if (!cell('benefit'))
|
|
249
|
+
fail('benefit', 'Describe what the customer gets');
|
|
250
|
+
terms.benefit = cell('benefit');
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
if (problems.length)
|
|
254
|
+
return { code, problems };
|
|
255
|
+
const description = cell('description');
|
|
256
|
+
return {
|
|
257
|
+
code,
|
|
258
|
+
problems,
|
|
259
|
+
item: {
|
|
260
|
+
code,
|
|
261
|
+
title,
|
|
262
|
+
...(description ? { description } : {}),
|
|
263
|
+
pointsCost: Number(points),
|
|
264
|
+
...(discountType ? { discountType } : {}),
|
|
265
|
+
...(discountValue ? { discountValue } : {}),
|
|
266
|
+
terms,
|
|
267
|
+
totalSupply,
|
|
268
|
+
perMemberLimit,
|
|
269
|
+
startsAt: opens ? new Date(`${opens}T00:00:00${offset}`).toISOString() : null,
|
|
270
|
+
expiresAt: closes ? new Date(`${closes}T23:59:59${offset}`).toISOString() : null,
|
|
271
|
+
validForDays: days ? Number(days) : null,
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* A date cell as `YYYY-MM-DD`. Excel rewrites dates in the computer's own format when it saves a
|
|
277
|
+
* CSV (`12/31/2027` on a US Mac, `31/12/2027` in Vietnam), so `D/M/YYYY` and `M/D/YYYY` are read too
|
|
278
|
+
* when only one of them is a real date. `05/02/2027` could be 5 February or 2 May: refused.
|
|
279
|
+
*/
|
|
280
|
+
function csvDate(cell) {
|
|
281
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
282
|
+
const real = (y, m, d) => {
|
|
283
|
+
const date = new Date(Date.UTC(y, m - 1, d));
|
|
284
|
+
return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d;
|
|
285
|
+
};
|
|
286
|
+
const ok = (y, m, d) => (real(y, m, d) ? { day: `${y}-${pad(m)}-${pad(d)}` } : undefined);
|
|
287
|
+
const unreadable = { problem: `"${cell}" is not a date; write it as YYYY-MM-DD, e.g. 2027-12-31` };
|
|
288
|
+
const iso = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/.exec(cell);
|
|
289
|
+
if (iso)
|
|
290
|
+
return ok(Number(iso[1]), Number(iso[2]), Number(iso[3])) ?? unreadable;
|
|
291
|
+
const local = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/.exec(cell);
|
|
292
|
+
if (!local)
|
|
293
|
+
return unreadable;
|
|
294
|
+
const [a, b, year] = [Number(local[1]), Number(local[2]), Number(local[3])];
|
|
295
|
+
const dayFirst = ok(year, b, a);
|
|
296
|
+
const monthFirst = ok(year, a, b);
|
|
297
|
+
if (dayFirst && monthFirst && a !== b)
|
|
298
|
+
return { problem: `"${cell}" could be ${dayFirst.day} or ${monthFirst.day}; write it as YYYY-MM-DD` };
|
|
299
|
+
return dayFirst ?? monthFirst ?? unreadable;
|
|
300
|
+
}
|
|
301
|
+
/** RFC 4180 CSV: quoted fields may hold commas, quotes ("") and line breaks; a UTF-8 BOM is skipped. */
|
|
302
|
+
function parseCsv(text) {
|
|
303
|
+
const rows = [];
|
|
304
|
+
let row = [];
|
|
305
|
+
let field = '';
|
|
306
|
+
let quoted = false;
|
|
307
|
+
const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
308
|
+
for (let i = 0; i < source.length; i += 1) {
|
|
309
|
+
const char = source[i];
|
|
310
|
+
if (quoted) {
|
|
311
|
+
if (char === '"' && source[i + 1] === '"') {
|
|
312
|
+
field += '"';
|
|
313
|
+
i += 1;
|
|
314
|
+
}
|
|
315
|
+
else if (char === '"')
|
|
316
|
+
quoted = false;
|
|
317
|
+
else
|
|
318
|
+
field += char;
|
|
319
|
+
}
|
|
320
|
+
else if (char === '"')
|
|
321
|
+
quoted = true;
|
|
322
|
+
else if (char === ',') {
|
|
323
|
+
row.push(field);
|
|
324
|
+
field = '';
|
|
325
|
+
}
|
|
326
|
+
else if (char === '\n' || char === '\r') {
|
|
327
|
+
if (char === '\r' && source[i + 1] === '\n')
|
|
328
|
+
i += 1;
|
|
329
|
+
row.push(field);
|
|
330
|
+
rows.push(row);
|
|
331
|
+
row = [];
|
|
332
|
+
field = '';
|
|
333
|
+
}
|
|
334
|
+
else
|
|
335
|
+
field += char;
|
|
336
|
+
}
|
|
337
|
+
if (field || row.length) {
|
|
338
|
+
row.push(field);
|
|
339
|
+
rows.push(row);
|
|
340
|
+
}
|
|
341
|
+
return rows.filter((r) => r.some((cell) => cell.trim()));
|
|
342
|
+
}
|
|
343
|
+
//# sourceMappingURL=voucher-csv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"voucher-csv.js","sourceRoot":"","sources":["../src/voucher-csv.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,0BAA0B,EAAyB,MAAM,kBAAkB,CAAC;AAE9G;;;;;GAKG;AAEH,sGAAsG;AACtG,MAAM,CAAC,MAAM,sBAAsB,GAAG,kBAAkB,CAAC;AAMzD,gDAAgD;AAChD,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,aAAa;IACb,YAAY;IACZ,WAAW;IACX,aAAa;IACb,eAAe;IACf,aAAa;IACb,QAAQ;CACA,CAAC;AAEX,MAAM,OAAO,GAAG;IACd,MAAM;IACN,OAAO;IACP,MAAM;IACN,aAAa;IACb,OAAO;IACP,kBAAkB;IAClB,eAAe;IACf,MAAM;IACN,cAAc;IACd,cAAc;IACd,WAAW;IACX,SAAS;IACT,YAAY;IACZ,cAAc;IACd,kBAAkB;IAClB,gBAAgB;IAChB,iBAAiB;IACjB,gBAAgB;IAChB,aAAa;CACL,CAAC;AAGX,6EAA6E;AAC7E,MAAM,cAAc,GAAoC,EAAE,SAAS,EAAE,gBAAgB,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;AAEvH,MAAM,YAAY,GAAuC;IACvD,WAAW,EAAE,aAAa;IAC1B,OAAO,EAAE,aAAa;IACtB,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,YAAY;IACpB,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,aAAa,EAAE,eAAe;IAC9B,aAAa,EAAE,eAAe;IAC9B,WAAW,EAAE,aAAa;IAC1B,aAAa,EAAE,aAAa;IAC5B,MAAM,EAAE,QAAQ;CACjB,CAAC;AAEF,sFAAsF;AACtF,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,OAAO,CAAC,IAAI,CAAC,GAA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,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { WebhookEvent } from '@octap/contracts';
|
|
2
|
+
/**
|
|
3
|
+
* Verifies an OctaP webhook's `x-octap-signature` header against the exact raw request body
|
|
4
|
+
* bytes (parse the body only after this returns true — a re-serialized JSON object will not
|
|
5
|
+
* match if key order or whitespace differs from what was actually sent).
|
|
6
|
+
*/
|
|
7
|
+
export declare function verifyWebhookSignature(rawBody: string, signature: string, secret: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Reference pattern for an idempotent receiver: OctaP retries a delivery (and a human can
|
|
10
|
+
* replay a dead-lettered one) without ever changing its `x-octap-event-id`, so a receiver only
|
|
11
|
+
* needs to remember ids it has already processed.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* const seen = new Set<string>(); // swap for a real store (DB/Redis) in production
|
|
15
|
+
* app.post('/webhooks/octap', (req, res) => {
|
|
16
|
+
* const eventId = req.headers['x-octap-event-id'] as string;
|
|
17
|
+
* if (!verifyWebhookSignature(req.rawBody, req.headers['x-octap-signature'] as string, secret)) {
|
|
18
|
+
* return res.status(401).end();
|
|
19
|
+
* }
|
|
20
|
+
* if (seen.has(eventId)) return res.status(200).end(); // already handled; ack without re-applying
|
|
21
|
+
* seen.add(eventId);
|
|
22
|
+
* // ...apply the event exactly once...
|
|
23
|
+
* res.status(200).end();
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* Verifies `x-octap-signature` and returns the typed event; throws `OctaSdkError` if the signature
|
|
29
|
+
* is missing or wrong. Switch on `event.type` to get the matching `data` shape.
|
|
30
|
+
*
|
|
31
|
+
* ```ts
|
|
32
|
+
* const event = constructWebhookEvent(req.rawBody, req.headers['x-octap-signature'], secret);
|
|
33
|
+
* if (event.type === 'credits.earn.confirmed') {
|
|
34
|
+
* creditCustomer(event.data.organizationEndUserId, event.data.pointsAmount);
|
|
35
|
+
* }
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
export declare function constructWebhookEvent(rawBody: string, signature: string | undefined, secret: string): WebhookEvent;
|
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { OctaSdkError } from './errors/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* Verifies an OctaP webhook's `x-octap-signature` header against the exact raw request body
|
|
5
|
+
* bytes (parse the body only after this returns true — a re-serialized JSON object will not
|
|
6
|
+
* match if key order or whitespace differs from what was actually sent).
|
|
7
|
+
*/
|
|
8
|
+
export function verifyWebhookSignature(rawBody, signature, secret) {
|
|
9
|
+
const expected = createHmac('sha256', secret).update(rawBody).digest('hex');
|
|
10
|
+
const expectedBuf = Buffer.from(expected, 'hex');
|
|
11
|
+
let actualBuf;
|
|
12
|
+
try {
|
|
13
|
+
actualBuf = Buffer.from(signature, 'hex');
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
return expectedBuf.length === actualBuf.length && timingSafeEqual(expectedBuf, actualBuf);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Reference pattern for an idempotent receiver: OctaP retries a delivery (and a human can
|
|
22
|
+
* replay a dead-lettered one) without ever changing its `x-octap-event-id`, so a receiver only
|
|
23
|
+
* needs to remember ids it has already processed.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* const seen = new Set<string>(); // swap for a real store (DB/Redis) in production
|
|
27
|
+
* app.post('/webhooks/octap', (req, res) => {
|
|
28
|
+
* const eventId = req.headers['x-octap-event-id'] as string;
|
|
29
|
+
* if (!verifyWebhookSignature(req.rawBody, req.headers['x-octap-signature'] as string, secret)) {
|
|
30
|
+
* return res.status(401).end();
|
|
31
|
+
* }
|
|
32
|
+
* if (seen.has(eventId)) return res.status(200).end(); // already handled; ack without re-applying
|
|
33
|
+
* seen.add(eventId);
|
|
34
|
+
* // ...apply the event exactly once...
|
|
35
|
+
* res.status(200).end();
|
|
36
|
+
* });
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
/**
|
|
40
|
+
* Verifies `x-octap-signature` and returns the typed event; throws `OctaSdkError` if the signature
|
|
41
|
+
* is missing or wrong. Switch on `event.type` to get the matching `data` shape.
|
|
42
|
+
*
|
|
43
|
+
* ```ts
|
|
44
|
+
* const event = constructWebhookEvent(req.rawBody, req.headers['x-octap-signature'], secret);
|
|
45
|
+
* if (event.type === 'credits.earn.confirmed') {
|
|
46
|
+
* creditCustomer(event.data.organizationEndUserId, event.data.pointsAmount);
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export function constructWebhookEvent(rawBody, signature, secret) {
|
|
51
|
+
if (!signature || !verifyWebhookSignature(rawBody, signature, secret)) {
|
|
52
|
+
throw new OctaSdkError('Invalid OctaP webhook signature');
|
|
53
|
+
}
|
|
54
|
+
return JSON.parse(rawBody);
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=webhooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhooks.js","sourceRoot":"","sources":["../src/webhooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAe,EAAE,SAAiB,EAAE,MAAc;IACvF,MAAM,QAAQ,GAAG,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;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