Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c507da8abc | ||
|
|
4992da394b | ||
|
|
f2e0c02013 | ||
|
|
d4716382d3 | ||
|
|
12c4afa09c | ||
|
|
f0b4245676 | ||
|
|
e9e78e64c1 | ||
|
|
95cf791737 | ||
|
|
2ceea23f40 | ||
|
|
4d1804eeeb | ||
|
|
9b8b96fd02 | ||
|
|
313bb2eab4 | ||
|
|
710da06c0a | ||
|
|
9d08169092 | ||
|
|
1aa7802a61 | ||
|
|
b83722e9c5 | ||
|
|
8d543f5eb1 | ||
|
|
df791e0c28 | ||
|
|
feda1283d4 | ||
|
|
8fd0514e76 | ||
|
|
1cde29b344 | ||
|
|
8517102b63 | ||
|
|
7773bcdecf | ||
|
|
c62ad626cc | ||
|
|
8835d8ca0c | ||
|
|
997a00c284 | ||
|
|
0fb904b9ac | ||
|
|
a5ede05d96 | ||
|
|
63746eb090 | ||
|
|
2ca00d032d | ||
|
|
cb15749448 | ||
|
|
9e1adf4627 | ||
|
|
0ad74b6b70 | ||
|
|
d1d007fc7d | ||
|
|
11ac6d7949 | ||
|
|
093ae419d5 | ||
|
|
2b0d50c3d0 | ||
|
|
8126bb3d81 | ||
|
|
dedf4f0963 | ||
|
|
601378a77e |
No files matched your search
@@ -26,7 +26,23 @@ ENV CI=true \
|
|||||||
MEILISEARCH_API_KEY=build-only-meili-key \
|
MEILISEARCH_API_KEY=build-only-meili-key \
|
||||||
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
GOOGLE_CLIENT_ID=build-only-google-client-id \
|
||||||
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
GOOGLE_CLIENT_SECRET=build-only-google-client-secret \
|
||||||
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback
|
GOOGLE_CALLBACK_URL=http://localhost:9000/auth/customer/google/callback \
|
||||||
|
EPAYCO_PUBLIC_KEY=build-only-epayco-public \
|
||||||
|
EPAYCO_PRIVATE_KEY=build-only-epayco-private \
|
||||||
|
EPAYCO_P_CUST_ID_CLIENTE=build-only-epayco-pcust \
|
||||||
|
EPAYCO_P_KEY=build-only-epayco-pkey \
|
||||||
|
EPAYCO_ENV=sandbox \
|
||||||
|
EPAYCO_RESPONSE_URL=http://localhost:8000/checkout/pse/return \
|
||||||
|
EPAYCO_NOTIFY_URL=http://localhost:9000/hooks/payment/epayco_pse \
|
||||||
|
ENVIOCLICK_API_KEY=build-only-envioclick-key \
|
||||||
|
ENVIOCLICK_SANDBOX=true \
|
||||||
|
ENVIOCLICK_ORIGIN_DANE_CODE=11001000 \
|
||||||
|
ENVIOCLICK_ORIGIN_ADDRESS="Calle 1 No 1-1" \
|
||||||
|
ENVIOCLICK_ORIGIN_COMPANY="ARI Shopping" \
|
||||||
|
ENVIOCLICK_ORIGIN_FIRST_NAME=ARI \
|
||||||
|
ENVIOCLICK_ORIGIN_LAST_NAME=Shopping \
|
||||||
|
ENVIOCLICK_ORIGIN_EMAIL=[email protected] \
|
||||||
|
ENVIOCLICK_ORIGIN_PHONE=3000000000
|
||||||
|
|
||||||
COPY package.json package-lock.json .npmrc ./
|
COPY package.json package-lock.json .npmrc ./
|
||||||
|
|
||||||
|
|||||||
@@ -133,6 +133,45 @@ module.exports = defineConfig({
|
|||||||
},
|
},
|
||||||
|
|
||||||
modules: [
|
modules: [
|
||||||
|
// ADR 0009 §2 / EnvíoClick: defineConfig() ya registra por defecto
|
||||||
|
// un modulo de fulfillment con el provider manual_manual
|
||||||
|
// (confirmado leyendo @medusajs/utils/dist/common/define-config.js
|
||||||
|
// directo) -- pero como este bloque propio comparte el mismo tipo de
|
||||||
|
// modulo, transformModules() lo pisa por completo (indexa por
|
||||||
|
// serviceName, el ultimo que llega gana), no lo mezcla. Por eso
|
||||||
|
// manual_manual va explicito ACA tambien: si se omitiera, la
|
||||||
|
// shipping option existente que ya usa ese provider se rompe en
|
||||||
|
// silencio. envioclick-fulfillment implementa el mismo contrato
|
||||||
|
// (AbstractFulfillmentProviderService) contra
|
||||||
|
// developers.envioclickpro.com.co, verificado en vivo (no solo doc)
|
||||||
|
// con una llamada de prueba real que devolvio tarifas reales de
|
||||||
|
// varias transportadoras.
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/fulfillment",
|
||||||
|
options: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/fulfillment-manual",
|
||||||
|
id: "manual",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
resolve: "./src/modules/envioclick-fulfillment",
|
||||||
|
id: "standard",
|
||||||
|
options: {
|
||||||
|
apiKey: required("ENVIOCLICK_API_KEY"),
|
||||||
|
sandbox: process.env.ENVIOCLICK_SANDBOX !== "false",
|
||||||
|
originDaneCode: process.env.ENVIOCLICK_ORIGIN_DANE_CODE || "11001000",
|
||||||
|
originAddress: required("ENVIOCLICK_ORIGIN_ADDRESS"),
|
||||||
|
originCompany: process.env.ENVIOCLICK_ORIGIN_COMPANY || "ARI Shopping",
|
||||||
|
originFirstName: process.env.ENVIOCLICK_ORIGIN_FIRST_NAME || "ARI",
|
||||||
|
originLastName: process.env.ENVIOCLICK_ORIGIN_LAST_NAME || "Shopping",
|
||||||
|
originEmail: required("ENVIOCLICK_ORIGIN_EMAIL"),
|
||||||
|
originPhone: required("ENVIOCLICK_ORIGIN_PHONE"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
resolve: "@medusajs/medusa/file",
|
resolve: "@medusajs/medusa/file",
|
||||||
options: {
|
options: {
|
||||||
@@ -181,6 +220,39 @@ module.exports = defineConfig({
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
// ADR 0009: proveedor de pago -- tercera vuelta. PayU LatAm fue la
|
||||||
|
// decision original, pero Rapyd compro ese negocio en 2023 y el
|
||||||
|
// registro real del usuario quedo con credenciales de Rapyd
|
||||||
|
// (incompatibles, API completamente distinta). Se evaluo Rapyd en
|
||||||
|
// vivo y se termino descartando: comision mas alta que otras
|
||||||
|
// opciones para el volumen real del usuario. ePayco elegido en su
|
||||||
|
// lugar -- 100% de Davivienda desde 2024, comision PSE mas baja,
|
||||||
|
// tarifa preferencial con cuenta Davivienda (que el usuario ya
|
||||||
|
// tiene), sin exigir Bancolombia/Nequi como si exige Wompi. Tampoco
|
||||||
|
// existe plugin real de Medusa para ePayco, modulo custom propio.
|
||||||
|
// Alcance inicial: solo PSE, no tarjetas/otros metodos.
|
||||||
|
// provider_id resultante: "pp_epayco_pse" (identifier "epayco" + id
|
||||||
|
// "pse", convencion de Medusa).
|
||||||
|
{
|
||||||
|
resolve: "@medusajs/medusa/payment",
|
||||||
|
options: {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
resolve: "./src/modules/epayco-pse",
|
||||||
|
id: "pse",
|
||||||
|
options: {
|
||||||
|
publicKey: required("EPAYCO_PUBLIC_KEY"),
|
||||||
|
privateKey: required("EPAYCO_PRIVATE_KEY"),
|
||||||
|
pCustIdCliente: required("EPAYCO_P_CUST_ID_CLIENTE"),
|
||||||
|
pKey: required("EPAYCO_P_KEY"),
|
||||||
|
env: process.env.EPAYCO_ENV || "sandbox",
|
||||||
|
responseUrl: required("EPAYCO_RESPONSE_URL"),
|
||||||
|
notifyUrl: required("EPAYCO_NOTIFY_URL"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
|
|
||||||
// ADR 0006 Etapa 2. Sin required(): a diferencia de S3/DB, Meilisearch
|
// ADR 0006 Etapa 2. Sin required(): a diferencia de S3/DB, Meilisearch
|
||||||
|
|||||||
+213
-1
@@ -13,7 +13,8 @@
|
|||||||
"@medusajs/cli": "2.18.0",
|
"@medusajs/cli": "2.18.0",
|
||||||
"@medusajs/framework": "2.18.0",
|
"@medusajs/framework": "2.18.0",
|
||||||
"@medusajs/medusa": "2.18.0",
|
"@medusajs/medusa": "2.18.0",
|
||||||
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1"
|
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1",
|
||||||
|
"epayco-sdk-node": "^1.4.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
@@ -9200,6 +9201,15 @@
|
|||||||
"node": ">=4.0.0"
|
"node": ">=4.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/component-emitter": {
|
||||||
|
"version": "1.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz",
|
||||||
|
"integrity": "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/compressible": {
|
"node_modules/compressible": {
|
||||||
"version": "2.0.18",
|
"version": "2.0.18",
|
||||||
"resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
|
"resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
|
||||||
@@ -9363,6 +9373,12 @@
|
|||||||
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
|
"integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/cookiejar": {
|
||||||
|
"version": "2.1.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/cookiejar/-/cookiejar-2.1.4.tgz",
|
||||||
|
"integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/copy-to-clipboard": {
|
"node_modules/copy-to-clipboard": {
|
||||||
"version": "3.3.3",
|
"version": "3.3.3",
|
||||||
"resolved": "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.3.tgz",
|
"resolved": "https://registry.npmjs.org/copy-to-clipboard/-/copy-to-clipboard-3.3.3.tgz",
|
||||||
@@ -9372,6 +9388,12 @@
|
|||||||
"toggle-selection": "^1.0.6"
|
"toggle-selection": "^1.0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/core-util-is": {
|
||||||
|
"version": "1.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
|
||||||
|
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/cors": {
|
"node_modules/cors": {
|
||||||
"version": "2.8.6",
|
"version": "2.8.6",
|
||||||
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
|
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
|
||||||
@@ -9434,6 +9456,13 @@
|
|||||||
"node": ">= 8"
|
"node": ">= 8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/crypto-js": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
|
||||||
|
"deprecated": "Active development of CryptoJS has been discontinued. This library is no longer maintained.",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/crypto-random-string": {
|
"node_modules/crypto-random-string": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/crypto-random-string/-/crypto-random-string-2.0.0.tgz",
|
||||||
@@ -9806,6 +9835,35 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/epayco-sdk-node": {
|
||||||
|
"version": "1.4.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/epayco-sdk-node/-/epayco-sdk-node-1.4.4.tgz",
|
||||||
|
"integrity": "sha512-i6SpQru6Hwp096yxAVaD4lsV76ASB0cqAbJsvXQoc0leCsePHRjetV/9C1AASw8ZFbnkmTajw9DhWsAvjdTEFw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"axios": "^1.8.2",
|
||||||
|
"crypto-js": "^4.2.0",
|
||||||
|
"debug": "2.6.9",
|
||||||
|
"dotenv": "^16.3.1",
|
||||||
|
"node-fetch": "^2.6.0",
|
||||||
|
"superagent": "^3.7.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/epayco-sdk-node/node_modules/debug": {
|
||||||
|
"version": "2.6.9",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
|
||||||
|
"integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ms": "2.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/epayco-sdk-node/node_modules/ms": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/es-define-property": {
|
"node_modules/es-define-property": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
|
||||||
@@ -10099,6 +10157,12 @@
|
|||||||
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
|
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/extend": {
|
||||||
|
"version": "3.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",
|
||||||
|
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/fast-deep-equal": {
|
"node_modules/fast-deep-equal": {
|
||||||
"version": "3.1.3",
|
"version": "3.1.3",
|
||||||
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
|
||||||
@@ -10292,6 +10356,16 @@
|
|||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/formidable": {
|
||||||
|
"version": "1.2.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/formidable/-/formidable-1.2.6.tgz",
|
||||||
|
"integrity": "sha512-KcpbcpuLNOwrEjnbpMC0gS+X8ciDoZE1kkqzat4a8vrprf+s9pKNQ/QIwWfbfs4ltgmFl3MD177SNTkve3BwGQ==",
|
||||||
|
"deprecated": "Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://ko-fi.com/tunnckoCore/commissions"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/forwarded": {
|
"node_modules/forwarded": {
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
|
||||||
@@ -11207,6 +11281,12 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/isarray": {
|
||||||
|
"version": "1.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
|
||||||
|
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/isexe": {
|
"node_modules/isexe": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
|
||||||
@@ -12164,6 +12244,26 @@
|
|||||||
"node": ">= 8.0.0"
|
"node": ">= 8.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/node-fetch": {
|
||||||
|
"version": "2.7.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||||
|
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"whatwg-url": "^5.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "4.x || >=6.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"encoding": "^0.1.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"encoding": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/node-gyp-build-optional-packages": {
|
"node_modules/node-gyp-build-optional-packages": {
|
||||||
"version": "5.2.2",
|
"version": "5.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
|
||||||
@@ -12924,6 +13024,12 @@
|
|||||||
"node": ">=6"
|
"node": ">=6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/process-nextick-args": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/prompts": {
|
"node_modules/prompts": {
|
||||||
"version": "2.4.2",
|
"version": "2.4.2",
|
||||||
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
|
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
|
||||||
@@ -14354,6 +14460,90 @@
|
|||||||
"node": ">= 6"
|
"node": ">= 6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/superagent": {
|
||||||
|
"version": "3.8.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/superagent/-/superagent-3.8.3.tgz",
|
||||||
|
"integrity": "sha512-GLQtLMCoEIK4eDv6OGtkOoSMt3D+oq0y3dsxMuYuDvaNUvuT8eFBuLmfR0iYYzHC1e8hpzC6ZsxbuP6DIalMFA==",
|
||||||
|
"deprecated": "Please upgrade to superagent v10.2.2+, see release notes at https://github.com/forwardemail/superagent/releases/tag/v10.2.2 - maintenance is supported by Forward Email @ https://forwardemail.net",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"component-emitter": "^1.2.0",
|
||||||
|
"cookiejar": "^2.1.0",
|
||||||
|
"debug": "^3.1.0",
|
||||||
|
"extend": "^3.0.0",
|
||||||
|
"form-data": "^2.3.1",
|
||||||
|
"formidable": "^1.2.0",
|
||||||
|
"methods": "^1.1.1",
|
||||||
|
"mime": "^1.4.1",
|
||||||
|
"qs": "^6.5.1",
|
||||||
|
"readable-stream": "^2.3.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/debug": {
|
||||||
|
"version": "3.2.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
|
||||||
|
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"ms": "^2.1.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/form-data": {
|
||||||
|
"version": "2.5.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.5.6.tgz",
|
||||||
|
"integrity": "sha512-Ogz/E85h9tlfJzpI6TuFpGcHZFhLrb9Gw8wq9v40CxSCPnv7ahKr6Xgtkn0KYCDQJ8DNn5VoMO8EXr9V5PadyA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"asynckit": "^0.4.0",
|
||||||
|
"combined-stream": "^1.0.8",
|
||||||
|
"es-set-tostringtag": "^2.1.0",
|
||||||
|
"hasown": "^2.0.4",
|
||||||
|
"mime-types": "^2.1.35",
|
||||||
|
"safe-buffer": "^5.2.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 0.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/readable-stream": {
|
||||||
|
"version": "2.3.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
|
||||||
|
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"core-util-is": "~1.0.0",
|
||||||
|
"inherits": "~2.0.3",
|
||||||
|
"isarray": "~1.0.0",
|
||||||
|
"process-nextick-args": "~2.0.0",
|
||||||
|
"safe-buffer": "~5.1.1",
|
||||||
|
"string_decoder": "~1.1.1",
|
||||||
|
"util-deprecate": "~1.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/readable-stream/node_modules/safe-buffer": {
|
||||||
|
"version": "5.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/string_decoder": {
|
||||||
|
"version": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"safe-buffer": "~5.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/superagent/node_modules/string_decoder/node_modules/safe-buffer": {
|
||||||
|
"version": "5.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||||
|
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/supports-color": {
|
"node_modules/supports-color": {
|
||||||
"version": "7.2.0",
|
"version": "7.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
|
||||||
@@ -14635,6 +14825,12 @@
|
|||||||
"node": ">=0.6"
|
"node": ">=0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/tr46": {
|
||||||
|
"version": "0.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||||
|
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/triple-beam": {
|
"node_modules/triple-beam": {
|
||||||
"version": "1.4.1",
|
"version": "1.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
|
||||||
@@ -15099,6 +15295,22 @@
|
|||||||
"defaults": "^1.0.3"
|
"defaults": "^1.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/webidl-conversions": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
|
||||||
|
"license": "BSD-2-Clause"
|
||||||
|
},
|
||||||
|
"node_modules/whatwg-url": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tr46": "~0.0.3",
|
||||||
|
"webidl-conversions": "^3.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/which": {
|
"node_modules/which": {
|
||||||
"version": "2.0.2",
|
"version": "2.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||||
|
|||||||
@@ -15,7 +15,8 @@
|
|||||||
"@medusajs/cli": "2.18.0",
|
"@medusajs/cli": "2.18.0",
|
||||||
"@medusajs/framework": "2.18.0",
|
"@medusajs/framework": "2.18.0",
|
||||||
"@medusajs/medusa": "2.18.0",
|
"@medusajs/medusa": "2.18.0",
|
||||||
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1"
|
"@rokmohar/medusa-plugin-meilisearch": "^1.4.1",
|
||||||
|
"epayco-sdk-node": "^1.4.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@swc/core": "^1.7.28",
|
"@swc/core": "^1.7.28",
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ type RowResult = {
|
|||||||
row: number;
|
row: number;
|
||||||
title: string;
|
title: string;
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
|
action?: "created" | "updated";
|
||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -91,9 +92,11 @@ const ProductImportPanel = () => {
|
|||||||
<div className="px-6 py-4">
|
<div className="px-6 py-4">
|
||||||
<Text size="small" className="text-ui-fg-subtle">
|
<Text size="small" className="text-ui-fg-subtle">
|
||||||
Columnas: <code>titulo, descripcion, precio, categoria, coleccion, cantidad, fotos</code>. Varias fotos se
|
Columnas: <code>titulo, descripcion, precio, categoria, coleccion, cantidad, fotos</code>. Varias fotos se
|
||||||
separan con <code>;</code> dentro de la misma celda. <code>categoria</code>/<code>coleccion</code> deben
|
separan con <code>;</code> dentro de la misma celda. Si <code>categoria</code>/<code>coleccion</code> no
|
||||||
escribirse igual que en la tienda o se dejan vacías. Cada foto se descarga y se guarda en el almacenamiento
|
coinciden con una ya existente, se crean nuevas. Si <code>titulo</code> coincide con un producto ya
|
||||||
propio de la tienda (no queda enlazada al sitio de origen).
|
importado, no se duplica: se le agregan las fotos nuevas y se actualiza la descripción si la fila trae una.
|
||||||
|
Cada foto se descarga y se guarda en el almacenamiento propio de la tienda (no queda enlazada al sitio de
|
||||||
|
origen).
|
||||||
</Text>
|
</Text>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -122,7 +125,7 @@ const ProductImportPanel = () => {
|
|||||||
<td className="py-2">{result.title}</td>
|
<td className="py-2">{result.title}</td>
|
||||||
<td className="py-2">
|
<td className="py-2">
|
||||||
{result.ok ? (
|
{result.ok ? (
|
||||||
<Badge color="green">Importado</Badge>
|
<Badge color="green">{result.action === "updated" ? "Actualizado (ya existía)" : "Importado"}</Badge>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-rose-600">{result.error}</span>
|
<span className="text-rose-600">{result.error}</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -7,8 +7,11 @@ import type {
|
|||||||
IStockLocationService,
|
IStockLocationService,
|
||||||
} from "@medusajs/framework/types";
|
} from "@medusajs/framework/types";
|
||||||
import {
|
import {
|
||||||
|
createCollectionsWorkflow,
|
||||||
createInventoryItemsWorkflow,
|
createInventoryItemsWorkflow,
|
||||||
|
createProductCategoriesWorkflow,
|
||||||
createProductsWorkflow,
|
createProductsWorkflow,
|
||||||
|
updateProductsWorkflow,
|
||||||
uploadFilesWorkflow,
|
uploadFilesWorkflow,
|
||||||
} from "@medusajs/medusa/core-flows";
|
} from "@medusajs/medusa/core-flows";
|
||||||
import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
||||||
@@ -20,11 +23,37 @@ import { csvRowsToObjects, parseCsv } from "../../../lib/csv";
|
|||||||
// fila se procesa independiente (una foto rota o categoria mal escrita
|
// fila se procesa independiente (una foto rota o categoria mal escrita
|
||||||
// no tumba el resto del archivo).
|
// no tumba el resto del archivo).
|
||||||
//
|
//
|
||||||
|
// categoria/coleccion: si el nombre no matchea una categoria/coleccion
|
||||||
|
// ya existente (case-insensitive), se crea nueva -- antes se descartaba
|
||||||
|
// en silencio y el producto quedaba sin categoria/coleccion sin avisar
|
||||||
|
// (confirmado en vivo: "Hello Kitty & Friends" nunca se creo como
|
||||||
|
// coleccion). El handle de la nueva categoria/coleccion se genera con
|
||||||
|
// el mismo slugify() ASCII-safe de mas abajo, por la misma razon que el
|
||||||
|
// handle del producto: el default de Medusa no quita tildes/enies y
|
||||||
|
// rompe la ruta publica.
|
||||||
|
//
|
||||||
|
// Re-importar el mismo titulo (ej. para agregar mas fotos o actualizar
|
||||||
|
// la descripcion de un producto ya cargado) actualiza el producto
|
||||||
|
// existente en vez de crear uno nuevo -- antes cada re-importacion
|
||||||
|
// generaba un producto duplicado con handle distinto (confirmado en
|
||||||
|
// vivo con "Hello Kitty & Friends": misma fila re-subida para sumar
|
||||||
|
// fotos, dos productos con el mismo titulo en la tienda). El match es
|
||||||
|
// por titulo exacto (case-insensitive/trim), igual que categoria y
|
||||||
|
// coleccion; en un match, las fotos nuevas se agregan a las que ya
|
||||||
|
// tenia (no se reemplazan) y la descripcion se actualiza si la fila
|
||||||
|
// trae una. No toca precio/cantidad/categoria/coleccion del producto
|
||||||
|
// existente -- eso se edita a mano en el admin si hace falta.
|
||||||
|
//
|
||||||
// Las fotos se descargan del origen y se re-alojan en el mismo
|
// Las fotos se descargan del origen y se re-alojan en el mismo
|
||||||
// MinIO/S3 que ya usa el resto del catalogo (uploadFilesWorkflow ->
|
// MinIO/S3 que ya usa el resto del catalogo (uploadFilesWorkflow ->
|
||||||
// mismo File Module Provider de medusa-config.ts, ya corre en el NAS),
|
// mismo File Module Provider de medusa-config.ts, ya corre en el NAS).
|
||||||
// bajo el prefijo import-products/ para separarlas de ari-products/
|
// El bucket (S3_BUCKET=ari-products) es plano -- el provider de S3 de
|
||||||
// (subidas manuales desde el Admin).
|
// Medusa descarta cualquier subcarpeta del filename (usa solo
|
||||||
|
// path.parse().name + ulid, confirmado leyendo
|
||||||
|
// @medusajs/file-s3/dist/services/s3-file.js), asi que no hay una
|
||||||
|
// carpeta separada real para lo importado -- queda mezclado con el
|
||||||
|
// resto de fotos del catalogo, mismo criterio de nombres unicos por
|
||||||
|
// ulid que ya usa todo el sitio.
|
||||||
|
|
||||||
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
||||||
const IMAGE_FETCH_TIMEOUT_MS = 15000;
|
const IMAGE_FETCH_TIMEOUT_MS = 15000;
|
||||||
@@ -45,9 +74,32 @@ type RowResult = {
|
|||||||
row: number;
|
row: number;
|
||||||
title: string;
|
title: string;
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
|
action?: "created" | "updated";
|
||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Medusa genera el handle por defecto solo en minusculas + espacios a
|
||||||
|
// guiones, sin quitar tildes/enies -- confirmado en vivo: 3 productos
|
||||||
|
// importados con titulo acentuado (ej. "niñas", "Lógicos") quedaron con
|
||||||
|
// handle como "...niñas..." y daban 404 real al entrar por
|
||||||
|
// shop.cruzcloud.net (el tunel/ingress publico rompe rutas con UTF-8
|
||||||
|
// no-ASCII en el path, aunque el mismo request funciona perfecto pegandole
|
||||||
|
// directo al servicio dentro del cluster). Se genera el handle nosotros
|
||||||
|
// mismos, ASCII-only, en vez de dejarselo al default de Medusa. El sufijo
|
||||||
|
// corto evita colisiones entre titulos parecidos/repetidos sin necesidad
|
||||||
|
// de revisar unicidad antes de crear.
|
||||||
|
function slugify(title: string, uniquePart: string): string {
|
||||||
|
const base = title
|
||||||
|
.normalize("NFD")
|
||||||
|
.replace(/[̀-ͯ]/g, "")
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9]+/g, "-")
|
||||||
|
.replace(/^-+|-+$/g, "")
|
||||||
|
.slice(0, 80)
|
||||||
|
.replace(/-+$/g, "");
|
||||||
|
return `${base || "producto"}-${uniquePart}`;
|
||||||
|
}
|
||||||
|
|
||||||
function extensionFromContentType(contentType: string | null, url: string): string {
|
function extensionFromContentType(contentType: string | null, url: string): string {
|
||||||
if (contentType?.includes("png")) return "png";
|
if (contentType?.includes("png")) return "png";
|
||||||
if (contentType?.includes("webp")) return "webp";
|
if (contentType?.includes("webp")) return "webp";
|
||||||
@@ -112,12 +164,18 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
const salesChannelService = req.scope.resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL);
|
const salesChannelService = req.scope.resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL);
|
||||||
const productService = req.scope.resolve<IProductModuleService>(Modules.PRODUCT);
|
const productService = req.scope.resolve<IProductModuleService>(Modules.PRODUCT);
|
||||||
|
|
||||||
const [locations, shippingProfiles, salesChannels, categories, collections] = await Promise.all([
|
const [locations, shippingProfiles, salesChannels, categories, collections, existingProducts] = await Promise.all([
|
||||||
stockLocationService.listStockLocations({}),
|
stockLocationService.listStockLocations({}),
|
||||||
fulfillmentService.listShippingProfiles({}),
|
fulfillmentService.listShippingProfiles({}),
|
||||||
salesChannelService.listSalesChannels({}),
|
salesChannelService.listSalesChannels({}),
|
||||||
productService.listProductCategories({}),
|
// select explicito -- sin el, name/title llegaban undefined (el
|
||||||
productService.listProductCollections({}),
|
// default de estos module services no siempre trae todos los
|
||||||
|
// escalares, a diferencia de la capa HTTP del Admin API, confirmado
|
||||||
|
// en vivo: la ruta /admin/product-categories con fields=id,name si
|
||||||
|
// los trae completos).
|
||||||
|
productService.listProductCategories({}, { select: ["id", "name"] }),
|
||||||
|
productService.listProductCollections({}, { select: ["id", "title"] }),
|
||||||
|
productService.listProducts({}, { select: ["id", "title"], relations: ["images"] }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const locationId = locations[0]?.id;
|
const locationId = locations[0]?.id;
|
||||||
@@ -131,8 +189,15 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const categoryByName = new Map(categories.map((c) => [c.name.toLowerCase().trim(), c.id]));
|
const categoryByName = new Map(
|
||||||
const collectionByName = new Map(collections.map((c) => [c.title.toLowerCase().trim(), c.id]));
|
categories.filter((c) => c.name).map((c) => [c.name.toLowerCase().trim(), c.id]),
|
||||||
|
);
|
||||||
|
const collectionByName = new Map(
|
||||||
|
collections.filter((c) => c.title).map((c) => [c.title.toLowerCase().trim(), c.id]),
|
||||||
|
);
|
||||||
|
const productByTitle = new Map(
|
||||||
|
existingProducts.filter((p) => p.title).map((p) => [p.title.toLowerCase().trim(), p]),
|
||||||
|
);
|
||||||
|
|
||||||
const results: RowResult[] = [];
|
const results: RowResult[] = [];
|
||||||
|
|
||||||
@@ -155,7 +220,7 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
const { result: uploadedFiles } = await uploadFilesWorkflow(req.scope).run({
|
const { result: uploadedFiles } = await uploadFilesWorkflow(req.scope).run({
|
||||||
input: {
|
input: {
|
||||||
files: downloaded.map((file, i) => ({
|
files: downloaded.map((file, i) => ({
|
||||||
filename: `import-products/${Date.now()}-${index}-${i}.${file.extension}`,
|
filename: `${Date.now()}-${index}-${i}.${file.extension}`,
|
||||||
mimeType: file.mimeType,
|
mimeType: file.mimeType,
|
||||||
content: file.content,
|
content: file.content,
|
||||||
access: "public" as const,
|
access: "public" as const,
|
||||||
@@ -163,6 +228,23 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const existingProduct = productByTitle.get(title.toLowerCase());
|
||||||
|
if (existingProduct) {
|
||||||
|
await updateProductsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
products: [
|
||||||
|
{
|
||||||
|
id: existingProduct.id,
|
||||||
|
description: row.descripcion?.trim() || undefined,
|
||||||
|
images: [...(existingProduct.images ?? []).map((image) => ({ url: image.url })), ...uploadedFiles.map((f) => ({ url: f.url }))],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
results.push({ row: rowNumber, title, ok: true, action: "updated" });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
const quantity = Number(row.cantidad);
|
const quantity = Number(row.cantidad);
|
||||||
const { result: inventoryItems } = await createInventoryItemsWorkflow(req.scope).run({
|
const { result: inventoryItems } = await createInventoryItemsWorkflow(req.scope).run({
|
||||||
input: {
|
input: {
|
||||||
@@ -179,14 +261,40 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
const inventoryItemId = inventoryItems[0]?.id;
|
const inventoryItemId = inventoryItems[0]?.id;
|
||||||
if (!inventoryItemId) throw new Error("No se pudo crear el registro de inventario");
|
if (!inventoryItemId) throw new Error("No se pudo crear el registro de inventario");
|
||||||
|
|
||||||
const categoryId = row.categoria ? categoryByName.get(row.categoria.toLowerCase().trim()) : undefined;
|
const categoryName = row.categoria?.trim();
|
||||||
const collectionId = row.coleccion ? collectionByName.get(row.coleccion.toLowerCase().trim()) : undefined;
|
let categoryId = categoryName ? categoryByName.get(categoryName.toLowerCase()) : undefined;
|
||||||
|
if (categoryName && !categoryId) {
|
||||||
|
const { result: createdCategories } = await createProductCategoriesWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
product_categories: [
|
||||||
|
{ name: categoryName, handle: slugify(categoryName, `${Date.now().toString(36)}${index}`) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
categoryId = createdCategories[0].id;
|
||||||
|
categoryByName.set(categoryName.toLowerCase(), categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const collectionName = row.coleccion?.trim();
|
||||||
|
let collectionId = collectionName ? collectionByName.get(collectionName.toLowerCase()) : undefined;
|
||||||
|
if (collectionName && !collectionId) {
|
||||||
|
const { result: createdCollections } = await createCollectionsWorkflow(req.scope).run({
|
||||||
|
input: {
|
||||||
|
collections: [
|
||||||
|
{ title: collectionName, handle: slugify(collectionName, `${Date.now().toString(36)}${index}`) },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
collectionId = createdCollections[0].id;
|
||||||
|
collectionByName.set(collectionName.toLowerCase(), collectionId);
|
||||||
|
}
|
||||||
|
|
||||||
await createProductsWorkflow(req.scope).run({
|
await createProductsWorkflow(req.scope).run({
|
||||||
input: {
|
input: {
|
||||||
products: [
|
products: [
|
||||||
{
|
{
|
||||||
title,
|
title,
|
||||||
|
handle: slugify(title, `${Date.now().toString(36)}${index}`),
|
||||||
description: row.descripcion || undefined,
|
description: row.descripcion || undefined,
|
||||||
status: "published",
|
status: "published",
|
||||||
thumbnail: uploadedFiles[0]?.url,
|
thumbnail: uploadedFiles[0]?.url,
|
||||||
@@ -210,7 +318,7 @@ export async function POST(req: MedusaRequest<{ csv: string }>, res: MedusaRespo
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
results.push({ row: rowNumber, title, ok: true });
|
results.push({ row: rowNumber, title, ok: true, action: "created" });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.push({ row: rowNumber, title: title || `Fila ${rowNumber}`, ok: false, error: (error as Error).message });
|
results.push({ row: rowNumber, title: title || `Fila ${rowNumber}`, ok: false, error: (error as Error).message });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework";
|
||||||
|
import { createEpaycoClient, type EpaycoEnv } from "../../../../lib/epayco";
|
||||||
|
|
||||||
|
// Lista de bancos PSE -- no hay forma de pedirle esto al modulo de pago
|
||||||
|
// custom directamente (AbstractPaymentProvider no expone sus metodos
|
||||||
|
// internos fuera del contrato de pago), asi que esta ruta llama a
|
||||||
|
// ePayco con las mismas credenciales de medusa-config.ts. Cache en
|
||||||
|
// memoria (sin Redis/cron), mismo criterio de simplicidad que ya usa la
|
||||||
|
// seccion de Meilisearch en medusa-config.ts.
|
||||||
|
//
|
||||||
|
// El shape exacto de la respuesta de bank.getBanks() no quedo verificado
|
||||||
|
// contra el sandbox real en esta sesion -- se prueban los nombres de
|
||||||
|
// campo mas probables (bankCode/bankName y variantes) y se degrada a
|
||||||
|
// lista vacia si no matchea nada, en vez de romper el checkout entero.
|
||||||
|
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
||||||
|
let cache: { banks: Array<{ pseCode: string; description: string }>; fetchedAt: number } | null = null;
|
||||||
|
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
if (cache && Date.now() - cache.fetchedAt < CACHE_TTL_MS) {
|
||||||
|
res.json({ banks: cache.banks });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const client = createEpaycoClient({
|
||||||
|
publicKey: process.env.EPAYCO_PUBLIC_KEY ?? "",
|
||||||
|
privateKey: process.env.EPAYCO_PRIVATE_KEY ?? "",
|
||||||
|
pCustIdCliente: process.env.EPAYCO_P_CUST_ID_CLIENTE ?? "",
|
||||||
|
pKey: process.env.EPAYCO_P_KEY ?? "",
|
||||||
|
env: (process.env.EPAYCO_ENV as EpaycoEnv) || "sandbox",
|
||||||
|
});
|
||||||
|
const response = await client.bank.getBanks();
|
||||||
|
const rawBanks = (response.data ?? response.banks ?? response) as unknown;
|
||||||
|
const list = Array.isArray(rawBanks) ? rawBanks : [];
|
||||||
|
|
||||||
|
const banks = list
|
||||||
|
.map((bank) => {
|
||||||
|
const record = bank as Record<string, unknown>;
|
||||||
|
const pseCode = record.bankCode ?? record.bank_code ?? record.codigo ?? record.id;
|
||||||
|
const description = record.bankName ?? record.bank_name ?? record.nombre ?? record.name ?? record.description;
|
||||||
|
return typeof pseCode === "string" || typeof pseCode === "number"
|
||||||
|
? { pseCode: String(pseCode), description: String(description ?? pseCode) }
|
||||||
|
: null;
|
||||||
|
})
|
||||||
|
.filter((bank): bank is { pseCode: string; description: string } => bank !== null);
|
||||||
|
|
||||||
|
cache = { banks, fetchedAt: Date.now() };
|
||||||
|
res.json({ banks });
|
||||||
|
} catch (error) {
|
||||||
|
res.json({ banks: cache?.banks ?? [], error: (error as Error).message });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
// EnvíoClick (ADR 0009 §2, ya anticipado desde el modelo de direcciones
|
||||||
|
// del checkout): cotización y generación de guía real por peso/volumen,
|
||||||
|
// reemplazando la tarifa fija de $15.000 COP. Contrato REST confirmado en
|
||||||
|
// vivo contra la cuenta real del usuario (apiDoc real,
|
||||||
|
// apidoc.envioclickpro.com.co/api_data.json -- la SPA de la doc no
|
||||||
|
// renderiza sin JS, pero ese archivo generado por apidoc trae la spec
|
||||||
|
// completa) y una llamada de prueba real que devolvió 200 con tarifas
|
||||||
|
// reales de PIBOX/COORDINADORA/ENVIA/RAPPI/TCC.
|
||||||
|
|
||||||
|
const BASE_URL = "https://api.envioclickpro.com.co/api/v2";
|
||||||
|
|
||||||
|
export interface EnvioClickCredentials {
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnvioClickPackage {
|
||||||
|
weight: number;
|
||||||
|
height: number;
|
||||||
|
length: number;
|
||||||
|
// "widht" es un typo real de la API (confirmado en el body de
|
||||||
|
// /shipment de la doc oficial), no un error nuestro -- solo se usa acá,
|
||||||
|
// en el request de /quotation el campo si se llama "width" (confirmado
|
||||||
|
// tambien contra la doc real, son dos endpoints con esa inconsistencia).
|
||||||
|
width: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnvioClickRate {
|
||||||
|
idRate: number;
|
||||||
|
idProduct: number;
|
||||||
|
product: string;
|
||||||
|
idCarrier: number;
|
||||||
|
carrier: string;
|
||||||
|
flete: number;
|
||||||
|
minimumInsurance: number;
|
||||||
|
extraInsurance: number;
|
||||||
|
deliveryDays: number;
|
||||||
|
cod: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnvioClickAddress {
|
||||||
|
daneCode: string;
|
||||||
|
address: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function envioclickRequest(
|
||||||
|
credentials: EnvioClickCredentials,
|
||||||
|
path: string,
|
||||||
|
body: Record<string, unknown>,
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
const response = await fetch(`${BASE_URL}${path}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
// Header real confirmado contra la doc oficial y una llamada en
|
||||||
|
// vivo -- "Authorization" a secas (sin "Bearer"), NO
|
||||||
|
// "AuthorizationKey" como usaba el plugin de WordPress de
|
||||||
|
// referencia (ese era para la API v1, desactualizada).
|
||||||
|
Authorization: credentials.apiKey,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
let json: Record<string, unknown>;
|
||||||
|
try {
|
||||||
|
json = JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
throw new Error(`Respuesta no-JSON de EnvíoClick (HTTP ${response.status}): ${text.slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
if (json.status !== "OK") {
|
||||||
|
throw new Error(`EnvíoClick respondió con error: ${JSON.stringify(json).slice(0, 400)}`);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo 1 paquete por cotizacion (limite real documentado y confirmado:
|
||||||
|
// "min 1, max 1" -- cada vez menos transportadoras ofrecen multi-paquete).
|
||||||
|
export async function quoteShipment(
|
||||||
|
credentials: EnvioClickCredentials,
|
||||||
|
params: {
|
||||||
|
pkg: EnvioClickPackage;
|
||||||
|
description: string;
|
||||||
|
contentValue: number;
|
||||||
|
origin: EnvioClickAddress;
|
||||||
|
destination: EnvioClickAddress;
|
||||||
|
},
|
||||||
|
): Promise<EnvioClickRate[]> {
|
||||||
|
const json = await envioclickRequest(credentials, "/quotation", {
|
||||||
|
packages: [params.pkg],
|
||||||
|
description: params.description,
|
||||||
|
contentValue: params.contentValue,
|
||||||
|
origin: params.origin,
|
||||||
|
destination: params.destination,
|
||||||
|
});
|
||||||
|
const data = json.data as Record<string, unknown>;
|
||||||
|
return (data.rates as EnvioClickRate[]) ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EnvioClickPerson {
|
||||||
|
company: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
address: string;
|
||||||
|
suburb: string;
|
||||||
|
crossStreet: string;
|
||||||
|
reference: string;
|
||||||
|
daneCode: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateGuideResult {
|
||||||
|
guide: string;
|
||||||
|
url: string;
|
||||||
|
tracker: string;
|
||||||
|
idOrder: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createGuide(
|
||||||
|
credentials: EnvioClickCredentials,
|
||||||
|
sandbox: boolean,
|
||||||
|
params: {
|
||||||
|
idRate: number;
|
||||||
|
myShipmentReference: string;
|
||||||
|
externalOrderId: string;
|
||||||
|
pkg: EnvioClickPackage;
|
||||||
|
description: string;
|
||||||
|
contentValue: number;
|
||||||
|
origin: EnvioClickPerson;
|
||||||
|
destination: EnvioClickPerson;
|
||||||
|
},
|
||||||
|
): Promise<CreateGuideResult> {
|
||||||
|
// /shipment_sandbox es el UNICO endpoint con modo de pruebas real (la
|
||||||
|
// cotizacion siempre usa tarifas reales de las transportadoras, no
|
||||||
|
// tiene sandbox) -- confirmado en la doc oficial ("Deberás cambiar a
|
||||||
|
// la URL de producción para que puedas generar guías reales").
|
||||||
|
const path = sandbox ? "/shipment_sandbox" : "/shipment";
|
||||||
|
const json = await envioclickRequest(credentials, path, {
|
||||||
|
idRate: params.idRate,
|
||||||
|
myShipmentReference: params.myShipmentReference,
|
||||||
|
external_order_id: params.externalOrderId,
|
||||||
|
requestPickup: false,
|
||||||
|
pickupDate: new Date().toISOString().slice(0, 10),
|
||||||
|
insurance: false,
|
||||||
|
description: params.description,
|
||||||
|
contentValue: params.contentValue,
|
||||||
|
packages: [
|
||||||
|
{
|
||||||
|
weight: params.pkg.weight,
|
||||||
|
height: params.pkg.height,
|
||||||
|
length: params.pkg.length,
|
||||||
|
widht: params.pkg.width,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
origin: params.origin,
|
||||||
|
destination: params.destination,
|
||||||
|
});
|
||||||
|
const data = json.data as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
guide: String(data.guide ?? ""),
|
||||||
|
url: String(data.url ?? ""),
|
||||||
|
tracker: String(data.tracker ?? ""),
|
||||||
|
idOrder: Number(data.idOrder ?? 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hasta 50 ordenes por llamada (limite real documentado).
|
||||||
|
export async function cancelGuides(credentials: EnvioClickCredentials, idOrders: number[]): Promise<void> {
|
||||||
|
await envioclickRequest(credentials, "cancellation/batch/order", { idOrders });
|
||||||
|
}
|
||||||
|
|
||||||
|
// código DANE estandar (5 digitos: 2 de departamento + 3 de municipio,
|
||||||
|
// ej. 11001 = Bogota, 5001 = Medellin -- mismo id que ya usa
|
||||||
|
// lib/data/colombia.ts del storefront, confirmado contra su propio
|
||||||
|
// comentario) con el padding real que espera EnvioClick (8 caracteres,
|
||||||
|
// confirmado contra su propio ejemplo real: "11001000" para Bogota =
|
||||||
|
// "11001" + "000").
|
||||||
|
export function toEnvioClickDaneCode(divipolaCityId: number): string {
|
||||||
|
return `${String(divipolaCityId).padStart(5, "0")}000`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
// ePayco (100% de Davivienda desde 2024, ver ADR 0009 -- tercer proveedor
|
||||||
|
// evaluado tras PayU LatAm/Rapyd, elegido por comision PSE mas baja para
|
||||||
|
// bajo volumen y tarifa preferencial con cuenta Davivienda, que el
|
||||||
|
// usuario ya tiene). A diferencia de PayU/Rapyd, no llamamos la API REST
|
||||||
|
// cruda nosotros: usamos el SDK oficial `epayco-sdk-node` (mantenido por
|
||||||
|
// github.com/epayco, ultimo publish reciente) porque su protocolo real
|
||||||
|
// -- leido del codigo fuente, no de la doc -- es bastante mas raro de lo
|
||||||
|
// que parece en los ejemplos: cada campo del payload se cifra con
|
||||||
|
// AES-CBC usando la private key como llave (IV fijo en cero) ANTES de
|
||||||
|
// mandarse a secure.payco.co, ademas de un login previo a
|
||||||
|
// api.secure.payco.co/v1/auth/login que da un bearer token que tambien
|
||||||
|
// va en la request. Reimplementar esto a mano tiene mucho mas riesgo de
|
||||||
|
// error que delegarlo al SDK del propio proveedor.
|
||||||
|
export type EpaycoEnv = "sandbox" | "production";
|
||||||
|
|
||||||
|
export interface EpaycoCredentials {
|
||||||
|
publicKey: string;
|
||||||
|
privateKey: string;
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
env: EpaycoEnv;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sin tipos de TypeScript en el paquete (confirmado: package.json no
|
||||||
|
// declara "types") -- se tipa manualmente el subset que usamos.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const EpaycoSdk = require("epayco-sdk-node");
|
||||||
|
|
||||||
|
export interface EpaycoClient {
|
||||||
|
bank: {
|
||||||
|
create(options: Record<string, unknown>): Promise<Record<string, unknown>>;
|
||||||
|
get(transactionId: string): Promise<Record<string, unknown>>;
|
||||||
|
getBanks(): Promise<Record<string, unknown>>;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createEpaycoClient(credentials: EpaycoCredentials): EpaycoClient {
|
||||||
|
return EpaycoSdk({
|
||||||
|
apiKey: credentials.publicKey,
|
||||||
|
privateKey: credentials.privateKey,
|
||||||
|
lang: "ES",
|
||||||
|
test: credentials.env === "sandbox",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Firma del webhook de confirmacion (url_confirmation) -- formula
|
||||||
|
// verificada contra la documentacion real de ePayco:
|
||||||
|
// sha256(p_cust_id_cliente^p_key^x_ref_payco^x_transaction_id^x_amount^x_currency_code).
|
||||||
|
// p_cust_id_cliente/p_key son valores propios del dashboard de ePayco
|
||||||
|
// (Configuracion > Llaves secretas), distintos de publicKey/privateKey
|
||||||
|
// -- confirmar contra el dashboard real antes de la primera prueba.
|
||||||
|
// Falla cerrado: cualquier mismatch devuelve false, nunca se traga la
|
||||||
|
// excepcion.
|
||||||
|
export function verifyWebhookSignature(params: {
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
refPayco: string;
|
||||||
|
transactionId: string;
|
||||||
|
amount: string;
|
||||||
|
currencyCode: string;
|
||||||
|
signature: string;
|
||||||
|
}): boolean {
|
||||||
|
const raw = `${params.pCustIdCliente}^${params.pKey}^${params.refPayco}^${params.transactionId}^${params.amount}^${params.currencyCode}`;
|
||||||
|
const expected = createHash("sha256").update(raw).digest("hex");
|
||||||
|
return expected.toLowerCase() === params.signature.toLowerCase();
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||||
|
import EnvioClickFulfillmentService from "./service";
|
||||||
|
|
||||||
|
export default ModuleProvider(Modules.FULFILLMENT, {
|
||||||
|
services: [EnvioClickFulfillmentService],
|
||||||
|
});
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils";
|
||||||
|
import type {
|
||||||
|
CalculatedShippingOptionPrice,
|
||||||
|
CalculateShippingOptionPriceContext,
|
||||||
|
CalculateShippingOptionPriceDTO,
|
||||||
|
CreateFulfillmentResult,
|
||||||
|
CreateShippingOptionDTO,
|
||||||
|
FulfillmentDTO,
|
||||||
|
FulfillmentItemDTO,
|
||||||
|
FulfillmentOption,
|
||||||
|
FulfillmentOrderDTO,
|
||||||
|
Logger,
|
||||||
|
ValidateFulfillmentDataContext,
|
||||||
|
} from "@medusajs/framework/types";
|
||||||
|
import { cancelGuides, createGuide, quoteShipment, toEnvioClickDaneCode } from "../../lib/envioclick";
|
||||||
|
import { DEFAULT_PACKAGE, FALLBACK_PRICE_COP, type EnvioClickOptions } from "./types";
|
||||||
|
|
||||||
|
type InjectedDependencies = {
|
||||||
|
logger: Logger;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Contexto minimo compartido entre calculatePrice/createFulfillment --
|
||||||
|
// ambos necesitan lo mismo (id DIVIPOLA de la ciudad destino, guardado
|
||||||
|
// como metadata en la direccion por el checkout -- ver ADR 0009 y
|
||||||
|
// checkout-client.tsx del storefront) y el paquete agregado del pedido.
|
||||||
|
interface AddressLike {
|
||||||
|
metadata?: Record<string, unknown> | null;
|
||||||
|
address_1?: string | null;
|
||||||
|
first_name?: string | null;
|
||||||
|
last_name?: string | null;
|
||||||
|
phone?: string | null;
|
||||||
|
email?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function destinationDaneCode(address: AddressLike | null | undefined): string | null {
|
||||||
|
const cityId = address?.metadata?.cityId;
|
||||||
|
return typeof cityId === "number" ? toEnvioClickDaneCode(cityId) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agrega el carrito/orden a UN solo paquete (EnvioClick solo acepta 1 por
|
||||||
|
// cotizacion/guia, confirmado en la doc real: "min 1, max 1"). Si algun
|
||||||
|
// item no tiene peso real cargado (hoy NINGUN producto lo tiene, ver
|
||||||
|
// plan de implementacion), se usa el paquete de fallback conservador
|
||||||
|
// completo en vez de mezclar datos reales con inventados a medias.
|
||||||
|
function aggregatePackage(items: Array<{ quantity: number; variant?: { weight?: number | null } | null }>) {
|
||||||
|
if (items.length === 0) return { ...DEFAULT_PACKAGE };
|
||||||
|
let totalWeight = 0;
|
||||||
|
for (const item of items) {
|
||||||
|
const weight = item.variant?.weight;
|
||||||
|
if (!weight) return { ...DEFAULT_PACKAGE };
|
||||||
|
totalWeight += weight * item.quantity;
|
||||||
|
}
|
||||||
|
return { ...DEFAULT_PACKAGE, weight: totalWeight };
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class EnvioClickFulfillmentService extends AbstractFulfillmentProviderService {
|
||||||
|
static identifier = "envioclick";
|
||||||
|
|
||||||
|
protected logger_: Logger;
|
||||||
|
protected options_: EnvioClickOptions;
|
||||||
|
|
||||||
|
constructor(container: InjectedDependencies, options: EnvioClickOptions) {
|
||||||
|
super();
|
||||||
|
this.logger_ = container.logger;
|
||||||
|
this.options_ = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateOptions(options: Record<string, unknown>): void {
|
||||||
|
for (const key of ["apiKey", "originDaneCode", "originAddress", "originCompany", "originFirstName", "originLastName", "originEmail", "originPhone"]) {
|
||||||
|
if (!options[key]) {
|
||||||
|
throw new Error(`envioclick-fulfillment: falta la opción "${key}" en medusa-config.ts`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
|
||||||
|
// Una sola opcion: siempre toma la tarifa mas barata entre las
|
||||||
|
// transportadoras que cotizan, mismo criterio que el plugin oficial
|
||||||
|
// de WooCommerce de referencia ("toma el precio mas economico").
|
||||||
|
return [{ id: "standard", name: "Envío nacional (calculado)" }];
|
||||||
|
}
|
||||||
|
|
||||||
|
async validateFulfillmentData(
|
||||||
|
optionData: Record<string, unknown>,
|
||||||
|
data: Record<string, unknown>,
|
||||||
|
_context: ValidateFulfillmentDataContext,
|
||||||
|
): Promise<any> {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async validateOption(_data: Record<string, unknown>): Promise<boolean> {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async canCalculate(_data: CreateShippingOptionDTO): Promise<boolean> {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se invoca en vivo durante el checkout cada vez que se piden/refrescan
|
||||||
|
// las shipping options del carrito. Medusa advierte explicitamente que
|
||||||
|
// un error acá bloquea el checkout entero -- por eso NUNCA se deja
|
||||||
|
// propagar una excepcion: cualquier falla (red, ciudad sin id DIVIPOLA,
|
||||||
|
// EnvioClick caido) cae al precio fijo que ya se usaba antes de esta
|
||||||
|
// integracion, para no romper la compra.
|
||||||
|
async calculatePrice(
|
||||||
|
optionData: CalculateShippingOptionPriceDTO["optionData"],
|
||||||
|
_data: CalculateShippingOptionPriceDTO["data"],
|
||||||
|
context: CalculateShippingOptionPriceContext,
|
||||||
|
): Promise<CalculatedShippingOptionPrice> {
|
||||||
|
const fallback: CalculatedShippingOptionPrice = {
|
||||||
|
calculated_amount: FALLBACK_PRICE_COP,
|
||||||
|
is_calculated_price_tax_inclusive: false,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const address = context.shipping_address as AddressLike | undefined;
|
||||||
|
const daneCode = destinationDaneCode(address);
|
||||||
|
if (!daneCode) {
|
||||||
|
this.logger_.warn("envioclick-fulfillment: dirección sin id DIVIPOLA en metadata, usando precio fijo de respaldo");
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = (context.items ?? []) as Array<{ quantity: number; variant?: { weight?: number | null } | null }>;
|
||||||
|
const pkg = aggregatePackage(items);
|
||||||
|
|
||||||
|
const rates = await quoteShipment(
|
||||||
|
{ apiKey: this.options_.apiKey },
|
||||||
|
{
|
||||||
|
pkg,
|
||||||
|
description: "Pedido ARI Shopping",
|
||||||
|
contentValue: 50000,
|
||||||
|
origin: { daneCode: this.options_.originDaneCode, address: this.options_.originAddress },
|
||||||
|
destination: { daneCode, address: address?.address_1 || "Dirección de entrega" },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rates.length === 0) return fallback;
|
||||||
|
|
||||||
|
const cheapest = rates.reduce((min, rate) =>
|
||||||
|
rate.flete + rate.minimumInsurance < min.flete + min.minimumInsurance ? rate : min,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
calculated_amount: cheapest.flete + cheapest.minimumInsurance,
|
||||||
|
is_calculated_price_tax_inclusive: false,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
this.logger_.warn(`envioclick-fulfillment: falló calculatePrice (${(error as Error).message}), usando precio fijo de respaldo`);
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A diferencia de calculatePrice, acá SÍ se deja propagar el error --
|
||||||
|
// el idRate de la cotización mostrada en checkout no se persiste en
|
||||||
|
// ningún lado (CalculatedShippingOptionPrice no tiene un campo `data`
|
||||||
|
// para eso, confirmado leyendo el tipo real), así que se vuelve a
|
||||||
|
// cotizar en el momento de generar la guía (más correcto igual: el
|
||||||
|
// fulfillment puede pasar horas/días después del checkout, un idRate
|
||||||
|
// viejo podría estar vencido) y se reserva con la tarifa más barata de
|
||||||
|
// esa cotización fresca.
|
||||||
|
async createFulfillment(
|
||||||
|
_data: Record<string, unknown>,
|
||||||
|
_items: Partial<Omit<FulfillmentItemDTO, "fulfillment">>[],
|
||||||
|
order: Partial<FulfillmentOrderDTO> | undefined,
|
||||||
|
_fulfillment: Partial<Omit<FulfillmentDTO, "provider_id" | "data" | "items">>,
|
||||||
|
): Promise<CreateFulfillmentResult> {
|
||||||
|
const address = order?.shipping_address as AddressLike | undefined;
|
||||||
|
const daneCode = destinationDaneCode(address);
|
||||||
|
if (!daneCode) {
|
||||||
|
throw new Error("envioclick-fulfillment: no se puede generar la guía sin un id DIVIPOLA en la dirección de envío.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = (order?.items ?? []) as unknown as Array<{ quantity: number; variant?: { weight?: number | null } | null }>;
|
||||||
|
const pkg = aggregatePackage(items);
|
||||||
|
|
||||||
|
const rates = await quoteShipment(
|
||||||
|
{ apiKey: this.options_.apiKey },
|
||||||
|
{
|
||||||
|
pkg,
|
||||||
|
description: "Pedido ARI Shopping",
|
||||||
|
contentValue: 50000,
|
||||||
|
origin: { daneCode: this.options_.originDaneCode, address: this.options_.originAddress },
|
||||||
|
destination: { daneCode, address: address?.address_1 || "Dirección de entrega" },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (rates.length === 0) {
|
||||||
|
throw new Error("envioclick-fulfillment: no hay tarifas disponibles para generar la guía.");
|
||||||
|
}
|
||||||
|
const cheapest = rates.reduce((min, rate) =>
|
||||||
|
rate.flete + rate.minimumInsurance < min.flete + min.minimumInsurance ? rate : min,
|
||||||
|
);
|
||||||
|
|
||||||
|
const guide = await createGuide(
|
||||||
|
{ apiKey: this.options_.apiKey },
|
||||||
|
this.options_.sandbox,
|
||||||
|
{
|
||||||
|
idRate: cheapest.idRate,
|
||||||
|
myShipmentReference: `Orden ${order?.display_id ?? order?.id ?? ""}`,
|
||||||
|
externalOrderId: String(order?.id ?? ""),
|
||||||
|
pkg,
|
||||||
|
description: "Pedido ARI Shopping",
|
||||||
|
contentValue: 50000,
|
||||||
|
origin: {
|
||||||
|
company: this.options_.originCompany,
|
||||||
|
firstName: this.options_.originFirstName,
|
||||||
|
lastName: this.options_.originLastName,
|
||||||
|
email: this.options_.originEmail,
|
||||||
|
phone: this.options_.originPhone,
|
||||||
|
address: this.options_.originAddress,
|
||||||
|
suburb: "N/A",
|
||||||
|
crossStreet: "N/A",
|
||||||
|
reference: "N/A",
|
||||||
|
daneCode: this.options_.originDaneCode,
|
||||||
|
},
|
||||||
|
destination: {
|
||||||
|
company: "N/A",
|
||||||
|
firstName: address?.first_name || "Cliente",
|
||||||
|
lastName: address?.last_name || "ARI",
|
||||||
|
email: address?.email || order?.email || "[email protected]",
|
||||||
|
phone: address?.phone || "0000000000",
|
||||||
|
address: address?.address_1 || "Dirección de entrega",
|
||||||
|
suburb: "N/A",
|
||||||
|
crossStreet: "N/A",
|
||||||
|
reference: "N/A",
|
||||||
|
daneCode,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: {
|
||||||
|
idOrder: guide.idOrder,
|
||||||
|
tracker: guide.tracker,
|
||||||
|
labelUrl: guide.url,
|
||||||
|
},
|
||||||
|
labels: [
|
||||||
|
{
|
||||||
|
tracking_number: guide.tracker,
|
||||||
|
tracking_url: guide.url,
|
||||||
|
label_url: guide.url,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
|
||||||
|
const idOrder = data.idOrder;
|
||||||
|
if (typeof idOrder !== "number") {
|
||||||
|
this.logger_.warn("envioclick-fulfillment: cancelFulfillment sin idOrder guardado, no hay nada que cancelar en EnvíoClick");
|
||||||
|
return { data };
|
||||||
|
}
|
||||||
|
await cancelGuides({ apiKey: this.options_.apiKey }, [idOrder]);
|
||||||
|
return { data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFulfillmentDocuments(_data: Record<string, unknown>): Promise<never[]> {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async createReturnFulfillment(_fulfillment: Record<string, unknown>): Promise<CreateFulfillmentResult> {
|
||||||
|
// Devoluciones no estan en alcance de esta primera version.
|
||||||
|
throw new Error("envioclick-fulfillment: createReturnFulfillment no está implementado todavía.");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getReturnDocuments(_data: Record<string, unknown>): Promise<never[]> {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async getShipmentDocuments(_data: Record<string, unknown>): Promise<never[]> {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async retrieveDocuments(_fulfillmentData: Record<string, unknown>, _documentType: string): Promise<void> {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
export interface EnvioClickOptions {
|
||||||
|
apiKey: string;
|
||||||
|
// El unico endpoint con modo de pruebas real es la generacion de guia
|
||||||
|
// (ver src/lib/envioclick.ts) -- la cotizacion siempre usa tarifas
|
||||||
|
// reales, no hay nada que alternar ahi.
|
||||||
|
sandbox: boolean;
|
||||||
|
// Datos de la bodega de origen -- la stock location real todavia no
|
||||||
|
// tiene direccion fisica cargada ("Sin dirección física registrada"),
|
||||||
|
// asi que estos vienen de config hasta que se cargue una real.
|
||||||
|
originDaneCode: string;
|
||||||
|
originAddress: string;
|
||||||
|
originCompany: string;
|
||||||
|
originFirstName: string;
|
||||||
|
originLastName: string;
|
||||||
|
originEmail: string;
|
||||||
|
originPhone: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Precio de fallback cuando EnvíoClick falla o no hay peso/dimensiones
|
||||||
|
// reales del pedido (hoy ningun producto los tiene cargados) -- mismo
|
||||||
|
// valor que ya usaba la shipping option fija de ADR 0009, para no
|
||||||
|
// empeorar la experiencia mientras no haya datos reales.
|
||||||
|
export const FALLBACK_PRICE_COP = 15000;
|
||||||
|
|
||||||
|
// Paquete por defecto cuando algun item del carrito no tiene
|
||||||
|
// peso/dimensiones reales -- conservador, no preciso. Ver nota en el
|
||||||
|
// plan de implementacion: esto es una tarea de datos, no de codigo.
|
||||||
|
export const DEFAULT_PACKAGE = {
|
||||||
|
weight: 1,
|
||||||
|
length: 20,
|
||||||
|
height: 20,
|
||||||
|
width: 20,
|
||||||
|
};
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { ModuleProvider, Modules } from "@medusajs/framework/utils";
|
||||||
|
import EpaycoPseProviderService from "./service";
|
||||||
|
|
||||||
|
export default ModuleProvider(Modules.PAYMENT, {
|
||||||
|
services: [EpaycoPseProviderService],
|
||||||
|
});
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { AbstractPaymentProvider, BigNumber } from "@medusajs/framework/utils";
|
||||||
|
import type {
|
||||||
|
AuthorizePaymentInput,
|
||||||
|
AuthorizePaymentOutput,
|
||||||
|
CancelPaymentInput,
|
||||||
|
CancelPaymentOutput,
|
||||||
|
CapturePaymentInput,
|
||||||
|
CapturePaymentOutput,
|
||||||
|
DeletePaymentInput,
|
||||||
|
DeletePaymentOutput,
|
||||||
|
GetPaymentStatusInput,
|
||||||
|
GetPaymentStatusOutput,
|
||||||
|
InitiatePaymentInput,
|
||||||
|
InitiatePaymentOutput,
|
||||||
|
Logger,
|
||||||
|
ProviderWebhookPayload,
|
||||||
|
RefundPaymentInput,
|
||||||
|
RefundPaymentOutput,
|
||||||
|
RetrievePaymentInput,
|
||||||
|
RetrievePaymentOutput,
|
||||||
|
UpdatePaymentInput,
|
||||||
|
UpdatePaymentOutput,
|
||||||
|
WebhookActionResult,
|
||||||
|
} from "@medusajs/framework/types";
|
||||||
|
import { createEpaycoClient, verifyWebhookSignature } from "../../lib/epayco";
|
||||||
|
import type { EpaycoPseInputData, EpaycoPseOptions, EpaycoPseSessionData } from "./types";
|
||||||
|
|
||||||
|
type InjectedDependencies = {
|
||||||
|
logger: Logger;
|
||||||
|
};
|
||||||
|
|
||||||
|
// PSE via ePayco es asincrono igual que PayU/Rapyd: no hay confirmacion
|
||||||
|
// real hasta que llega el webhook (url_confirmation), nunca en la
|
||||||
|
// respuesta sincrona de bank.create(). authorizePayment/capturePayment
|
||||||
|
// por eso son casi no-ops -- el estado real lo trae siempre el webhook.
|
||||||
|
export default class EpaycoPseProviderService extends AbstractPaymentProvider<EpaycoPseOptions> {
|
||||||
|
static identifier = "epayco";
|
||||||
|
|
||||||
|
protected logger_: Logger;
|
||||||
|
protected options_: EpaycoPseOptions;
|
||||||
|
|
||||||
|
constructor(container: InjectedDependencies, options: EpaycoPseOptions) {
|
||||||
|
super(container, options);
|
||||||
|
this.logger_ = container.logger;
|
||||||
|
this.options_ = options;
|
||||||
|
}
|
||||||
|
|
||||||
|
static validateOptions(options: Record<string, unknown>): void {
|
||||||
|
for (const key of ["publicKey", "privateKey", "pCustIdCliente", "pKey", "env", "responseUrl", "notifyUrl"]) {
|
||||||
|
if (!options[key]) {
|
||||||
|
throw new Error(`epayco-pse: falta la opción "${key}" en medusa-config.ts`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseInputData & { session_id: string };
|
||||||
|
const sessionId = data.session_id;
|
||||||
|
const amount = new BigNumber(input.amount).numeric;
|
||||||
|
const currency = input.currency_code.toUpperCase();
|
||||||
|
|
||||||
|
const client = createEpaycoClient(this.options_);
|
||||||
|
|
||||||
|
// Campos confirmados leyendo node_modules/epayco-sdk-node/lib/keylang.json
|
||||||
|
// y tests/bank.js directamente (no la documentacion publica -- esa
|
||||||
|
// mostraba "metodoconfirmacion", el codigo real que de verdad manda
|
||||||
|
// el SDK usa "method_confirmation"). El SDK cifra estos valores y
|
||||||
|
// agrega ip/test/auth por su cuenta, no hace falta hacerlo nosotros.
|
||||||
|
const response = await client.bank.create({
|
||||||
|
bank: data.bank_code,
|
||||||
|
invoice: sessionId,
|
||||||
|
description: `Orden ARI Shopping ${sessionId}`,
|
||||||
|
value: String(amount),
|
||||||
|
tax: "0",
|
||||||
|
tax_base: "0",
|
||||||
|
currency,
|
||||||
|
type_person: data.user_type,
|
||||||
|
doc_type: data.doc_type,
|
||||||
|
doc_number: data.doc_number,
|
||||||
|
name: data.first_name,
|
||||||
|
last_name: data.last_name,
|
||||||
|
email: data.email,
|
||||||
|
country: "CO",
|
||||||
|
city: data.city,
|
||||||
|
cell_phone: data.phone,
|
||||||
|
url_response: this.options_.responseUrl,
|
||||||
|
url_confirmation: this.options_.notifyUrl,
|
||||||
|
method_confirmation: "POST",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.error) {
|
||||||
|
throw new Error(`ePayco rechazó la transacción para la sesión ${sessionId}: ${JSON.stringify(response).slice(0, 300)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// El nombre real del campo con la URL de redirección al banco NO
|
||||||
|
// quedó verificado contra una respuesta real de sandbox en esta
|
||||||
|
// sesión (ni la doc ni los tests del SDK lo muestran) -- se prueban
|
||||||
|
// los candidatos más probables y, si ninguno aparece, se tira un
|
||||||
|
// error con el payload completo para poder leerlo en los logs y
|
||||||
|
// corregir esto en el primer intento real contra el sandbox.
|
||||||
|
const flat = (response.data ?? response) as Record<string, unknown>;
|
||||||
|
const bankUrlCandidates = ["urlbanco", "url_banco", "urlBanco", "url", "redirect_url"];
|
||||||
|
const bankUrl = bankUrlCandidates.map((key) => flat[key]).find((value) => typeof value === "string" && value);
|
||||||
|
|
||||||
|
if (typeof bankUrl !== "string" || !bankUrl) {
|
||||||
|
throw new Error(
|
||||||
|
`ePayco no devolvió una URL de banco reconocible para la sesión ${sessionId}. Respuesta completa (revisar para corregir el nombre del campo): ${JSON.stringify(response).slice(0, 500)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionData: EpaycoPseSessionData = {
|
||||||
|
...data,
|
||||||
|
session_id: sessionId,
|
||||||
|
ref_payco: String(flat.ref_payco ?? flat.refPayco ?? ""),
|
||||||
|
transaction_id: String(flat.transactionID ?? flat.transaction_id ?? ""),
|
||||||
|
bank_url: bankUrl,
|
||||||
|
state: "PENDING",
|
||||||
|
amount,
|
||||||
|
currency,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { id: sessionId, data: sessionData as unknown as Record<string, unknown>, status: "pending" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// PSE es diferido: en el momento de completar el carrito, ePayco
|
||||||
|
// todavia no confirmo nada -- "pending_authorization" es el mecanismo
|
||||||
|
// documentado de Medusa para esto (la orden queda "awaiting" y el
|
||||||
|
// navegador ya puede redirigirse al banco).
|
||||||
|
async authorizePayment(input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
|
||||||
|
return { data: input.data, status: "pending_authorization" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casi no-op: cuando el webhook reporta "captured", ePayco ya liquido
|
||||||
|
// el dinero de su lado -- solo persiste el data actualizado.
|
||||||
|
async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async cancelPayment(input: CancelPaymentInput): Promise<CancelPaymentOutput> {
|
||||||
|
this.logger_.warn("epayco-pse: cancelPayment llamado, pero PSE no soporta cancelar una transacción ya enviada");
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async deletePayment(input: DeletePaymentInput): Promise<DeletePaymentOutput> {
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Endpoint de reembolso de ePayco no quedó verificado en vivo en esta
|
||||||
|
// sesión -- con dinero real de por medio, mejor tirar un error
|
||||||
|
// explícito que fingir un reembolso que nunca se procesó.
|
||||||
|
async refundPayment(_input: RefundPaymentInput): Promise<RefundPaymentOutput> {
|
||||||
|
throw new Error(
|
||||||
|
"epayco-pse: refundPayment no está implementado todavía -- procesar el reembolso manualmente desde el panel de ePayco por ahora.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /validation/v1/reference/{ref_payco} -- endpoint de verificación
|
||||||
|
// server-to-server documentado por ePayco para consultar el estado
|
||||||
|
// real de una transacción.
|
||||||
|
async retrievePayment(input: RetrievePaymentInput): Promise<RetrievePaymentOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseSessionData | undefined;
|
||||||
|
const refPayco = data?.ref_payco;
|
||||||
|
if (!refPayco) {
|
||||||
|
throw new Error("epayco-pse: retrievePayment necesita ref_payco, no está guardado en esta sesión.");
|
||||||
|
}
|
||||||
|
const response = await fetch(`https://secure.epayco.co/validation/v1/reference/${refPayco}`);
|
||||||
|
const json = await response.json();
|
||||||
|
return { data: json as Record<string, unknown> };
|
||||||
|
}
|
||||||
|
|
||||||
|
async updatePayment(input: UpdatePaymentInput): Promise<UpdatePaymentOutput> {
|
||||||
|
// ePayco no tiene concepto de "modificar" una transaccion ya
|
||||||
|
// enviada. El checkout solo llega al step de pago despues de fijar
|
||||||
|
// direccion y envio, asi que el total no deberia cambiar una vez que
|
||||||
|
// existe una sesion PSE.
|
||||||
|
return { data: input.data };
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPaymentStatus(input: GetPaymentStatusInput): Promise<GetPaymentStatusOutput> {
|
||||||
|
const data = input.data as unknown as EpaycoPseSessionData | undefined;
|
||||||
|
const state = data?.state;
|
||||||
|
if (state === "1") return { status: "captured" };
|
||||||
|
if (state === "3") return { status: "pending" };
|
||||||
|
if (state === "PENDING") return { status: "pending" };
|
||||||
|
return { status: "canceled" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unico punto real de confirmacion asincrona. Falla cerrado: si la
|
||||||
|
// firma no matchea, no se hace nada -- nunca se confia en un webhook
|
||||||
|
// sin firma valida.
|
||||||
|
async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
|
||||||
|
const body = payload.data as Record<string, unknown>;
|
||||||
|
const refPayco = String(body.x_ref_payco ?? "");
|
||||||
|
const transactionId = String(body.x_transaction_id ?? "");
|
||||||
|
const amount = String(body.x_amount ?? "");
|
||||||
|
const currencyCode = String(body.x_currency_code ?? "");
|
||||||
|
const codState = String(body.x_cod_transaction_state ?? "");
|
||||||
|
const signature = String(body.x_signature ?? "");
|
||||||
|
// session_id sale del invoice que nosotros mandamos -- ePayco lo
|
||||||
|
// devuelve como x_id_invoice (o x_extra1 si no viniera) segun el
|
||||||
|
// webhook real; se intentan ambos.
|
||||||
|
const sessionId = String(body.x_id_invoice ?? body.x_extra1 ?? refPayco);
|
||||||
|
|
||||||
|
const validSignature = verifyWebhookSignature({
|
||||||
|
pCustIdCliente: this.options_.pCustIdCliente,
|
||||||
|
pKey: this.options_.pKey,
|
||||||
|
refPayco,
|
||||||
|
transactionId,
|
||||||
|
amount,
|
||||||
|
currencyCode,
|
||||||
|
signature,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!validSignature) {
|
||||||
|
this.logger_.warn(`epayco-pse: webhook con firma inválida para x_ref_payco=${refPayco}, ignorado`);
|
||||||
|
return { action: "not_supported" };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Solo "1" (Aceptada) es exito -- cualquier otro codigo (2 Rechazada,
|
||||||
|
// 4 Fallida, 6 Reversada, 9 caducada, 10 abandonada, 11 Cancelada,
|
||||||
|
// 3 Pendiente) se trata como fallido en vez de asumir un exito
|
||||||
|
// distinto. Un "failed" de mas es reintentable; un "captured" de mas
|
||||||
|
// (dinero que nunca se aprobo) no lo es.
|
||||||
|
const action = codState === "1" ? "captured" : "failed";
|
||||||
|
|
||||||
|
return {
|
||||||
|
action,
|
||||||
|
data: {
|
||||||
|
session_id: sessionId,
|
||||||
|
amount: new BigNumber(amount || 0),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import type { EpaycoEnv } from "../../lib/epayco";
|
||||||
|
|
||||||
|
export interface EpaycoPseOptions {
|
||||||
|
publicKey: string;
|
||||||
|
privateKey: string;
|
||||||
|
// p_cust_id_cliente / p_key -- valores propios del dashboard de ePayco
|
||||||
|
// para verificar la firma del webhook, distintos de publicKey/privateKey.
|
||||||
|
pCustIdCliente: string;
|
||||||
|
pKey: string;
|
||||||
|
env: EpaycoEnv;
|
||||||
|
// A donde ePayco redirige al comprador de vuelta tras pagar en el
|
||||||
|
// banco (pagina propia del storefront, no confirma nada por si sola).
|
||||||
|
responseUrl: string;
|
||||||
|
// URL publica de confirmacion -- por-transaccion (a diferencia de
|
||||||
|
// Rapyd, que solo permite configurarlo una vez a nivel de cuenta),
|
||||||
|
// apunta a la ruta nativa de Medusa /hooks/payment/:provider.
|
||||||
|
notifyUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type EpaycoDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
// "0" persona natural, "1" persona juridica -- valores reales que espera
|
||||||
|
// el campo type_person de ePayco.
|
||||||
|
export type EpaycoUserType = "0" | "1";
|
||||||
|
|
||||||
|
// Lo que el storefront manda como `data` al crear la sesion de pago PSE
|
||||||
|
// (recolectado en el step "address" del checkout, mas el banco/tipo de
|
||||||
|
// persona/documento del nuevo step "payment"). No viene de
|
||||||
|
// `context.customer` porque el checkout es de invitado -- ver ADR 0009.
|
||||||
|
export interface EpaycoPseInputData {
|
||||||
|
bank_code: string;
|
||||||
|
user_type: EpaycoUserType;
|
||||||
|
doc_type: EpaycoDocType;
|
||||||
|
doc_number: string;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
city: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lo que initiatePayment devuelve y queda guardado en `data` de la
|
||||||
|
// PaymentSession -- publico para el storefront, nunca poner credenciales
|
||||||
|
// acá. `bank_url`: nombre de campo AUN NO VERIFICADO contra una
|
||||||
|
// respuesta real de sandbox (ver comentario en service.ts) -- primer
|
||||||
|
// punto a confirmar en la primera prueba end-to-end.
|
||||||
|
export interface EpaycoPseSessionData extends EpaycoPseInputData {
|
||||||
|
session_id: string;
|
||||||
|
ref_payco: string;
|
||||||
|
transaction_id: string;
|
||||||
|
bank_url: string;
|
||||||
|
state: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
}
|
||||||
@@ -37,6 +37,9 @@ flowchart LR
|
|||||||
SSH["Cliente SSH<br/>(laptop / tablet / lo que sea)"] -->|docker exec| C["Contenedor tmux-host<br/>--network host, --restart unless-stopped"]
|
SSH["Cliente SSH<br/>(laptop / tablet / lo que sea)"] -->|docker exec| C["Contenedor tmux-host<br/>--network host, --restart unless-stopped"]
|
||||||
C --> T["tmux server<br/>sesión 'lab'"]
|
C --> T["tmux server<br/>sesión 'lab'"]
|
||||||
T --> CC["proceso claude<br/>(Claude Code)"]
|
T --> CC["proceso claude<br/>(Claude Code)"]
|
||||||
|
C --> HC["healthcheck.sh (background)<br/>cada 30 min"]
|
||||||
|
HC -.->|curl| NET["gitea.cruzcloud.net"]
|
||||||
|
HC -.->|recrea si falta| T
|
||||||
C -.->|bind mount| DATA["/DATA (host)<br/>repos y configs del lab"]
|
C -.->|bind mount| DATA["/DATA (host)<br/>repos y configs del lab"]
|
||||||
C -.->|bind mount| SOCK["/var/run/docker.sock (host)<br/>control de Docker/k3d"]
|
C -.->|bind mount| SOCK["/var/run/docker.sock (host)<br/>control de Docker/k3d"]
|
||||||
C -.->|bind mount| HOME["/DATA/AppData/k3d-lab-v3/claude-code-home (host)<br/>-> /root/.claude"]
|
C -.->|bind mount| HOME["/DATA/AppData/k3d-lab-v3/claude-code-home (host)<br/>-> /root/.claude"]
|
||||||
@@ -49,7 +52,17 @@ reinicia.
|
|||||||
|
|
||||||
## Contenedor: `tmux-host`
|
## Contenedor: `tmux-host`
|
||||||
|
|
||||||
|
La imagen se construye desde `scripts/tmux-host/Dockerfile` (antes era
|
||||||
|
un `docker run ... alpine sh -c "apk add ..."` inline — mismo contenido,
|
||||||
|
pero ahora como imagen versionada en vez de reinstalar todo en cada
|
||||||
|
arranque). El Dockerfile fija `WORKDIR /DATA/AppData/k3d-lab-v3/lab-cruzcloud`
|
||||||
|
(la raíz del lab, con `CLAUDE.md`, `apps-registry/`, `platform-infra/` y
|
||||||
|
`scripts/`) y agrega `healthcheck.sh` (ver más abajo) como proceso en
|
||||||
|
background del contenedor.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
docker build -t tmux-host:local scripts/tmux-host
|
||||||
|
|
||||||
docker run -d \
|
docker run -d \
|
||||||
--name tmux-host \
|
--name tmux-host \
|
||||||
--restart unless-stopped \
|
--restart unless-stopped \
|
||||||
@@ -59,9 +72,15 @@ docker run -d \
|
|||||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home:/root/.claude \
|
-v /DATA/AppData/k3d-lab-v3/claude-code-home:/root/.claude \
|
||||||
-v /DATA/AppData/k3d-lab-v3/claude-code-home.json:/root/.claude.json \
|
-v /DATA/AppData/k3d-lab-v3/claude-code-home.json:/root/.claude.json \
|
||||||
--network host \
|
--network host \
|
||||||
alpine sh -c "apk add --no-cache tmux docker-cli bash curl git kubectl nodejs npm && npm install -g @anthropic-ai/claude-code && git config --global --add safe.directory '*' && tail -f /dev/null"
|
tmux-host:local
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`WORKDIR` hace que `docker exec` (y por lo tanto `lab-session.sh`)
|
||||||
|
arranquen ya posicionados en la raíz del lab sin tener que navegar a
|
||||||
|
mano — `lab-session.sh` además pasa la ruta explícita vía `tmux new -c`
|
||||||
|
por las dudas, para no depender de que `docker exec` herede el `WORKDIR`
|
||||||
|
de la imagen.
|
||||||
|
|
||||||
| Volumen | Destino | Por qué |
|
| Volumen | Destino | Por qué |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `/DATA` | `/DATA` | Acceso a los repos (`apps-registry`, `platform-infra`, `scripts`) y configs del lab, mismos paths que en el host |
|
| `/DATA` | `/DATA` | Acceso a los repos (`apps-registry`, `platform-infra`, `scripts`) y configs del lab, mismos paths que en el host |
|
||||||
@@ -195,13 +214,47 @@ Si la sesión `lab` existe, se adjunta a ella (mismo shell, mismo
|
|||||||
ejemplo justo después de que el contenedor se recreó desde cero— la
|
ejemplo justo después de que el contenedor se recreó desde cero— la
|
||||||
crea. No hay que recordar cuál de los dos casos aplica.
|
crea. No hay que recordar cuál de los dos casos aplica.
|
||||||
|
|
||||||
|
## Chequeo de salud automático (cada 30 min)
|
||||||
|
|
||||||
|
`scripts/tmux-host/healthcheck.sh` corre en background dentro del
|
||||||
|
propio contenedor (lanzado por `entrypoint.sh`, el `ENTRYPOINT` de la
|
||||||
|
imagen) y cada `HEALTHCHECK_INTERVAL_SEC` (1800s por defecto) hace dos
|
||||||
|
chequeos independientes, con una respuesta distinta según el tipo de
|
||||||
|
falla:
|
||||||
|
|
||||||
|
- **Conectividad de red real** (`curl` a `https://gitea.cruzcloud.net/`):
|
||||||
|
si falla, **solo se registra** en el log y se notifica por Telegram —
|
||||||
|
el contenedor nunca intenta "arreglar" la red del host. Un problema de
|
||||||
|
red puede ser de hardware/BIOS (deuda técnica ya conocida, ver
|
||||||
|
`incidente-medusa-crashloop-2026-08.md`), fuera del alcance real de un
|
||||||
|
contenedor.
|
||||||
|
- **Existencia de la sesión tmux `lab`** (`tmux has-session`): si no
|
||||||
|
existe, **sí se recrea automáticamente** (`tmux new-session -d -s lab
|
||||||
|
-c <WORKDIR>`) — es solo recuperar el propio entorno de trabajo del
|
||||||
|
contenedor, no tocar infraestructura externa, así que es seguro
|
||||||
|
hacerlo sin intervención humana.
|
||||||
|
|
||||||
|
Todo evento (chequeo ok, falla de red, sesión recreada) queda en
|
||||||
|
`/DATA/AppData/k3d-lab-v3/tmux-host/logs/health.log` — persistente en
|
||||||
|
`/DATA`, no solo en el stdout del contenedor (que se pierde con
|
||||||
|
`docker logs` al recrearlo). Las notificaciones de Telegram reusan el
|
||||||
|
mismo bot/`chat_id` ya configurado para `scripts/lab-agent/`
|
||||||
|
(`lab-agent.env`), en vez de duplicar credenciales entre los dos
|
||||||
|
agentes del lab.
|
||||||
|
|
||||||
|
Para probar el intervalo sin esperar 30 minutos, se puede levantar el
|
||||||
|
contenedor con `-e HEALTHCHECK_INTERVAL_SEC=60` (solo para pruebas en un
|
||||||
|
contenedor descartable — nunca cambiar esto en el `tmux-host` real sin
|
||||||
|
volver a 1800 después).
|
||||||
|
|
||||||
## Qué sobrevive a qué
|
## Qué sobrevive a qué
|
||||||
|
|
||||||
| Evento | ¿Sobrevive la sesión tmux (`lab`)? | ¿Sobrevive el login de Claude Code? |
|
| Evento | ¿Sobrevive la sesión tmux (`lab`)? | ¿Sobrevive el login de Claude Code? |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Corte de SSH / cerrar la terminal / cambiar de dispositivo | Sí — es exactamente el caso que este setup resuelve | Sí |
|
| Corte de SSH / cerrar la terminal / cambiar de dispositivo | Sí — es exactamente el caso que este setup resuelve | Sí |
|
||||||
| `docker restart tmux-host` (reinicio del NAS) | **No** — el proceso `tmux server` muere con el contenedor; `lab-session.sh` crea una sesión nueva automáticamente | Sí, vía el volumen montado en `/root/.claude` |
|
| `docker restart tmux-host` (reinicio del NAS) | **No al toque, pero se auto-recupera solo** — el proceso `tmux server` muere con el contenedor; `healthcheck.sh` la recrea en el próximo ciclo (máx. 30 min) sin intervención, o `lab-session.sh` la crea al instante si alguien se reconecta antes | Sí, vía el volumen montado en `/root/.claude` |
|
||||||
| `docker rm` + recrear el contenedor desde cero | No | Sí, vía el mismo volumen — no hace falta volver a autenticar ni reconfirmar el diálogo de confianza del folder (ver el mount de `claude-code-home.json`) |
|
| `docker rm` + recrear el contenedor desde cero | No, pero igual se auto-recupera sola (mismo mecanismo de arriba) | Sí, vía el mismo volumen — no hace falta volver a autenticar ni reconfirmar el diálogo de confianza del folder (ver el mount de `claude-code-home.json`) |
|
||||||
|
| Falla de red real del host/NAS | N/A | N/A — `healthcheck.sh` la detecta y notifica, pero no la corrige (fuera de su alcance) |
|
||||||
|
|
||||||
## Validación en vivo
|
## Validación en vivo
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
# ADR 0008 — Identidad visual "Navy & Coral" para ARI Shopping
|
# ADR 0008 — Identidad visual "Navy & Coral" para ARI Shopping
|
||||||
|
|
||||||
**Estado:** aceptada (implementación en curso, por sub-fases)
|
**Estado:** aceptada, con enmienda de paleta (ver §8) — sub-fases 1 a 4
|
||||||
**Fecha:** 2026-08-27
|
completas, sub-fase 5 parcial (ver §9)
|
||||||
|
**Fecha:** 2026-08-27 (enmendada 2026-09-06)
|
||||||
**Reemplaza a:** [ADR 0007](0007-identidad-visual-propia.md) (Opción 2, "Atelier cálido")
|
**Reemplaza a:** [ADR 0007](0007-identidad-visual-propia.md) (Opción 2, "Atelier cálido")
|
||||||
|
|
||||||
|
> **Nota de vigencia:** la paleta descrita en §4 ("Navy & Coral":
|
||||||
|
> marino `#122844` / coral `#D85A30` / coral claro `#F0997B`) fue la
|
||||||
|
> dirección **aprobada e implementada en las sub-fases 1-3**, pero fue
|
||||||
|
> **reemplazada el mismo día** por una paleta azul/amarillo estilo
|
||||||
|
> Walmart (rama `fix/adr0008-walmart-palette-blue-yellow`, ver §8). Los
|
||||||
|
> valores reales en producción hoy están en §8, no en §4. Se deja §4
|
||||||
|
> intacto como registro histórico de la decisión original.
|
||||||
|
|
||||||
## 1. Contexto
|
## 1. Contexto
|
||||||
|
|
||||||
Este es el tercer intento de identidad visual propia para ARI Shopping,
|
Este es el tercer intento de identidad visual propia para ARI Shopping,
|
||||||
@@ -168,3 +177,66 @@ definitivo; los alias se eliminan por completo al cerrar la sub-fase
|
|||||||
`commerce-backend`, `platform-infra`, ni CI nuevo.
|
`commerce-backend`, `platform-infra`, ni CI nuevo.
|
||||||
- `docs-portal` se actualiza con capturas/descripción del resultado
|
- `docs-portal` se actualiza con capturas/descripción del resultado
|
||||||
final una vez cada sub-fase esté validada en producción, no antes.
|
final una vez cada sub-fase esté validada en producción, no antes.
|
||||||
|
|
||||||
|
## 8. Enmienda 2026-08-27 tarde: pivote de paleta a azul/amarillo
|
||||||
|
|
||||||
|
Horas después de mergear la sub-fase 3 (product card + grid), se
|
||||||
|
mergeó `fix/adr0008-walmart-palette-blue-yellow`: la paleta "Navy &
|
||||||
|
Coral" de §4 se descartó en producción y se reemplazó por una paleta
|
||||||
|
azul/amarillo (mismo patrón "estética Walmart" ya usado como
|
||||||
|
referencia de UX en ADR 0007). Esta decisión **no quedó documentada
|
||||||
|
como enmienda en su momento** — se detecta y se registra aquí recién
|
||||||
|
el 2026-09-06, al auditar el estado real del código contra este
|
||||||
|
documento.
|
||||||
|
|
||||||
|
Valores reales en `globals.css` hoy (los nombres de token de §4 se
|
||||||
|
conservan, pero apuntan a estos valores, no a los de la tabla
|
||||||
|
original):
|
||||||
|
|
||||||
|
| Token | Valor real | Uso |
|
||||||
|
|---|---|---|
|
||||||
|
| `--color-ari-marino` | `#0055B8` (azul) | ancla: header, footer, fondo de hero, botón de búsqueda |
|
||||||
|
| `--color-ari-coral` | `#0055B8` (azul, mismo valor que marino) | CTA "Agregar al carrito", precio destacado |
|
||||||
|
| `--color-ari-coral-claro` | `#FFC220` (amarillo) | badges de oferta/urgencia, acento del isotipo, botón "yellow" del hero |
|
||||||
|
|
||||||
|
Nota: `ari-coral` y `ari-marino` son el mismo azul (`#0055B8`) — a
|
||||||
|
diferencia de la especificación original de §4, donde marino y coral
|
||||||
|
eran colores distintos. Cualquier lectura de este ADR para decisiones
|
||||||
|
de diseño futuras debe partir de esta tabla, no de §4.
|
||||||
|
|
||||||
|
El isotipo (mariposa de 4 elipses, §4) tampoco se implementó como se
|
||||||
|
describe: el logo vigente es `logo-ari-circular.svg` (rama
|
||||||
|
`adr0008-logo-circular-header`), un lockup circular distinto al
|
||||||
|
descrito en la tabla de coordenadas de §4. `logo-ari.svg` (rectangular,
|
||||||
|
el que sí sigue la spec original) quedó sin usarse en el header.
|
||||||
|
|
||||||
|
## 9. Estado real por sub-fase (auditado 2026-09-06)
|
||||||
|
|
||||||
|
Auditoría contra el código en `main`, no contra el plan de §6.
|
||||||
|
|
||||||
|
| # | Sub-fase | Estado | Evidencia |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | Tokens base + logo | ✅ completa (con la paleta enmendada en §8, no la de §4) | `globals.css`, `logo-ari.svg` inicial, luego reemplazado por circular en sub-fase posterior |
|
||||||
|
| 2 | Header + footer (incl. limpieza de §5) | ✅ completa | `navbar.tsx`, restos arcoíris (gradiente ámbar/lima, línea cian/violeta/fucsia de §5) eliminados |
|
||||||
|
| 3 | Product card + grid + badges | ✅ completa | `product-card.tsx` en tokens `ari-*` |
|
||||||
|
| 4 | Home (hero, tiles, secciones) | ✅ completa | `hero-carousel.tsx`, `category-tiles.tsx` (varias iteraciones: pastel → scrim → foto flotante → foto más grande, todas mergeadas) |
|
||||||
|
| 5 | Página de producto + drawers de carrito/wishlist | ⚠️ **parcial** | `product-purchase.tsx`/página de producto sí migraron (rama `adr0008-product-purchase-mobile-y-badge`). **`cart-drawer.tsx` y `wishlist-drawer.tsx` no tienen ningún token `ari-*` — nunca se tocaron.** No hay rama mergeada que los mencione. |
|
||||||
|
|
||||||
|
**Deuda abierta, no asumir resuelta:**
|
||||||
|
|
||||||
|
- Los alias de compatibilidad de §6 (`ari-ciruela`, `ari-cobre`,
|
||||||
|
`ari-carbon`, `ari-carbon-oscuro`, `ari-terracota-oscuro`,
|
||||||
|
`ari-hueso`) **siguen en uso real en `button.tsx`**
|
||||||
|
(`focus-visible:ring-ari-cobre/40`, `bg-ari-ciruela`,
|
||||||
|
`hover:border-ari-cobre`) — la condición de cierre de §6 ("los alias
|
||||||
|
se eliminan por completo al cerrar la sub-fase 5") no se cumplió.
|
||||||
|
Confirma que la sub-fase 5 no está cerrada, más allá de los drawers.
|
||||||
|
- Ramas mergeadas fuera del plan original de 5 sub-fases de §6, sin
|
||||||
|
enmienda que las registre: `adr0008-megamenu-mobile-overflow`,
|
||||||
|
`adr0008-club-ari-y-novedades`, `adr0008-club-ari-imagen-azul`. Son
|
||||||
|
trabajo real en producción, pero expanden el alcance de este ADR sin
|
||||||
|
quedar documentado como tal.
|
||||||
|
- `docs-portal` (este documento) es la primera actualización desde el
|
||||||
|
cierre de la sub-fase 3 — la condición de §7 ("se actualiza con
|
||||||
|
capturas/descripción... una vez cada sub-fase esté validada") no se
|
||||||
|
vino cumpliendo sub-fase por sub-fase como se planeó.
|
||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsNonRoot: false
|
runAsNonRoot: false
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.207
|
image: gitea.cruzcloud.net/devops/docs-portal:v1.0.224
|
||||||
# El base saca TODAS las capabilities. Probado en vivo y
|
# El base saca TODAS las capabilities. Probado en vivo y
|
||||||
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
# revertido: con drop: ALL (aunque se agregue NET_BIND_SERVICE
|
||||||
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
# de vuelta) el propio entrypoint de nginx:1.27-alpine falla al
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { completeCart } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId } = await request.json();
|
||||||
|
if (!cartId) {
|
||||||
|
return Response.json({ error: "Falta cartId" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await completeCart(cartId);
|
||||||
|
return Response.json({ ok: true });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { getPseBanks } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function GET() {
|
||||||
|
try {
|
||||||
|
const banks = await getPseBanks();
|
||||||
|
return Response.json({ banks });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { createPaymentCollection, createPsePaymentSession } from "@/lib/headless/providers/medusa-payment";
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const { cartId, ...pse } = await request.json();
|
||||||
|
if (!cartId || !pse.bankCode || !pse.docNumber || !pse.firstName || !pse.lastName || !pse.email || !pse.phone) {
|
||||||
|
return Response.json({ error: "Faltan campos obligatorios para el pago con PSE" }, { status: 400 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const paymentCollectionId = await createPaymentCollection(cartId);
|
||||||
|
const bankUrl = await createPsePaymentSession(paymentCollectionId, pse);
|
||||||
|
return Response.json({ bankUrl });
|
||||||
|
} catch (error) {
|
||||||
|
return Response.json({ error: (error as Error).message }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Suspense } from "react";
|
||||||
|
import { PseReturnClient } from "@/components/checkout/pse-return-client";
|
||||||
|
|
||||||
|
export default function PseReturnPage() {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={null}>
|
||||||
|
<PseReturnClient />
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -24,3 +24,27 @@ data:
|
|||||||
# env var del plugin, no del servidor Meilisearch en si -- ver
|
# env var del plugin, no del servidor Meilisearch en si -- ver
|
||||||
# MEILI_MASTER_KEY en secrets.template.yaml).
|
# MEILI_MASTER_KEY en secrets.template.yaml).
|
||||||
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
MEILISEARCH_HOST: http://meilisearch-svc:7700
|
||||||
|
|
||||||
|
# ePayco (ADR 0009 -- tercer proveedor evaluado, ver medusa-config.ts
|
||||||
|
# para el historial completo) -- solo URLs/config no sensible,
|
||||||
|
# credenciales reales (publicKey/privateKey/pCustIdCliente/pKey) van en
|
||||||
|
# secrets.template.yaml. EPAYCO_ENV=sandbox hasta que haya credenciales
|
||||||
|
# de produccion reales.
|
||||||
|
EPAYCO_ENV: sandbox
|
||||||
|
EPAYCO_RESPONSE_URL: https://shop.cruzcloud.net/checkout/pse/return
|
||||||
|
EPAYCO_NOTIFY_URL: https://commerce.cruzcloud.net/hooks/payment/epayco_pse
|
||||||
|
|
||||||
|
# EnvíoClick (ADR 0009 §2) -- fulfillment provider real por peso/volumen,
|
||||||
|
# reemplaza la tarifa fija. Solo config no sensible; ENVIOCLICK_API_KEY
|
||||||
|
# va en secrets.template.yaml. ENVIOCLICK_SANDBOX=true usa el endpoint
|
||||||
|
# de guía de pruebas (/shipment_sandbox) -- la cotización siempre usa
|
||||||
|
# tarifas reales, no tiene modo sandbox. Origen = bodega Bogotá
|
||||||
|
# ("Bodega principal ARI Shopping", sin dirección física real cargada
|
||||||
|
# todavía -- ENVIOCLICK_ORIGIN_ADDRESS es un placeholder hasta que la
|
||||||
|
# haya).
|
||||||
|
ENVIOCLICK_SANDBOX: "true"
|
||||||
|
ENVIOCLICK_ORIGIN_DANE_CODE: "11001000"
|
||||||
|
ENVIOCLICK_ORIGIN_ADDRESS: "Calle 1 No 1-1"
|
||||||
|
ENVIOCLICK_ORIGIN_COMPANY: "ARI Shopping"
|
||||||
|
ENVIOCLICK_ORIGIN_EMAIL: "[email protected]"
|
||||||
|
ENVIOCLICK_ORIGIN_PHONE: "3000000000"
|
||||||
@@ -65,7 +65,7 @@ spec:
|
|||||||
memory: 64Mi
|
memory: 64Mi
|
||||||
|
|
||||||
- name: migrations
|
- name: migrations
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.218
|
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.229
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
command:
|
command:
|
||||||
- node
|
- node
|
||||||
@@ -86,7 +86,7 @@ spec:
|
|||||||
|
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.218
|
image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.229
|
||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
envFrom:
|
envFrom:
|
||||||
- configMapRef:
|
- configMapRef:
|
||||||
|
|||||||
@@ -35,6 +35,22 @@ stringData:
|
|||||||
# commerce-storefront: el subscriber de Medusa lo envía como header
|
# commerce-storefront: el subscriber de Medusa lo envía como header
|
||||||
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
# x-revalidate-secret al invocar POST /api/revalidate en el storefront.
|
||||||
REVALIDATE_SECRET: CAMBIAR
|
REVALIDATE_SECRET: CAMBIAR
|
||||||
|
|
||||||
|
# ePayco (ADR 0009 -- tercer proveedor evaluado: PayU LatAm quedó
|
||||||
|
# inviable porque Rapyd compró ese negocio en 2023, Rapyd descartado
|
||||||
|
# por costo; ePayco es de Davivienda desde 2024, mejor tarifa PSE para
|
||||||
|
# el volumen real del usuario). Credenciales del comercio real, nunca
|
||||||
|
# hardcodeadas acá. p_cust_id_cliente/p_key son valores propios del
|
||||||
|
# dashboard de ePayco (Configuración > Llaves secretas), distintos de
|
||||||
|
# publicKey/privateKey.
|
||||||
|
EPAYCO_PUBLIC_KEY: CAMBIAR
|
||||||
|
EPAYCO_PRIVATE_KEY: CAMBIAR
|
||||||
|
EPAYCO_P_CUST_ID_CLIENTE: CAMBIAR
|
||||||
|
EPAYCO_P_KEY: CAMBIAR
|
||||||
|
|
||||||
|
# EnvíoClick (ADR 0009 §2) -- API key real de la cuenta
|
||||||
|
# (envioclickpro.com.co > API Key / Desarrolladores).
|
||||||
|
ENVIOCLICK_API_KEY: CAMBIAR
|
||||||
---
|
---
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Secret
|
kind: Secret
|
||||||
|
|||||||
@@ -352,7 +352,11 @@ export function CatalogClient({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-8 lg:grid-cols-[260px_1fr]">
|
<div className="grid gap-8 lg:grid-cols-[260px_1fr]">
|
||||||
<aside className="h-fit space-y-6 rounded-lg border border-slate-100 bg-white p-6 shadow-lg shadow-ari-marino/5 lg:sticky lg:top-44">
|
{/* overflow-y-auto + max-h propio en lg: sticky no le da scroll
|
||||||
|
propio al contenido, y con 30+ categorias mas marca/edad/precio
|
||||||
|
el panel se pasa del viewport sin forma de llegar al resto salvo
|
||||||
|
bajando el zoom del navegador (reportado en vivo). */}
|
||||||
|
<aside className="h-fit space-y-6 overflow-y-auto rounded-lg border border-slate-100 bg-white p-6 shadow-lg shadow-ari-marino/5 lg:sticky lg:top-44 lg:max-h-[calc(100vh-13rem)]">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<strong className="flex items-center gap-2 text-lg font-black">
|
<strong className="flex items-center gap-2 text-lg font-black">
|
||||||
<SlidersHorizontal className="size-5 text-ari-coral-claro" />
|
<SlidersHorizontal className="size-5 text-ari-coral-claro" />
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { ArrowLeft, MapPin, MessageCircle, Truck } from "lucide-react";
|
import { ArrowLeft, Landmark, MapPin, MessageCircle, Truck } from "lucide-react";
|
||||||
import { type FormEvent, useState } from "react";
|
import { type FormEvent, useState } from "react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
@@ -13,11 +13,12 @@ import { useCartStore } from "@/store/cart-store";
|
|||||||
const SELECT_CLASS =
|
const SELECT_CLASS =
|
||||||
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
"h-12 w-full rounded-full border border-slate-200 bg-white px-5 text-sm text-slate-950 outline-none transition focus:border-cyan-500 focus:ring-4 focus:ring-cyan-300/30 disabled:opacity-50";
|
||||||
|
|
||||||
// ADR 0009, siguiente corte tras el carrito real: direccion + seleccion de
|
// ADR 0009: direccion + envio + pago real, todo contra el Store API real.
|
||||||
// envio contra el Store API real (mismos endpoints ya verificados en vivo
|
// El pago es ePayco/PSE (modulo custom del backend, ver
|
||||||
// para las shipping options). El pago (PayU custom) todavia no existe --
|
// workloads/commerce-backend/src/modules/epayco-pse) -- redirige al banco
|
||||||
// el ultimo paso sigue siendo WhatsApp, ahora con el pedido completo
|
// del comprador, la confirmacion real llega despues via webhook async
|
||||||
// (direccion, envio, total real) en vez de solo la lista de productos.
|
// (nunca por esta pantalla). WhatsApp queda como respaldo manual si la
|
||||||
|
// iniciacion del pago falla, ya no como camino principal.
|
||||||
|
|
||||||
interface ShippingOption {
|
interface ShippingOption {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -25,7 +26,12 @@ interface ShippingOption {
|
|||||||
amount: number;
|
amount: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
type Step = "address" | "shipping" | "review";
|
interface PseBank {
|
||||||
|
pseCode: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Step = "address" | "shipping" | "payment";
|
||||||
|
|
||||||
async function postJson(url: string, body: unknown) {
|
async function postJson(url: string, body: unknown) {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
@@ -60,6 +66,11 @@ export function CheckoutClient() {
|
|||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [banks, setBanks] = useState<PseBank[]>([]);
|
||||||
|
const [bankCode, setBankCode] = useState("");
|
||||||
|
const [userType, setUserType] = useState<"0" | "1">("0");
|
||||||
|
const [docType, setDocType] = useState<"CC" | "CE" | "NIT" | "TI" | "PP">("CC");
|
||||||
|
const [docNumber, setDocNumber] = useState("");
|
||||||
|
|
||||||
const itemsSubtotal = items.reduce((sum, item) => sum + (item.product.price ?? 0) * item.quantity, 0);
|
const itemsSubtotal = items.reduce((sum, item) => sum + (item.product.price ?? 0) * item.quantity, 0);
|
||||||
const currency = items[0]?.product.currency;
|
const currency = items[0]?.product.currency;
|
||||||
@@ -77,6 +88,12 @@ export function CheckoutClient() {
|
|||||||
address1: form.address1,
|
address1: form.address1,
|
||||||
city: selectedCiudad.name,
|
city: selectedCiudad.name,
|
||||||
province: selectedDepartamento.name,
|
province: selectedDepartamento.name,
|
||||||
|
// ids DIVIPOLA reales -- EnvioClick (fulfillment provider) los
|
||||||
|
// necesita para cotizar sin ambiguedad, el nombre solo no
|
||||||
|
// alcanza (hay municipios con el mismo nombre en distintos
|
||||||
|
// departamentos).
|
||||||
|
cityId: selectedCiudad.id,
|
||||||
|
departmentId: selectedDepartamento.id,
|
||||||
phone: form.phone,
|
phone: form.phone,
|
||||||
email: form.email,
|
email: form.email,
|
||||||
});
|
});
|
||||||
@@ -103,7 +120,12 @@ export function CheckoutClient() {
|
|||||||
if (cart.error) throw new Error(cart.error);
|
if (cart.error) throw new Error(cart.error);
|
||||||
setShippingTotal(cart.shippingTotal ?? 0);
|
setShippingTotal(cart.shippingTotal ?? 0);
|
||||||
setTotal(cart.total ?? itemsSubtotal);
|
setTotal(cart.total ?? itemsSubtotal);
|
||||||
setStep("review");
|
const banksResponse = await fetch("/api/cart/payment/banks");
|
||||||
|
const banksData = await banksResponse.json();
|
||||||
|
const bankList: PseBank[] = banksData.banks ?? [];
|
||||||
|
setBanks(bankList);
|
||||||
|
setBankCode(bankList[0]?.pseCode ?? "");
|
||||||
|
setStep("payment");
|
||||||
} catch (submitError) {
|
} catch (submitError) {
|
||||||
setError((submitError as Error).message);
|
setError((submitError as Error).message);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -111,6 +133,37 @@ export function CheckoutClient() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function submitPayment(event: FormEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!cartId || !bankCode || !docNumber || !selectedCiudad || !selectedDepartamento) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const session = await postJson("/api/cart/payment/session", {
|
||||||
|
cartId,
|
||||||
|
bankCode,
|
||||||
|
userType,
|
||||||
|
docType,
|
||||||
|
docNumber,
|
||||||
|
firstName: form.firstName,
|
||||||
|
lastName: form.lastName,
|
||||||
|
email: form.email,
|
||||||
|
phone: form.phone,
|
||||||
|
city: selectedCiudad.name,
|
||||||
|
});
|
||||||
|
if (session.error) throw new Error(session.error);
|
||||||
|
const completion = await postJson("/api/cart/complete", { cartId });
|
||||||
|
if (completion.error) throw new Error(completion.error);
|
||||||
|
// Navegacion completa, no iframe -- asi lo exige ePayco para el
|
||||||
|
// flujo de PSE. La confirmacion real llega despues via webhook,
|
||||||
|
// esta pagina nunca vuelve a cargar sola.
|
||||||
|
window.location.href = session.bankUrl;
|
||||||
|
} catch (submitError) {
|
||||||
|
setError((submitError as Error).message);
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function continueOnWhatsApp() {
|
function continueOnWhatsApp() {
|
||||||
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
const lines = items.map((item) => `• ${item.quantity} x ${item.product.name}`).join("\n");
|
||||||
const message = `Hola Ari Shopping 👋\nQuiero confirmar mi pedido:\n\n${lines}\n\nSubtotal: ${formatMoney(itemsSubtotal, currency)}\nEnvío: ${formatMoney(shippingTotal, currency)}\nTotal: ${formatMoney(total, currency)}\n\nNombre: ${form.firstName} ${form.lastName}\nDirección: ${form.address1}, ${selectedCiudad?.name ?? ""}${selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}\nTeléfono: ${form.phone}`;
|
const message = `Hola Ari Shopping 👋\nQuiero confirmar mi pedido:\n\n${lines}\n\nSubtotal: ${formatMoney(itemsSubtotal, currency)}\nEnvío: ${formatMoney(shippingTotal, currency)}\nTotal: ${formatMoney(total, currency)}\n\nNombre: ${form.firstName} ${form.lastName}\nDirección: ${form.address1}, ${selectedCiudad?.name ?? ""}${selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}\nTeléfono: ${form.phone}`;
|
||||||
@@ -192,17 +245,55 @@ export function CheckoutClient() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{step === "review" && (
|
{step === "payment" && (
|
||||||
<div className="mt-8 space-y-4">
|
<form onSubmit={submitPayment} className="mt-8 space-y-4">
|
||||||
<div className="rounded-2xl border border-slate-200 p-5">
|
<div className="rounded-2xl border border-slate-200 p-5">
|
||||||
<p className="text-xs font-black uppercase tracking-wide text-slate-400">Entrega</p>
|
<p className="text-xs font-black uppercase tracking-wide text-slate-400">Entrega</p>
|
||||||
<p className="mt-1 font-bold">{form.firstName} {form.lastName}</p>
|
<p className="mt-1 font-bold">{form.firstName} {form.lastName}</p>
|
||||||
<p className="text-sm text-slate-500">{form.address1}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</p>
|
<p className="text-sm text-slate-500">{form.address1}, {selectedCiudad?.name}{selectedDepartamento ? `, ${selectedDepartamento.name}` : ""}</p>
|
||||||
<p className="text-sm text-slate-500">{form.phone}</p>
|
<p className="text-sm text-slate-500">{form.phone}</p>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-slate-500">El pago en línea todavía no está disponible — confirmamos tu pedido por WhatsApp con estos datos.</p>
|
|
||||||
<Button variant="primary" size="lg" className="w-full" onClick={continueOnWhatsApp}><MessageCircle className="size-5" />Confirmar por WhatsApp</Button>
|
<p className="flex items-center gap-2 text-sm font-bold text-slate-700"><Landmark className="size-4" />Paga con PSE (transferencia desde tu banco)</p>
|
||||||
</div>
|
|
||||||
|
{banks.length > 0 ? (
|
||||||
|
<select required value={bankCode} onChange={(event) => setBankCode(event.target.value)} className={SELECT_CLASS}>
|
||||||
|
{banks.map((bank) => <option key={bank.pseCode} value={bank.pseCode}>{bank.description}</option>)}
|
||||||
|
</select>
|
||||||
|
) : (
|
||||||
|
<p className="rounded-2xl bg-yellow-50 p-3 text-xs font-bold leading-5 text-yellow-800">No pudimos cargar la lista de bancos — probá de nuevo en un momento, o confirmá tu pedido por WhatsApp abajo.</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex gap-4 text-sm font-bold">
|
||||||
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "0"} onChange={() => setUserType("0")} />Persona natural</label>
|
||||||
|
<label className="flex items-center gap-2"><input type="radio" name="userType" checked={userType === "1"} onChange={() => setUserType("1")} />Persona jurídica</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
value={docType}
|
||||||
|
onChange={(event) => setDocType(event.target.value as typeof docType)}
|
||||||
|
className={SELECT_CLASS}
|
||||||
|
>
|
||||||
|
<option value="CC">Cédula de ciudadanía</option>
|
||||||
|
<option value="CE">Cédula de extranjería</option>
|
||||||
|
<option value="TI">Tarjeta de identidad</option>
|
||||||
|
<option value="PP">Pasaporte</option>
|
||||||
|
<option value="NIT">NIT</option>
|
||||||
|
</select>
|
||||||
|
<Input placeholder="Número de documento" required value={docNumber} onChange={(event) => setDocNumber(event.target.value)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && <p className="text-sm font-bold text-rose-600">{error}</p>}
|
||||||
|
|
||||||
|
<Button type="submit" variant="primary" size="lg" className="w-full" disabled={loading || banks.length === 0}>{loading ? "Redirigiendo a tu banco…" : "Pagar con PSE"}</Button>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 text-xs font-bold uppercase tracking-wide text-slate-400">
|
||||||
|
<span className="h-px flex-1 bg-slate-200" />¿Prefieres otra vía?<span className="h-px flex-1 bg-slate-200" />
|
||||||
|
</div>
|
||||||
|
<Button type="button" variant="outline" size="lg" className="w-full" onClick={continueOnWhatsApp}><MessageCircle className="size-5" />Confirmar por WhatsApp</Button>
|
||||||
|
</form>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -219,8 +310,8 @@ export function CheckoutClient() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="mt-5 space-y-2 border-t border-slate-100 pt-4 text-sm">
|
<div className="mt-5 space-y-2 border-t border-slate-100 pt-4 text-sm">
|
||||||
<div className="flex justify-between"><span className="text-slate-500">Subtotal</span><span className="font-bold">{formatMoney(itemsSubtotal, currency)}</span></div>
|
<div className="flex justify-between"><span className="text-slate-500">Subtotal</span><span className="font-bold">{formatMoney(itemsSubtotal, currency)}</span></div>
|
||||||
{step === "review" && <div className="flex justify-between"><span className="text-slate-500">Envío</span><span className="font-bold">{formatMoney(shippingTotal, currency)}</span></div>}
|
{step === "payment" && <div className="flex justify-between"><span className="text-slate-500">Envío</span><span className="font-bold">{formatMoney(shippingTotal, currency)}</span></div>}
|
||||||
<div className="flex justify-between text-base"><span className="font-black">Total</span><span className="font-black">{formatMoney(step === "review" ? total : itemsSubtotal, currency)}</span></div>
|
<div className="flex justify-between text-base"><span className="font-black">Total</span><span className="font-black">{formatMoney(step === "payment" ? total : itemsSubtotal, currency)}</span></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { Clock } from "lucide-react";
|
||||||
|
import { useSearchParams } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
// ePayco redirige aca despues de que el comprador paga en su banco --
|
||||||
|
// esto NO confirma el pago. Los parametros de esta URL son solo
|
||||||
|
// informativos; el estado real y definitivo llega por el webhook async
|
||||||
|
// de ePayco al backend (getWebhookActionAndData en el modulo
|
||||||
|
// epayco-pse), nunca por esta pantalla. Por eso el mensaje nunca afirma
|
||||||
|
// exito, solo que estamos esperando la confirmacion.
|
||||||
|
export function PseReturnClient() {
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const referenceCode = searchParams.get("referenceCode") ?? searchParams.get("reference_sale");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-lg px-4 py-24 text-center">
|
||||||
|
<Clock className="mx-auto size-12 text-ari-marino" />
|
||||||
|
<h1 className="mt-6 text-2xl font-black">Estamos confirmando tu pago</h1>
|
||||||
|
<p className="mt-3 text-slate-500">
|
||||||
|
Tu banco ya procesó la transferencia. ePayco nos avisa en unos minutos si quedó aprobada — te llegará la confirmación por correo.
|
||||||
|
{referenceCode && (
|
||||||
|
<>
|
||||||
|
{" "}Tu número de referencia es <strong>{referenceCode}</strong>.
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
<p className="mt-3 text-sm text-slate-400">
|
||||||
|
Si después de un rato no ves la confirmación, escribinos por WhatsApp con este número de referencia.
|
||||||
|
</p>
|
||||||
|
<Button asChild variant="primary" className="mt-8">
|
||||||
|
<Link href="/catalog">Volver al catálogo</Link>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -199,6 +199,24 @@ function CategoryNavBar({
|
|||||||
function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActive: (name: string) => boolean }) {
|
function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActive: (name: string) => boolean }) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
const cancelClose = () => {
|
||||||
|
if (closeTimer.current) {
|
||||||
|
clearTimeout(closeTimer.current);
|
||||||
|
closeTimer.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// Delay corto en vez de cerrar al toque: aunque el gap entre el boton y
|
||||||
|
// el panel ya se elimino (antes era la causa real -- el panel es
|
||||||
|
// absolute y no suma a la altura del contenedor, asi que un mt-1 ahi
|
||||||
|
// dejaba una franja muerta que cerraba el menu a mitad de camino,
|
||||||
|
// reportado en vivo), este margen extra tolera movimientos rapidos o en
|
||||||
|
// diagonal cerca del borde sin reabrir nada raro.
|
||||||
|
const scheduleClose = () => {
|
||||||
|
cancelClose();
|
||||||
|
closeTimer.current = setTimeout(() => setOpen(false), 200);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
@@ -216,8 +234,15 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
|||||||
};
|
};
|
||||||
}, [open]);
|
}, [open]);
|
||||||
|
|
||||||
|
useEffect(() => () => cancelClose(), []);
|
||||||
|
|
||||||
|
const openNow = () => {
|
||||||
|
cancelClose();
|
||||||
|
setOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={containerRef} className="shrink-0" onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
|
<div ref={containerRef} className="shrink-0" onMouseEnter={openNow} onMouseLeave={scheduleClose}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setOpen((value) => !value)}
|
onClick={() => setOpen((value) => !value)}
|
||||||
@@ -231,7 +256,7 @@ function DepartmentsMegaMenu({ tree, isActive }: { tree: CategoryNode[]; isActiv
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
{open && (
|
{open && (
|
||||||
<div className="absolute left-0 top-full z-50 mt-1 max-h-[80vh] w-[min(92vw,64rem)] overflow-y-auto rounded-2xl border border-white/10 bg-ari-marino p-6 shadow-2xl">
|
<div className="absolute left-0 top-full z-50 max-h-[80vh] w-[min(92vw,64rem)] overflow-y-auto rounded-2xl border border-white/10 bg-ari-marino p-6 shadow-2xl">
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-6">
|
<div className="grid grid-cols-2 gap-x-6 gap-y-5 sm:grid-cols-3 lg:grid-cols-6">
|
||||||
{tree.map((root) => (
|
{tree.map((root) => (
|
||||||
<div key={root.id}>
|
<div key={root.id}>
|
||||||
|
|||||||
@@ -2,19 +2,36 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { Maximize2, Minus, Plus, RotateCcw, ZoomIn } from "lucide-react";
|
import { Maximize2, Minus, Plus, RotateCcw, ZoomIn } from "lucide-react";
|
||||||
import { PointerEvent, WheelEvent, useRef, useState } from "react";
|
import { MouseEvent, PointerEvent, WheelEvent, useRef, useState } from "react";
|
||||||
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
|
||||||
|
|
||||||
interface Offset { x: number; y: number }
|
interface Offset { x: number; y: number }
|
||||||
interface DragState { pointerId: number; startX: number; startY: number; originX: number; originY: number }
|
interface DragState { pointerId: number; startX: number; startY: number; originX: number; originY: number }
|
||||||
|
interface HoverZoomOrigin { x: number; y: number }
|
||||||
|
|
||||||
|
// Zoom automatico al pasar el cursor (estilo lupa clasico de e-commerce)
|
||||||
|
// sobre la imagen principal -- solo mouse (mousemove no dispara de forma
|
||||||
|
// continua en touch, asi que en mobile simplemente no aparece el efecto,
|
||||||
|
// sin romper nada). Independiente del zoom interactivo del modal
|
||||||
|
// (click -> Dialog con scale/drag), que sigue igual.
|
||||||
|
const HOVER_ZOOM_SCALE = 2.2;
|
||||||
|
|
||||||
export function ProductGallery({ images, name }: { images: string[]; name: string }) {
|
export function ProductGallery({ images, name }: { images: string[]; name: string }) {
|
||||||
const [selected, setSelected] = useState(images[0] ?? "");
|
const [selected, setSelected] = useState(images[0] ?? "");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [scale, setScale] = useState(1);
|
const [scale, setScale] = useState(1);
|
||||||
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
|
const [offset, setOffset] = useState<Offset>({ x: 0, y: 0 });
|
||||||
|
const [hoverZoom, setHoverZoom] = useState<HoverZoomOrigin | null>(null);
|
||||||
const drag = useRef<DragState | null>(null);
|
const drag = useRef<DragState | null>(null);
|
||||||
|
|
||||||
|
const trackHoverZoom = (event: MouseEvent<HTMLButtonElement>) => {
|
||||||
|
const rect = event.currentTarget.getBoundingClientRect();
|
||||||
|
setHoverZoom({
|
||||||
|
x: ((event.clientX - rect.left) / rect.width) * 100,
|
||||||
|
y: ((event.clientY - rect.top) / rect.height) * 100,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const applyScale = (next: number) => {
|
const applyScale = (next: number) => {
|
||||||
const value = Math.min(3, Math.max(1, Number(next.toFixed(2))));
|
const value = Math.min(3, Math.max(1, Number(next.toFixed(2))));
|
||||||
setScale(value);
|
setScale(value);
|
||||||
@@ -44,8 +61,24 @@ export function ProductGallery({ images, name }: { images: string[]; name: strin
|
|||||||
</div>
|
</div>
|
||||||
<Dialog open={open} onOpenChange={changeOpen}>
|
<Dialog open={open} onOpenChange={changeOpen}>
|
||||||
<DialogTrigger asChild>
|
<DialogTrigger asChild>
|
||||||
<button type="button" className="group relative order-1 aspect-square overflow-hidden rounded-[2rem] bg-slate-50 lg:order-2">
|
<button
|
||||||
<Image src={selected} alt={name} fill priority sizes="(max-width: 1024px) 100vw, 50vw" className="object-cover transition duration-500 group-hover:scale-[1.03]" />
|
type="button"
|
||||||
|
className="group relative order-1 aspect-square cursor-zoom-in overflow-hidden rounded-[2rem] bg-slate-50 lg:order-2"
|
||||||
|
onMouseMove={trackHoverZoom}
|
||||||
|
onMouseLeave={() => setHoverZoom(null)}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
src={selected}
|
||||||
|
alt={name}
|
||||||
|
fill
|
||||||
|
priority
|
||||||
|
sizes="(max-width: 1024px) 100vw, 50vw"
|
||||||
|
className="object-cover transition-transform duration-150 ease-out"
|
||||||
|
style={{
|
||||||
|
transform: `scale(${hoverZoom ? HOVER_ZOOM_SCALE : 1})`,
|
||||||
|
transformOrigin: hoverZoom ? `${hoverZoom.x}% ${hoverZoom.y}%` : "center",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<span className="absolute bottom-5 right-5 inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-xs font-black shadow-xl"><ZoomIn className="size-4" />Zoom interactivo</span>
|
<span className="absolute bottom-5 right-5 inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-xs font-black shadow-xl"><ZoomIn className="size-4" />Zoom interactivo</span>
|
||||||
</button>
|
</button>
|
||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ spec:
|
|||||||
runAsUser: 1001
|
runAsUser: 1001
|
||||||
containers:
|
containers:
|
||||||
- name: app
|
- name: app
|
||||||
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.216
|
image: gitea.cruzcloud.net/devops/ecommerce-frontend:v1.0.230
|
||||||
env:
|
env:
|
||||||
- name: HEADLESS_PROVIDER
|
- name: HEADLESS_PROVIDER
|
||||||
value: medusa
|
value: medusa
|
||||||
|
|||||||
@@ -46,6 +46,14 @@ export interface ShippingAddressInput {
|
|||||||
province?: string;
|
province?: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
email: string;
|
email: string;
|
||||||
|
// ids DIVIPOLA/DANE reales (lib/data/colombia.ts) -- se guardan en la
|
||||||
|
// metadata de la direccion porque Medusa no tiene un campo propio para
|
||||||
|
// esto. EnvioClick (fulfillment provider real, ver ADR 0009 §2) los
|
||||||
|
// necesita para cotizar/generar guia sin ambiguedad -- el nombre de
|
||||||
|
// ciudad solo no alcanza (hay nombres de municipio repetidos entre
|
||||||
|
// distintos departamentos en Colombia).
|
||||||
|
cityId?: number;
|
||||||
|
departmentId?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ShippingOption {
|
export interface ShippingOption {
|
||||||
@@ -119,7 +127,9 @@ function mapCart(cart: MedusaCart): CartSummary {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function medusaCartFetch(
|
// Exportado para medusa-payment.ts (mismo backend, mismo criterio de
|
||||||
|
// no-store/x-publishable-api-key -- evita duplicar el fetch helper).
|
||||||
|
export async function medusaCartFetch(
|
||||||
path: string,
|
path: string,
|
||||||
init?: { method?: string; body?: unknown },
|
init?: { method?: string; body?: unknown },
|
||||||
): Promise<Record<string, unknown>> {
|
): Promise<Record<string, unknown>> {
|
||||||
@@ -210,6 +220,10 @@ export async function setShippingAddress(
|
|||||||
province: address.province || undefined,
|
province: address.province || undefined,
|
||||||
country_code: "co",
|
country_code: "co",
|
||||||
phone: address.phone,
|
phone: address.phone,
|
||||||
|
metadata:
|
||||||
|
address.cityId || address.departmentId
|
||||||
|
? { cityId: address.cityId, departmentId: address.departmentId }
|
||||||
|
: undefined,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// ADR 0009: pago real via ePayco (PSE) -- tercer proveedor evaluado
|
||||||
|
// (PayU LatAm descartado porque Rapyd compró ese negocio en 2023 y el
|
||||||
|
// registro real quedó con credenciales incompatibles; Rapyd descartado
|
||||||
|
// por costo). ePayco: 100% de Davivienda desde 2024, comisión PSE más
|
||||||
|
// baja para el volumen real del usuario, tarifa preferencial con cuenta
|
||||||
|
// Davivienda. Módulo custom del backend
|
||||||
|
// (workloads/commerce-backend/src/modules/epayco-pse). Archivo separado
|
||||||
|
// de medusa-cart.ts por el mismo motivo que ese archivo esta separado de
|
||||||
|
// medusa.ts -- reutiliza su mismo fetch helper (medusaCartFetch), no
|
||||||
|
// duplica la logica de headers/no-store.
|
||||||
|
import { medusaCartFetch } from "./medusa-cart";
|
||||||
|
|
||||||
|
export interface PseBank {
|
||||||
|
pseCode: string;
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "0" persona natural, "1" persona juridica -- valores reales que espera
|
||||||
|
// ePayco (campo type_person), no un codigo propio nuestro.
|
||||||
|
export type PseUserType = "0" | "1";
|
||||||
|
export type PseDocType = "CC" | "CE" | "NIT" | "TI" | "PP";
|
||||||
|
|
||||||
|
export interface PsePaymentInput {
|
||||||
|
bankCode: string;
|
||||||
|
userType: PseUserType;
|
||||||
|
docType: PseDocType;
|
||||||
|
docNumber: string;
|
||||||
|
firstName: string;
|
||||||
|
lastName: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
city: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "pp_{identifier}_{id}" -- convencion de Medusa, confirmada contra el
|
||||||
|
// codigo fuente de @medusajs/payment (identifier "epayco" + id "pse" en
|
||||||
|
// medusa-config.ts).
|
||||||
|
const PSE_PROVIDER_ID = "pp_epayco_pse";
|
||||||
|
|
||||||
|
export async function getPseBanks(): Promise<PseBank[]> {
|
||||||
|
const data = await medusaCartFetch("/store/payments/pse-banks");
|
||||||
|
const banks = (data.banks as Array<{ pseCode?: string; description?: string }> | undefined) ?? [];
|
||||||
|
return banks
|
||||||
|
.filter((bank): bank is { pseCode: string; description: string } => Boolean(bank.pseCode && bank.description))
|
||||||
|
.map((bank) => ({ pseCode: bank.pseCode, description: bank.description }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPaymentCollection(cartId: string): Promise<string> {
|
||||||
|
const data = await medusaCartFetch("/store/payment-collections", {
|
||||||
|
method: "POST",
|
||||||
|
body: { cart_id: cartId },
|
||||||
|
});
|
||||||
|
const collection = data.payment_collection as { id: string };
|
||||||
|
return collection.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPsePaymentSession(paymentCollectionId: string, input: PsePaymentInput): Promise<string> {
|
||||||
|
const data = await medusaCartFetch(`/store/payment-collections/${paymentCollectionId}/payment-sessions`, {
|
||||||
|
method: "POST",
|
||||||
|
body: {
|
||||||
|
provider_id: PSE_PROVIDER_ID,
|
||||||
|
data: {
|
||||||
|
bank_code: input.bankCode,
|
||||||
|
user_type: input.userType,
|
||||||
|
doc_type: input.docType,
|
||||||
|
doc_number: input.docNumber,
|
||||||
|
first_name: input.firstName,
|
||||||
|
last_name: input.lastName,
|
||||||
|
email: input.email,
|
||||||
|
phone: input.phone,
|
||||||
|
city: input.city,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const collection = data.payment_collection as {
|
||||||
|
payment_sessions?: Array<{ provider_id: string; data?: { bank_url?: string } }>;
|
||||||
|
};
|
||||||
|
const session = collection.payment_sessions?.find((paymentSession) => paymentSession.provider_id === PSE_PROVIDER_ID);
|
||||||
|
const bankUrl = session?.data?.bank_url;
|
||||||
|
if (!bankUrl) {
|
||||||
|
throw new Error("ePayco no devolvió la URL del banco para completar el pago.");
|
||||||
|
}
|
||||||
|
return bankUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// El carrito se completa (orden creada en estado "awaiting") ANTES de
|
||||||
|
// redirigir al banco -- authorizePayment del modulo PSE devuelve
|
||||||
|
// "pending_authorization" a proposito, que es justo el mecanismo de
|
||||||
|
// Medusa para esto (ver AbstractPaymentProvider). La confirmacion real
|
||||||
|
// llega despues via el webhook nativo de Medusa, no por esta llamada.
|
||||||
|
export async function completeCart(cartId: string): Promise<void> {
|
||||||
|
const data = await medusaCartFetch(`/store/carts/${cartId}/complete`, { method: "POST" });
|
||||||
|
if (data.type === "cart") {
|
||||||
|
const error = (data as { error?: { message?: string } }).error;
|
||||||
|
throw new Error(error?.message || "No se pudo completar el pedido.");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user