@pagaqr/mcp 0.0.0-stage → 0.7.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 +9 -0
- package/LICENSE +202 -0
- package/NOTICE +9 -0
- package/README.md +99 -2
- package/dist/capture-cli.d.ts +2 -0
- package/dist/capture-cli.js +34 -0
- package/dist/capture-local.d.ts +9 -0
- package/dist/capture-local.js +18 -0
- package/dist/capture-store.d.ts +7 -0
- package/dist/capture-store.js +175 -0
- package/dist/catalogue.d.ts +33 -0
- package/dist/catalogue.js +78 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +27 -0
- package/dist/diagnose.d.ts +23 -0
- package/dist/diagnose.js +93 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +134 -0
- package/dist/invocation-log.d.ts +9 -0
- package/dist/invocation-log.js +70 -0
- package/dist/masked-terminal.d.ts +4 -0
- package/dist/masked-terminal.js +71 -0
- package/dist/next-postgres.json +92 -0
- package/dist/sbom.cdx.json +523 -0
- package/dist/setup/database.d.ts +7 -0
- package/dist/setup/database.js +83 -0
- package/dist/setup/notice.d.ts +2 -0
- package/dist/setup/notice.js +2 -0
- package/dist/setup/run.d.ts +25 -0
- package/dist/setup/run.js +215 -0
- package/dist/setup/runtime.js +718 -0
- package/dist/setup/state.d.ts +7 -0
- package/dist/setup/state.js +81 -0
- package/dist/setup/step.d.ts +59 -0
- package/dist/setup/step.js +9 -0
- package/dist/setup/steps/pey.d.ts +8 -0
- package/dist/setup/steps/pey.js +271 -0
- package/dist/setup/steps/vercel.d.ts +5 -0
- package/dist/setup/steps/vercel.js +375 -0
- package/dist/setup/store-secrets.d.ts +3 -0
- package/dist/setup/store-secrets.js +67 -0
- package/dist/setup/terminal-guard.d.ts +9 -0
- package/dist/setup/terminal-guard.js +17 -0
- package/dist/setup/verify.d.ts +34 -0
- package/dist/setup/verify.js +144 -0
- package/dist/setup-cli.d.ts +2 -0
- package/dist/setup-cli.js +70 -0
- package/dist/template.d.ts +4 -0
- package/dist/template.js +119 -0
- package/dist/webhook.d.ts +1 -0
- package/dist/webhook.js +30 -0
- package/package.json +51 -3
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare const PROGRESS_FILE = ".pagaqr-setup.json";
|
|
2
|
+
export declare const PRIVATE_FILE = ".env.pagaqr-setup.json";
|
|
3
|
+
export declare function installationRefusal(root: string): string | undefined;
|
|
4
|
+
export declare function installationFile(root: string, name: typeof PROGRESS_FILE | typeof PRIVATE_FILE): {
|
|
5
|
+
read: () => Map<string, string>;
|
|
6
|
+
save(values: ReadonlyMap<string, string>): void;
|
|
7
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, renameSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { gitFileProtection, gitIgnores, gitWorkingTree } from "../capture-store.js";
|
|
5
|
+
export const PROGRESS_FILE = ".pagaqr-setup.json";
|
|
6
|
+
export const PRIVATE_FILE = ".env.pagaqr-setup.json";
|
|
7
|
+
const MAX_BYTES = 64 * 1024;
|
|
8
|
+
export function installationRefusal(root) {
|
|
9
|
+
if (!gitWorkingTree(root))
|
|
10
|
+
return "Esta carpeta no es un repositorio Git. Corre `git init` aquí y vuelve a ejecutar el asistente.";
|
|
11
|
+
for (const [file, description] of [
|
|
12
|
+
[PRIVATE_FILE, "el archivo local de secretos"],
|
|
13
|
+
[PROGRESS_FILE, "el archivo de estado"],
|
|
14
|
+
]) {
|
|
15
|
+
const protection = gitFileProtection(root, file);
|
|
16
|
+
if (protection === "ignored")
|
|
17
|
+
continue;
|
|
18
|
+
const ignore = `Corre \`node -e "require('node:fs').appendFileSync('.gitignore','\\n/${file}*\\n')"\` aquí para agregar la regla y vuelve a ejecutar el asistente.`;
|
|
19
|
+
if (protection === "tracked")
|
|
20
|
+
return `Git ya rastrea ${description} (${file}). Corre \`git rm --cached -- ${file}\` para conservar el archivo fuera del índice. ${ignore}`;
|
|
21
|
+
return `Git debe ignorar ${description} (${file}). ${ignore}`;
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
function missing(cause) {
|
|
26
|
+
return cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
|
27
|
+
}
|
|
28
|
+
function read(root, name) {
|
|
29
|
+
const file = join(root, name);
|
|
30
|
+
let fd;
|
|
31
|
+
try {
|
|
32
|
+
fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
33
|
+
}
|
|
34
|
+
catch (cause) {
|
|
35
|
+
if (missing(cause))
|
|
36
|
+
return new Map();
|
|
37
|
+
throw cause;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const atPath = lstatSync(file);
|
|
41
|
+
const opened = fstatSync(fd);
|
|
42
|
+
if (!gitIgnores(root, name) ||
|
|
43
|
+
!atPath.isFile() ||
|
|
44
|
+
!opened.isFile() ||
|
|
45
|
+
opened.nlink !== 1 ||
|
|
46
|
+
opened.ino !== atPath.ino ||
|
|
47
|
+
opened.dev !== atPath.dev ||
|
|
48
|
+
opened.size > MAX_BYTES)
|
|
49
|
+
throw new Error("Unsafe installation state");
|
|
50
|
+
const data = JSON.parse(readFileSync(fd, "utf8"));
|
|
51
|
+
if (data === null || typeof data !== "object" || Array.isArray(data))
|
|
52
|
+
throw new Error("Invalid installation state");
|
|
53
|
+
const fields = Object.entries(data);
|
|
54
|
+
if (fields.some(([, value]) => typeof value !== "string"))
|
|
55
|
+
throw new Error("Invalid installation state");
|
|
56
|
+
return new Map(fields);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
closeSync(fd);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function installationFile(root, name) {
|
|
63
|
+
return {
|
|
64
|
+
read: () => read(root, name),
|
|
65
|
+
save(values) {
|
|
66
|
+
if (!gitIgnores(root, name))
|
|
67
|
+
throw new Error("Installation file must be ignored by Git");
|
|
68
|
+
read(root, name);
|
|
69
|
+
const scratch = name + "." + randomUUID();
|
|
70
|
+
if (!gitIgnores(root, scratch))
|
|
71
|
+
throw new Error("Temporary installation file must be ignored by Git");
|
|
72
|
+
const content = JSON.stringify(Object.fromEntries(values)) + "\n";
|
|
73
|
+
if (Buffer.byteLength(content) > MAX_BYTES)
|
|
74
|
+
throw new Error("Installation state is too large");
|
|
75
|
+
writeFileSync(join(root, scratch), content, { flag: "wx", mode: 0o600 });
|
|
76
|
+
if (!gitIgnores(root, name))
|
|
77
|
+
throw new Error("Installation file must be ignored by Git");
|
|
78
|
+
renameSync(join(root, scratch), join(root, name));
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contract between the person-only setup wizard and each of its steps.
|
|
3
|
+
*
|
|
4
|
+
* The frame owns the terminal: it captures secrets masked, shows each step's
|
|
5
|
+
* pending changes, asks for confirmation and prints redacted output. A step
|
|
6
|
+
* never prints, never reads the terminal or `process.env`, and never returns
|
|
7
|
+
* a secret inside a summary, a change line or a reason.
|
|
8
|
+
*/
|
|
9
|
+
/** Secrets the frame captures masked, on first use, from a real terminal only. */
|
|
10
|
+
export type SecretName = "PEY_API_KEY" | "VERCEL_TOKEN" | "DATABASE_OWNER_URL";
|
|
11
|
+
export type StepStatus =
|
|
12
|
+
/** Nothing left to do; `summary` is one plain-Spanish line without secrets. */
|
|
13
|
+
{
|
|
14
|
+
readonly kind: "done";
|
|
15
|
+
readonly summary: string;
|
|
16
|
+
}
|
|
17
|
+
/** What `apply` would change, one plain-Spanish line per change, without secrets. */
|
|
18
|
+
| {
|
|
19
|
+
readonly kind: "pending";
|
|
20
|
+
readonly changes: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
/** Cannot continue; `next` tells the person what to do outside the wizard. */
|
|
23
|
+
| {
|
|
24
|
+
readonly kind: "blocked";
|
|
25
|
+
readonly reason: string;
|
|
26
|
+
readonly next: string;
|
|
27
|
+
};
|
|
28
|
+
/** A runtime variable the store needs; the hosting step publishes it. */
|
|
29
|
+
export interface EnvValue {
|
|
30
|
+
readonly value: string;
|
|
31
|
+
/** Published as a sensitive variable and never compared or shown back. */
|
|
32
|
+
readonly sensitive: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface SetupContext {
|
|
35
|
+
readonly projectDir: string;
|
|
36
|
+
readonly environment: "test" | "production";
|
|
37
|
+
readonly fetch: typeof globalThis.fetch;
|
|
38
|
+
readonly signal: AbortSignal;
|
|
39
|
+
/** Returns a secret, asking the person for it masked the first time. */
|
|
40
|
+
secret(name: SecretName): Promise<string>;
|
|
41
|
+
/** Records a runtime variable for the store; a later call replaces it. */
|
|
42
|
+
provide(name: string, value: EnvValue): void;
|
|
43
|
+
provided(): ReadonlyMap<string, EnvValue>;
|
|
44
|
+
/** Persists a non-secret fact (an id, a project name) so a rerun can inspect it. */
|
|
45
|
+
remember(key: string, value: string): void;
|
|
46
|
+
recall(key: string): string | undefined;
|
|
47
|
+
/** Asks a non-secret question; with options, the answer is one of them. */
|
|
48
|
+
ask(question: string, options?: readonly string[]): Promise<string>;
|
|
49
|
+
}
|
|
50
|
+
export interface SetupStep {
|
|
51
|
+
/** Stable kebab-case id, used for `remember` keys and `--revisar` output. */
|
|
52
|
+
readonly id: string;
|
|
53
|
+
/** Plain-Spanish title shown to the person. */
|
|
54
|
+
readonly title: string;
|
|
55
|
+
/** Read-only against every external service; may call `provide` with known values. */
|
|
56
|
+
inspect(context: SetupContext): Promise<StepStatus>;
|
|
57
|
+
/** Runs only after the person confirmed `inspect`'s changes; rerunning it changes nothing twice. */
|
|
58
|
+
apply(context: SetupContext): Promise<StepStatus>;
|
|
59
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contract between the person-only setup wizard and each of its steps.
|
|
3
|
+
*
|
|
4
|
+
* The frame owns the terminal: it captures secrets masked, shows each step's
|
|
5
|
+
* pending changes, asks for confirmation and prints redacted output. A step
|
|
6
|
+
* never prints, never reads the terminal or `process.env`, and never returns
|
|
7
|
+
* a secret inside a summary, a change line or a reason.
|
|
8
|
+
*/
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SetupStep } from "../step.js";
|
|
2
|
+
export interface PeyStepOptions {
|
|
3
|
+
/** Waits between status reads; tests replace it. */
|
|
4
|
+
readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
5
|
+
readonly now?: () => number;
|
|
6
|
+
}
|
|
7
|
+
export declare function createPeyStep(options?: PeyStepOptions): SetupStep;
|
|
8
|
+
export declare const peyStep: SetupStep;
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// The pey step: registers the store's bank account with the store's own key, waits for CoDi to activate it and
|
|
2
|
+
// hands the store its account id and approved CLABE. pey has no API to register the payment notice (webhook): the
|
|
3
|
+
// key's webhook is set in the pey Portal, so this step asks the person to do it there and waits for the frame to
|
|
4
|
+
// provide the notice secret.
|
|
5
|
+
import { canonicalWebhookUrl } from "../../webhook.js";
|
|
6
|
+
/** pey has no sandbox: the test and production environments use the same official API. */
|
|
7
|
+
const TEST_BASE_URL = "https://api.pey.mx";
|
|
8
|
+
const PRODUCTION_BASE_URL = "https://api.pey.mx";
|
|
9
|
+
/** The CLABE pey offers for trying CoDi; it activates at once. */
|
|
10
|
+
const TEST_CLABE = "012180015826225713";
|
|
11
|
+
const WEBHOOK_ROUTE = "/api/pagaqr/webhooks/pey";
|
|
12
|
+
const ACCOUNT_KEY = "pey.bankAccountId";
|
|
13
|
+
const KEY_ID_KEY = "pey.apiKeyId";
|
|
14
|
+
const POLL_LIMIT_MS = 30_000;
|
|
15
|
+
const POLL_EVERY_MS = 3_000;
|
|
16
|
+
function wait(ms, signal) {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
if (signal.aborted)
|
|
19
|
+
return reject(signal.reason);
|
|
20
|
+
const timer = setTimeout(resolve, ms);
|
|
21
|
+
signal.addEventListener("abort", () => {
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
reject(signal.reason);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function baseUrl(context) {
|
|
28
|
+
return context.environment === "production" ? PRODUCTION_BASE_URL : TEST_BASE_URL;
|
|
29
|
+
}
|
|
30
|
+
function lastDigits(clabe) {
|
|
31
|
+
return clabe.slice(-4);
|
|
32
|
+
}
|
|
33
|
+
function record(value) {
|
|
34
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
35
|
+
? value
|
|
36
|
+
: {};
|
|
37
|
+
}
|
|
38
|
+
/** Reads the body as JSON without ever surfacing it: an unreadable body is an empty record. */
|
|
39
|
+
async function readJson(response) {
|
|
40
|
+
try {
|
|
41
|
+
return record(await response.json());
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return {};
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function send(context) {
|
|
48
|
+
return context["fetch"];
|
|
49
|
+
}
|
|
50
|
+
async function readAccount(context, id) {
|
|
51
|
+
const response = await send(context)(`${baseUrl(context)}/bank-account/${encodeURIComponent(id)}`, {
|
|
52
|
+
method: "GET",
|
|
53
|
+
headers: { authorization: `Bearer ${await context.secret("PEY_API_KEY")}` },
|
|
54
|
+
signal: context.signal,
|
|
55
|
+
});
|
|
56
|
+
if (response.status === 404)
|
|
57
|
+
return { kind: "missing" };
|
|
58
|
+
if (response.status !== 200)
|
|
59
|
+
return { kind: "failed", status: response.status };
|
|
60
|
+
const body = await readJson(response);
|
|
61
|
+
const clabe = body["clabe"];
|
|
62
|
+
const status = body["codiStatus"];
|
|
63
|
+
if (typeof clabe !== "string" || typeof status !== "string")
|
|
64
|
+
return { kind: "failed", status: 200 };
|
|
65
|
+
return { kind: "found", clabe, status };
|
|
66
|
+
}
|
|
67
|
+
function failure(status) {
|
|
68
|
+
if (status === 401 || status === 403) {
|
|
69
|
+
return {
|
|
70
|
+
kind: "blocked",
|
|
71
|
+
reason: `pey no aceptó la llave (respuesta ${status}).`,
|
|
72
|
+
next: "Revisa en el Portal de pey que la llave esté activa y vuelve a correr el asistente con esa llave.",
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
kind: "blocked",
|
|
77
|
+
reason: `pey no respondió como se esperaba (respuesta ${status}).`,
|
|
78
|
+
next: "Espera unos minutos y vuelve a correr el asistente. Si sigue igual, escribe al soporte de pey.",
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function storeOrigin(context) {
|
|
82
|
+
return context.provided().get("PAGAQR_STORE_ORIGIN")?.value;
|
|
83
|
+
}
|
|
84
|
+
/** The account is ready; what is left is the key id and the payment notice, which only the Portal shows. */
|
|
85
|
+
function afterActive(context, id, clabe) {
|
|
86
|
+
context.provide("PEY_BASE_URL", { value: baseUrl(context), sensitive: false });
|
|
87
|
+
context.provide("PEY_BANK_ACCOUNT_ID", { value: id, sensitive: false });
|
|
88
|
+
context.provide("PEY_APPROVED_CLABE", { value: clabe, sensitive: true });
|
|
89
|
+
const keyId = context.recall(KEY_ID_KEY);
|
|
90
|
+
if (keyId)
|
|
91
|
+
context.provide("PEY_API_KEY_ID", { value: keyId, sensitive: false });
|
|
92
|
+
if (!context.provided().has("PEY_WEBHOOK_SECRETS")) {
|
|
93
|
+
const origin = storeOrigin(context);
|
|
94
|
+
const url = origin === undefined ? undefined : canonicalWebhookUrl(origin + WEBHOOK_ROUTE);
|
|
95
|
+
return {
|
|
96
|
+
kind: "blocked",
|
|
97
|
+
reason: "Falta que pey sepa a dónde avisar a tu tienda cuando te paguen. pey solo deja hacerlo en su Portal.",
|
|
98
|
+
next: url === undefined
|
|
99
|
+
? "Primero publica tu tienda en Vercel. Después, en el Portal de pey, abre API Keys, edita la llave de esta tienda y pon en «Webhook» la dirección de tu tienda terminada en /api/pagaqr/webhooks/pey. Guarda el secreto del webhook (empieza con whsec_) para dárselo al asistente."
|
|
100
|
+
: `En el Portal de pey, abre API Keys, edita la llave de esta tienda y pon en «Webhook» esta dirección: ${url}. Guarda el secreto del webhook (empieza con whsec_) para dárselo al asistente.`,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (!keyId) {
|
|
104
|
+
return {
|
|
105
|
+
kind: "pending",
|
|
106
|
+
changes: ["Anotar el identificador de tu llave de pey"],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
kind: "done",
|
|
111
|
+
summary: `Tu cuenta CLABE terminación ${lastDigits(clabe)} ya cobra con CoDi en pey.`,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
function waitingForPey(clabe) {
|
|
115
|
+
return {
|
|
116
|
+
kind: "blocked",
|
|
117
|
+
reason: `pey todavía está activando tu cuenta CLABE terminación ${lastDigits(clabe)}. Con una cuenta real puede tardar hasta 5 días hábiles.`,
|
|
118
|
+
next: `Vuelve a correr el asistente cuando pey te avise que la cuenta está activa. Si solo quieres probar ya, usa la CLABE de prueba de pey, ${TEST_CLABE}, que se activa al momento.`,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function statusOf(context, id, account) {
|
|
122
|
+
if (account.kind === "failed")
|
|
123
|
+
return failure(account.status);
|
|
124
|
+
if (account.kind === "missing") {
|
|
125
|
+
return { kind: "pending", changes: ["Registrar tu cuenta CLABE en pey para cobrar con CoDi"] };
|
|
126
|
+
}
|
|
127
|
+
if (account.status === "ACTIVE")
|
|
128
|
+
return afterActive(context, id, account.clabe);
|
|
129
|
+
if (account.status === "PENDING" || account.status === "PROCESSING")
|
|
130
|
+
return waitingForPey(account.clabe);
|
|
131
|
+
return {
|
|
132
|
+
kind: "blocked",
|
|
133
|
+
reason: `pey rechazó la cuenta CLABE terminación ${lastDigits(account.clabe)}.`,
|
|
134
|
+
next: "Revisa la CLABE con tu banco y vuelve a correr el asistente con una CLABE correcta.",
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/** With the account active, the store gets the same key that registered it, published as sensitive. */
|
|
138
|
+
async function settle(context, id, account) {
|
|
139
|
+
if (account.kind === "found" && account.status === "ACTIVE") {
|
|
140
|
+
context.provide("PEY_API_KEY", { value: await context.secret("PEY_API_KEY"), sensitive: true });
|
|
141
|
+
}
|
|
142
|
+
return statusOf(context, id, account);
|
|
143
|
+
}
|
|
144
|
+
async function askClabe(context) {
|
|
145
|
+
const custom = "Otra CLABE";
|
|
146
|
+
let clabe;
|
|
147
|
+
if (context.environment === "test") {
|
|
148
|
+
const choice = await context.ask("¿Qué cuenta CLABE quieres usar para recibir los pagos de prueba?", [
|
|
149
|
+
`La CLABE de prueba de pey (${TEST_CLABE}), que se activa al momento`,
|
|
150
|
+
custom,
|
|
151
|
+
]);
|
|
152
|
+
clabe = choice === custom ? await context.ask("Escribe tu CLABE de 18 dígitos.") : TEST_CLABE;
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
clabe = await context.ask("Escribe la CLABE de 18 dígitos de la cuenta donde quieres recibir los pagos.");
|
|
156
|
+
}
|
|
157
|
+
clabe = clabe.replace(/\s+/g, "");
|
|
158
|
+
return /^\d{18}$/.test(clabe) && (context.environment === "test" || clabe !== TEST_CLABE)
|
|
159
|
+
? clabe
|
|
160
|
+
: undefined;
|
|
161
|
+
}
|
|
162
|
+
const invalidClabe = {
|
|
163
|
+
kind: "blocked",
|
|
164
|
+
reason: "La CLABE debe tener 18 dígitos. La CLABE de prueba solo se admite en modo de prueba.",
|
|
165
|
+
next: "Revisa la CLABE y el modo elegido antes de continuar.",
|
|
166
|
+
};
|
|
167
|
+
const differentClabe = {
|
|
168
|
+
kind: "blocked",
|
|
169
|
+
reason: "La CLABE verificada por pey difiere de la que elegiste.",
|
|
170
|
+
next: "Confirma en el Portal de pey qué cuenta está ligada a esta llave antes de continuar.",
|
|
171
|
+
};
|
|
172
|
+
async function register(context, clabe) {
|
|
173
|
+
const name = (await context.ask("¿A nombre de quién está la cuenta? Escríbelo como aparece en tu banco.")).trim();
|
|
174
|
+
const entity = await context.ask("¿La cuenta es de una persona o de una empresa?", ["Persona", "Empresa"]);
|
|
175
|
+
const response = await send(context)(`${baseUrl(context)}/bank-account`, {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: {
|
|
178
|
+
authorization: `Bearer ${await context.secret("PEY_API_KEY")}`,
|
|
179
|
+
"content-type": "application/json",
|
|
180
|
+
},
|
|
181
|
+
body: JSON.stringify({
|
|
182
|
+
alias: "PagaQR",
|
|
183
|
+
name,
|
|
184
|
+
clabe,
|
|
185
|
+
entity: entity === "Empresa" ? "BUSINESS" : "PERSON",
|
|
186
|
+
}),
|
|
187
|
+
signal: context.signal,
|
|
188
|
+
});
|
|
189
|
+
if (response.status === 400) {
|
|
190
|
+
return {
|
|
191
|
+
kind: "blocked",
|
|
192
|
+
reason: "pey no aceptó los datos de la cuenta (respuesta 400).",
|
|
193
|
+
next: "Revisa la CLABE y el nombre del titular con tu banco y vuelve a correr el asistente.",
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (response.status !== 200 && response.status !== 201)
|
|
197
|
+
return failure(response.status);
|
|
198
|
+
const registered = await readJson(response);
|
|
199
|
+
if (registered["clabe"] !== undefined && registered["clabe"] !== clabe)
|
|
200
|
+
return differentClabe;
|
|
201
|
+
const id = registered["id"];
|
|
202
|
+
if (typeof id !== "string" || !id)
|
|
203
|
+
return failure(response.status);
|
|
204
|
+
return id;
|
|
205
|
+
}
|
|
206
|
+
export function createPeyStep(options = {}) {
|
|
207
|
+
const sleep = options.sleep ?? wait;
|
|
208
|
+
const now = options.now ?? Date.now;
|
|
209
|
+
const selections = new WeakMap();
|
|
210
|
+
async function selected(context) {
|
|
211
|
+
const previous = selections.get(context);
|
|
212
|
+
if (previous)
|
|
213
|
+
return previous;
|
|
214
|
+
const clabe = await askClabe(context);
|
|
215
|
+
if (clabe)
|
|
216
|
+
selections.set(context, clabe);
|
|
217
|
+
return clabe;
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
id: "pey",
|
|
221
|
+
title: "Cuenta para cobrar con CoDi en pey",
|
|
222
|
+
async inspect(context) {
|
|
223
|
+
const id = context.recall(ACCOUNT_KEY);
|
|
224
|
+
if (!id)
|
|
225
|
+
return { kind: "pending", changes: ["Registrar tu cuenta CLABE en pey para cobrar con CoDi"] };
|
|
226
|
+
const account = await readAccount(context, id);
|
|
227
|
+
if (account.kind === "found") {
|
|
228
|
+
const expected = await selected(context);
|
|
229
|
+
if (!expected)
|
|
230
|
+
return invalidClabe;
|
|
231
|
+
if (account.clabe !== expected)
|
|
232
|
+
return differentClabe;
|
|
233
|
+
}
|
|
234
|
+
return settle(context, id, account);
|
|
235
|
+
},
|
|
236
|
+
async apply(context) {
|
|
237
|
+
let id = context.recall(ACCOUNT_KEY);
|
|
238
|
+
let account = id ? await readAccount(context, id) : { kind: "missing" };
|
|
239
|
+
if (account.kind === "failed")
|
|
240
|
+
return failure(account.status);
|
|
241
|
+
const clabe = await selected(context);
|
|
242
|
+
if (!clabe)
|
|
243
|
+
return invalidClabe;
|
|
244
|
+
if (!id || account.kind === "missing") {
|
|
245
|
+
const registered = await register(context, clabe);
|
|
246
|
+
if (typeof registered !== "string")
|
|
247
|
+
return registered;
|
|
248
|
+
id = registered;
|
|
249
|
+
// Remembered before polling: a rerun reads this account instead of registering the CLABE again.
|
|
250
|
+
context.remember(ACCOUNT_KEY, id);
|
|
251
|
+
account = await readAccount(context, id);
|
|
252
|
+
}
|
|
253
|
+
const deadline = now() + POLL_LIMIT_MS;
|
|
254
|
+
while (account.kind === "found" && account.status !== "ACTIVE" && now() < deadline) {
|
|
255
|
+
if (account.clabe !== clabe)
|
|
256
|
+
return differentClabe;
|
|
257
|
+
await sleep(POLL_EVERY_MS, context.signal);
|
|
258
|
+
account = await readAccount(context, id);
|
|
259
|
+
}
|
|
260
|
+
if (account.kind === "found" && account.clabe !== clabe)
|
|
261
|
+
return differentClabe;
|
|
262
|
+
if (account.kind === "found" && account.status === "ACTIVE" && !context.recall(KEY_ID_KEY)) {
|
|
263
|
+
const keyId = (await context.ask("Copia el identificador de tu llave en el Portal de pey (API Keys, columna ID; no es la llave) y pégalo aquí.")).trim();
|
|
264
|
+
if (/^[0-9A-HJKMNP-TV-Z]{26}$/i.test(keyId))
|
|
265
|
+
context.remember(KEY_ID_KEY, keyId.toUpperCase());
|
|
266
|
+
}
|
|
267
|
+
return settle(context, id, account);
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
export const peyStep = createPeyStep();
|