first commit

This commit is contained in:
Admin 2026-06-30 15:57:49 +07:00
commit 3109f200e1
7 changed files with 1579 additions and 0 deletions

21
.env.example Normal file
View File

@ -0,0 +1,21 @@
# Copy thành .env rồi chỉnh sửa
PORT=8787
MAGENTO_BASE=https://prology.net
# Store theo vị trí client: AU -> 'au', còn lại -> 'us'
# STORES = danh sách store hợp lệ; DEFAULT_STORE = dùng khi không phát hiện được vị trí
STORES=au,us
DEFAULT_STORE=us
MAGENTO_USER=admin
MAGENTO_PASS=Work1234
# Origin được phép gọi API. Khi lên prod nên đặt đúng domain blog, vd:
# ALLOWED_ORIGIN=https://prology.net
# '*' chỉ nên dùng lúc test.
ALLOWED_ORIGIN=*
# Tinh chỉnh
POOL=40
PRODUCTS_TTL=300
STOCK_TTL=60

19
.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
node_modules/
.env
# Logs
logs/
*.log
npm-debug.log*
# OS
.DS_Store
Thumbs.db
# Editor
.vscode/
.idea/
# Build output
dist/
build/

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# Prology Banner sản phẩm liên quan
Banner quảng cáo tự lấy sản phẩm liên quan từ Magento (có ảnh + còn hàng), nhúng vào bài blog WordPress.
> **Kiến trúc an toàn:** script nhúng (public) **KHÔNG** chứa tài khoản/token/REST Magento.
> Mọi thao tác Magento (login, search, lọc tồn kho) nằm ở **server riêng**. Client chỉ gọi endpoint server.
## Cấu trúc
```
prology-product-banner/
├── prology-product-banner.js # Script nhúng vào blog (SERVER-ONLY, không lộ Magento)
├── demo.html # Trang blog mô phỏng để xem thử (cần server chạy)
├── console-test.js # ⚠️ DEV-ONLY: dán tay vào Console để test, chứa creds — KHÔNG nhúng
└── server/ # API Node.js — login Magento + lọc stock + cache + CORS
├── server.js
├── package.json
└── .env.example
```
## 1) Chạy server (bắt buộc)
```bash
cd server
npm install
cp .env.example .env # chỉnh MAGENTO_PASS, ALLOWED_ORIGIN...
npm start # http://localhost:8787
```
Test:
```
http://localhost:8787/api/related-products?q=Catalyst%209300,Catalyst%209200,Cisco&count=16&store=au
```
## 2) Nhúng vào blog
```html
<script>
window.PROLOGY_BANNER = {
endpoint: 'https://your-server/api/related-products' // domain server đã deploy
};
</script>
<script src="prology-product-banner.js" defer></script>
```
Script chỉ gọi `endpoint?q=<keywords>&count=<n>&store=<au|us>` và render kết quả. Không có thông tin Magento nào trong file này.
## 3) Test nhanh khi chưa deploy server (DEV-ONLY)
`console-test.js` cho phép xem thử ngay trên prology.net **mà không cần server** — nhưng nó **chứa tài khoản admin** và gọi Magento trực tiếp.
- Chỉ dùng để **dán tay vào DevTools Console của chính bạn**. F12 → Console → dán → Enter.
- **TUYỆT ĐỐI KHÔNG** nhúng vào trang, không commit lên site, không để lộ cho khách.
## Tuỳ chỉnh (window.PROLOGY_BANNER)
| Option | Mặc định | Ý nghĩa |
|---|---|---|
| `endpoint` | **(bắt buộc)** | URL server của bạn |
| `count` | 16 | Số sản phẩm trong carousel (10-20) |
| `store` | `null` (auto) | `'au'` \| `'us'` \| `null` = tự phát hiện theo vị trí (geo) |
| `keywords` | tự tách từ `<h1>` | Mảng keyword tìm sản phẩm liên quan |
| `placement` | `after-first-table` | `start` \| `end` \| `after-first-table` |
| `mountSelector` | `.entry-content,...` | Vùng nội dung bài viết |
## Store theo vị trí client (AU → `au`, còn lại → `us`)
- **Client**: gọi `/cdn-cgi/trace` (Cloudflare, cùng origin — chỉ là **geo**, không phải thông tin Magento). `loc=AU``au`, khác → `us`. Fallback timezone/locale. Gửi kèm `?store=` cho server.
- **Server**: nhận `?store=`; nếu thiếu → đọc header `CF-IPCountry`; nếu vẫn không có → `DEFAULT_STORE`. Cấu hình `.env`: `STORES=au,us`, `DEFAULT_STORE=us`.
## Ghi chú bảo mật
- **Script public không lộ Magento**: không user/password, không admin token, không URL REST. Tất cả ở server.
- Server: đặt `ALLOWED_ORIGIN=https://prology.net`, để `.env` ngoài repo, nên đặt sau Cloudflare/HTTPS.
- Banner dùng Shadow DOM → CSS không đụng theme WordPress; tự khóa width đúng `.entry-content`.
- Link sản phẩm gắn `rel="nofollow noopener sponsored"`, mở tab mới.

844
package-lock.json generated Normal file
View File

@ -0,0 +1,844 @@
{
"name": "prology-related-products-api",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "prology-related-products-api",
"version": "1.0.0",
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2"
},
"engines": {
"node": ">=18"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
"integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==",
"license": "MIT",
"dependencies": {
"mime-types": "~2.1.34",
"negotiator": "0.6.3"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/body-parser": {
"version": "1.20.5",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz",
"integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"content-type": "~1.0.5",
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "~1.2.0",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"on-finished": "~2.4.1",
"qs": "~6.15.1",
"raw-body": "~2.5.3",
"type-is": "~1.6.18",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
"integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==",
"license": "MIT",
"dependencies": {
"safe-buffer": "5.2.1"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",
"integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",
"license": "MIT"
},
"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/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/destroy": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz",
"integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==",
"license": "MIT",
"engines": {
"node": ">= 0.8",
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://dotenvx.com"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
"integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "4.22.2",
"resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz",
"integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==",
"license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
"body-parser": "~1.20.5",
"content-disposition": "~0.5.4",
"content-type": "~1.0.4",
"cookie": "~0.7.1",
"cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"finalhandler": "~1.3.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
"qs": "~6.15.1",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
"send": "~0.19.0",
"serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
"statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz",
"integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"on-finished": "~2.4.1",
"parseurl": "~1.3.3",
"statuses": "~2.0.2",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
"integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
"integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/merge-descriptors": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz",
"integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/methods": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz",
"integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"license": "MIT",
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"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/negotiator": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
"integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
"integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
"integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==",
"license": "MIT"
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
"integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/qs": {
"version": "6.15.3",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
"integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/raw-body": {
"version": "2.5.3",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz",
"integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.4.24",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
"integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==",
"license": "MIT",
"dependencies": {
"debug": "2.6.9",
"depd": "2.0.0",
"destroy": "1.2.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
"fresh": "~0.5.2",
"http-errors": "~2.0.1",
"mime": "1.6.0",
"ms": "2.1.3",
"on-finished": "~2.4.1",
"range-parser": "~1.2.1",
"statuses": "~2.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/send/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/serve-static": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz",
"integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==",
"license": "MIT",
"dependencies": {
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"parseurl": "~1.3.3",
"send": "~0.19.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/utils-merge": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==",
"license": "MIT",
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
}
}
}

16
package.json Normal file
View File

@ -0,0 +1,16 @@
{
"name": "prology-related-products-api",
"version": "1.0.0",
"description": "Server riêng cho banner sản phẩm liên quan (Magento -> blog WordPress)",
"main": "server.js",
"type": "commonjs",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js"
},
"engines": { "node": ">=18" },
"dependencies": {
"dotenv": "^16.4.5",
"express": "^4.19.2"
}
}

370
prology-product-banner.js Normal file
View File

@ -0,0 +1,370 @@
/* =============================================================================
* Prology Related Products Carousel (vanilla JS, embeddable) [SERVER-ONLY]
* -----------------------------------------------------------------------------
* Public-facing widget. It NEVER touches Magento directly: no admin
* credentials, no admin token, no Magento REST URLs live in this file.
* All of that stays on YOUR server. This script only:
* - detects keywords from the post title
* - detects the visitor's store by geo (au/us) geo only, no Magento info
* - calls YOUR endpoint and renders the returned products in a carousel
*
* EMBED:
* <script>
* window.PROLOGY_BANNER = { endpoint: 'https://your-server/api/related-products' };
* </script>
* <script src="prology-product-banner.js" defer></script>
*
* Your server returns a JSON array of:
* { name, image, url, price, qty } (price already formatted, url absolute)
* See server/server.js for the reference implementation.
* ========================================================================== */
window.PROLOGY_BANNER = {
endpoint: "http://localhost:8787/api/related-products",
};
(function () {
"use strict";
// ----- Defaults (override via window.PROLOGY_BANNER) -----------------------
var CFG = Object.assign(
{
// REQUIRED: your server endpoint (does the Magento login + stock filtering).
endpoint: null,
count: 16, // how many products to show (10-20)
// Keywords for related products. Empty -> auto-detect from the post title.
keywords: null, // e.g. ['Catalyst 9300', 'Catalyst 9200', 'Cisco']
// Store hint passed to the server. null -> detect by visitor geo (au/us).
// This is GEO only (Cloudflare trace); it carries no Magento information.
store: null, // 'au' | 'us' | null = auto-detect
traceUrl: "/cdn-cgi/trace",
// Where to inject: CSS selector of the post content area.
mountSelector: ".entry-content",
// Placement: 'after-first-table' | 'end' | 'start'
placement: "after-first-table",
},
window.PROLOGY_BANNER || {},
);
// ---------------------------------------------------------------------------
// 1. Detect related keywords from the page
// ---------------------------------------------------------------------------
function detectKeywords() {
if (CFG.keywords && CFG.keywords.length) return CFG.keywords.slice();
var h1 = document.querySelector("h1");
var text = ((h1 && h1.textContent) || document.title || "").trim();
var BRANDS = [
"Cisco",
"Catalyst",
"Meraki",
"Aruba",
"HPE",
"Juniper",
"Ubiquiti",
"UniFi",
"Fortinet",
"Netgear",
"MikroTik",
];
var found = [];
var re = /([A-Z][a-zA-Z]+)\s*(\d{3,4}[A-Za-z]?)/g,
m;
while ((m = re.exec(text)) !== null) found.push(m[1] + " " + m[2]);
BRANDS.forEach(function (b) {
if (new RegExp("\\b" + b + "\\b", "i").test(text)) found.push(b);
});
var seen = {},
out = [];
found.forEach(function (k) {
var key = k.toLowerCase();
if (!seen[key]) {
seen[key] = 1;
out.push(k);
}
});
return out.length ? out : ["Cisco"];
}
// ---------------------------------------------------------------------------
// 2. Detect store by visitor geo (AU -> 'au', otherwise -> 'us'). Geo only.
// The server validates this and can override it (e.g. via CF-IPCountry).
// ---------------------------------------------------------------------------
function fallbackStore() {
try {
if (
/Australia/i.test(
Intl.DateTimeFormat().resolvedOptions().timeZone || "",
)
)
return "au";
} catch (e) {}
return /-au\b/i.test(navigator.language || "") ? "au" : "us";
}
function resolveStore() {
if (CFG.store) return Promise.resolve(CFG.store);
return fetch(CFG.traceUrl)
.then(function (r) {
return r.ok ? r.text() : "";
})
.then(function (t) {
var m = /(?:^|\n)loc=([A-Z]{2})/.exec(t || "");
return m ? (m[1] === "AU" ? "au" : "us") : fallbackStore();
})
.catch(fallbackStore);
}
// ---------------------------------------------------------------------------
// 3. Load products from YOUR server (the only network call to your backend)
// ---------------------------------------------------------------------------
function loadProducts(store) {
var q = encodeURIComponent(detectKeywords().join(","));
var sep = CFG.endpoint.indexOf("?") >= 0 ? "&" : "?";
var url =
CFG.endpoint +
sep +
"q=" +
q +
"&count=" +
CFG.count +
(store ? "&store=" + encodeURIComponent(store) : "");
return fetch(url)
.then(function (r) {
return r.json();
})
.then(function (list) {
return Array.isArray(list) ? list : (list && list.items) || [];
});
}
// ---------------------------------------------------------------------------
// 4. Render (Shadow DOM) carousel with prev/next arrows, no header
// ---------------------------------------------------------------------------
var STYLE =
'\
:host{all:initial;display:block!important;width:100%;max-width:100%;min-width:0}\
*{box-sizing:border-box}\
.pb{position:relative;width:100%;max-width:100%;overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;margin:32px 0;color:#0f2747}\
.pb-spon{display:block;text-align:right;font-size:10px;letter-spacing:.6px;text-transform:uppercase;color:#9aa7b8;margin:0 2px 4px}\
.pb-track{display:flex;gap:14px;width:100%;min-width:0;max-width:100%;overflow-x:auto;scroll-snap-type:x mandatory;scroll-behavior:smooth;\
padding:6px 2px 12px;-webkit-overflow-scrolling:touch;scrollbar-width:none}\
.pb-track::-webkit-scrollbar{display:none}\
.pb-card{scroll-snap-align:start;flex:0 0 200px;display:flex;flex-direction:column;\
border:1px solid #eef2f7;border-radius:12px;overflow:hidden;text-decoration:none;color:inherit;background:#fff;\
transition:transform .15s ease,box-shadow .15s ease,border-color .15s ease}\
.pb-card:hover{transform:translateY(-3px);box-shadow:0 10px 22px rgba(16,42,77,.12);border-color:#cfe0f5}\
.pb-thumb{position:relative;aspect-ratio:1/1;background:#f5f8fc;display:flex;align-items:center;justify-content:center}\
.pb-thumb img{width:100%;height:100%;object-fit:contain;padding:10px}\
.pb-stock{position:absolute;top:8px;left:8px;font-size:10px;font-weight:600;color:#0a7d3c;\
background:#e6f7ec;border:1px solid #b6e6c6;border-radius:20px;padding:2px 8px}\
.pb-body{padding:11px 12px 13px;display:flex;flex-direction:column;gap:7px;flex:1}\
.pb-name{font-size:12.5px;line-height:1.35;font-weight:600;color:#13294a;\
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;min-height:34px}\
.pb-foot{margin-top:auto;display:flex;align-items:center;justify-content:space-between;gap:8px}\
.pb-price{font-size:14px;font-weight:800;color:#0a4a8f}\
.pb-cta{font-size:11px;font-weight:700;color:#0a4a8f;background:#eaf2fc;border-radius:7px;padding:5px 9px;white-space:nowrap}\
.pb-card:hover .pb-cta{background:#0a4a8f;color:#fff}\
.pb-nav{position:absolute;top:38%;transform:translateY(-50%);width:40px;height:40px;border-radius:50%;\
border:1px solid #e3e9f1;background:#fff;color:#0a4a8f;cursor:pointer;z-index:3;\
display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px rgba(16,42,77,.16);\
transition:opacity .15s ease,background .15s ease,color .15s ease}\
.pb-nav:hover{background:#0a4a8f;color:#fff}\
.pb-nav svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:2.4;stroke-linecap:round;stroke-linejoin:round}\
.pb-prev{left:6px}.pb-next{right:6px}\
.pb-nav[disabled]{opacity:0;pointer-events:none}\
.pb-empty,.pb-load{padding:26px 20px;text-align:center;color:#6b7a90;font-size:13px}\
.pb-sk{flex:0 0 200px;background:linear-gradient(90deg,#f0f3f8 25%,#e7ecf3 37%,#f0f3f8 63%);\
background-size:400% 100%;animation:pbsh 1.3s ease infinite;border-radius:12px;aspect-ratio:.74/1}\
@keyframes pbsh{0%{background-position:100% 0}100%{background-position:-100% 0}}\
@media(max-width:680px){.pb-card,.pb-sk{flex:0 0 158px}.pb-nav{width:34px;height:34px}.pb-prev{left:4px}.pb-next{right:4px}}\
@media(max-width:380px){.pb-card,.pb-sk{flex:0 0 144px}}';
var ARROW_L = '<svg viewBox="0 0 24 24"><path d="M15 18l-6-6 6-6"/></svg>';
var ARROW_R = '<svg viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></svg>';
function el(host) {
var root = host.attachShadow ? host.attachShadow({ mode: "open" }) : host;
var st = document.createElement("style");
st.textContent = STYLE;
root.appendChild(st);
var wrap = document.createElement("div");
wrap.className = "pb";
root.appendChild(wrap);
return wrap;
}
function esc(s) {
return String(s == null ? "" : s).replace(/[&<>"']/g, function (c) {
return {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
}[c];
});
}
function skeleton(wrap) {
var cards = "";
for (var i = 0; i < 6; i++) cards += '<div class="pb-sk"></div>';
wrap.innerHTML = '<div class="pb-track">' + cards + "</div>";
}
function wireCarousel(wrap) {
var track = wrap.querySelector(".pb-track");
var prev = wrap.querySelector(".pb-prev");
var next = wrap.querySelector(".pb-next");
if (!track || !prev || !next) return;
function stepSize() {
return Math.max(track.clientWidth * 0.85, 200);
}
prev.addEventListener("click", function () {
track.scrollBy({ left: -stepSize(), behavior: "smooth" });
});
next.addEventListener("click", function () {
track.scrollBy({ left: stepSize(), behavior: "smooth" });
});
function update() {
prev.disabled = track.scrollLeft <= 2;
next.disabled =
track.scrollLeft + track.clientWidth >= track.scrollWidth - 2;
}
var host = track.getRootNode().host;
track.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", function () {
fit(host);
update();
});
update();
}
function render(wrap, items) {
if (!items.length) {
wrap.innerHTML =
'<div class="pb-empty">No related products in stock right now.</div>';
return;
}
var cards = items
.map(function (p) {
return (
'<a class="pb-card" href="' +
esc(p.url) +
'" target="_blank" rel="nofollow noopener sponsored">' +
'<div class="pb-thumb">' +
(p.qty ? '<span class="pb-stock">In stock</span>' : "") +
'<img loading="lazy" alt="' +
esc(p.name) +
'" src="' +
esc(p.image) +
'"></div>' +
'<div class="pb-body"><div class="pb-name">' +
esc(p.name) +
"</div>" +
'<div class="pb-foot">' +
(p.price
? '<span class="pb-price">' + esc(p.price) + "</span>"
: "<span></span>") +
'<span class="pb-cta">View</span>' +
"</div></div></a>"
);
})
.join("");
wrap.innerHTML =
'<span class="pb-spon">Sponsored</span>' +
'<button class="pb-nav pb-prev" aria-label="Previous">' +
ARROW_L +
"</button>" +
'<div class="pb-track">' +
cards +
"</div>" +
'<button class="pb-nav pb-next" aria-label="Next">' +
ARROW_R +
"</button>";
wireCarousel(wrap);
}
// ---------------------------------------------------------------------------
// 5. Inject into the page + lock width to the real column (no column blowout)
// ---------------------------------------------------------------------------
function fit(host) {
if (!host || !host.parentNode) return;
host.style.width = "0px"; // collapse -> column reflows to real width
var p = host.parentNode,
cs = getComputedStyle(p);
var w =
p.clientWidth -
(parseFloat(cs.paddingLeft) || 0) -
(parseFloat(cs.paddingRight) || 0);
host.style.width = (w > 0 ? Math.floor(w) : 0) + "px";
}
function mountPoint() {
var host = document.createElement("div");
host.setAttribute("data-prology-banner", "");
host.style.cssText =
"display:block;max-width:100%;min-width:0;box-sizing:border-box;overflow:hidden;";
var container = document.querySelector(CFG.mountSelector);
if (!container) {
document.body.appendChild(host);
return host;
}
if (CFG.placement === "after-first-table") {
var t = container.querySelector("table, figure.wp-block-table");
if (t) {
t.parentNode.insertBefore(host, t.nextSibling);
return host;
}
}
if (CFG.placement === "start") {
container.insertBefore(host, container.firstChild);
return host;
}
container.appendChild(host);
return host;
}
function init() {
if (!CFG.endpoint) {
console.error(
"[Prology Banner] Missing config. Set " +
'window.PROLOGY_BANNER = { endpoint: "https://your-server/api/related-products" } before this script.',
);
return;
}
var host = mountPoint();
fit(host);
var wrap = el(host);
skeleton(wrap);
resolveStore()
.then(function (s) {
return loadProducts(s);
})
.then(function (items) {
render(wrap, items);
})
.catch(function (err) {
console.error("[Prology Banner]", err);
render(wrap, []);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();

236
server.js Normal file
View File

@ -0,0 +1,236 @@
/* =============================================================================
* Prology Related Products API (Node.js / Express)
* -----------------------------------------------------------------------------
* Server riêng đứng giữa blog WordPress Magento, để:
* - Tự login Magento lấy admin token (KHÔNG lộ ra trình duyệt) + cache token
* - Chọn store theo vị trí client: AU -> 'au', còn lại -> 'us'
* - Tìm sản phẩm liên quan theo keyword, lọc: status=1 + ảnh + CÒN HÀNG
* - Random trả về mảng đã chuẩn hóa {name,image,url,price,qty}
* - Bật CORS để trang blog gọi được, không dính CORS
* - Cache kết quả ngắn hạn để giảm tải Magento
*
* CHẠY:
* cd server && npm install && cp .env.example .env (sửa .env nếu cần)
* npm start # mặc định http://localhost:8787
*
* Yêu cầu: Node.js >= 18 (dùng global fetch).
*
* Endpoint:
* GET /api/related-products?q=Catalyst%209300,Cisco&count=16&store=au
* - store: client tự phát hiện (qua Cloudflare /cdn-cgi/trace) rồi gửi lên.
* Nếu thiếu, server fallback theo header CF-IPCountry, rồi tới DEFAULT_STORE.
* ========================================================================== */
'use strict';
const express = require('express');
require('dotenv').config();
const {
PORT = 8787,
MAGENTO_BASE = 'https://prology.net',
// Danh sách store hợp lệ + store mặc định khi không phát hiện được
STORES = 'au,us',
DEFAULT_STORE = 'us',
MAGENTO_USER = 'admin',
MAGENTO_PASS = 'Work1234',
// Origin được phép gọi (vd: https://prology.net). '*' = mọi nơi (chỉ nên dùng khi test)
ALLOWED_ORIGIN = '*',
POOL = '40', // số sản phẩm lấy về để lọc/random
PRODUCTS_TTL = '300', // cache danh sách sản phẩm (giây)
STOCK_TTL = '60', // cache tồn kho (giây)
} = process.env;
const STORE_LIST = STORES.split(',').map((s) => s.trim()).filter(Boolean);
const apiBase = (store) => `${MAGENTO_BASE}/${store}/rest/V1`;
const mediaBase = (store) => `${MAGENTO_BASE}/${store}/media/catalog/product`;
const app = express();
app.set('trust proxy', true);
// ----------------------------- CORS ----------------------------------------
app.use((req, res, next) => {
res.set('Access-Control-Allow-Origin', ALLOWED_ORIGIN);
res.set('Vary', 'Origin');
res.set('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.set('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
// ------------------- Chọn store theo vị trí client -------------------------
function pickStore(req) {
// 1) client tự phát hiện (Cloudflare trace) rồi gửi ?store=
const q = String(req.query.store || '').toLowerCase();
if (STORE_LIST.includes(q)) return q;
// 2) fallback: nếu server đứng sau Cloudflare -> có header CF-IPCountry
const cc = String(req.get('CF-IPCountry') || '').toUpperCase();
if (cc === 'AU') return 'au';
if (cc && cc !== 'XX' && STORE_LIST.includes('us')) return 'us';
// 3) mặc định
return DEFAULT_STORE;
}
// ------------------------- Token (cache + tự gia hạn) -----------------------
let tokenCache = { value: null, exp: 0 };
async function getToken(force = false) {
const now = Date.now();
if (!force && tokenCache.value && now < tokenCache.exp) return tokenCache.value;
// Token admin dùng chung cho mọi store; login qua store mặc định
const r = await fetch(`${apiBase(DEFAULT_STORE)}/integration/admin/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: MAGENTO_USER, password: MAGENTO_PASS }),
});
if (!r.ok) throw new Error(`Magento login failed: ${r.status} ${await r.text()}`);
const token = (await r.json());
// Token Magento mặc định sống ~1h; cache 50 phút cho an toàn
tokenCache = { value: token, exp: now + 50 * 60 * 1000 };
return token;
}
// Gọi Magento (theo store) kèm Bearer, tự refetch token 1 lần nếu gặp 401
async function mget(store, path) {
let token = await getToken();
let r = await fetch(`${apiBase(store)}${path}`, { headers: { Authorization: `Bearer ${token}` } });
if (r.status === 401) {
token = await getToken(true);
r = await fetch(`${apiBase(store)}${path}`, { headers: { Authorization: `Bearer ${token}` } });
}
if (!r.ok) throw new Error(`Magento ${store}${path} -> ${r.status}`);
return r.json();
}
// ------------------------------ Cache nhỏ (TTL) ----------------------------
function makeCache(ttlSec) {
const m = new Map();
return {
get(k) { const e = m.get(k); if (e && Date.now() < e.exp) return e.val; m.delete(k); return null; },
set(k, val) { m.set(k, { val, exp: Date.now() + ttlSec * 1000 }); return val; },
};
}
const prodCache = makeCache(Number(PRODUCTS_TTL));
const stockCache = makeCache(Number(STOCK_TTL));
// ------------------------------- Helpers -----------------------------------
const attr = (it, code) =>
(it.custom_attributes || []).find((c) => c.attribute_code === code)?.value ?? null;
function imageOf(it, store) {
let f = attr(it, 'image') || attr(it, 'small_image');
if (!f || f === 'no_selection') {
const g = (it.media_gallery_entries || []).find((e) => e.media_type === 'image' && !e.disabled);
f = g ? g.file : null;
}
return f ? mediaBase(store) + f : null;
}
function urlOf(it, store) {
const k = attr(it, 'url_key');
return k ? `${MAGENTO_BASE}/${store}/${k}` : `${MAGENTO_BASE}/${store}/`;
}
function priceOf(it, store) {
const v = Number(it.price || 0);
if (!v) return '';
const locale = store === 'au' ? 'en-AU' : 'en-US';
const currency = store === 'au' ? 'AUD' : 'USD';
try {
return new Intl.NumberFormat(locale, { style: 'currency', currency, maximumFractionDigits: 0 }).format(v);
} catch { return '$' + v; }
}
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) { const j = (Math.random() * (i + 1)) | 0; [a[i], a[j]] = [a[j], a[i]]; }
return a;
}
// ------------------------- Magento data access -----------------------------
async function searchByName(store, keyword) {
const ck = `${store}|${keyword}`;
const cached = prodCache.get(ck);
if (cached) return cached;
const p = new URLSearchParams();
p.set('searchCriteria[filterGroups][0][filters][0][field]', 'name');
p.set('searchCriteria[filterGroups][0][filters][0][value]', `%${keyword}%`);
p.set('searchCriteria[filterGroups][0][filters][0][conditionType]', 'like');
p.set('searchCriteria[filterGroups][1][filters][0][field]', 'status');
p.set('searchCriteria[filterGroups][1][filters][0][value]', '1');
p.set('searchCriteria[filterGroups][1][filters][0][conditionType]', 'eq');
p.set('searchCriteria[pageSize]', POOL);
p.set('searchCriteria[currentPage]', '1');
p.set('searchCriteria[sortOrders][0][field]', 'updated_at');
p.set('searchCriteria[sortOrders][0][direction]', 'DESC');
const data = await mget(store, `/products?${p.toString()}`);
return prodCache.set(ck, data.items || []);
}
async function inStock(store, sku) {
const ck = `${store}|${sku}`;
const cached = stockCache.get(ck);
if (cached !== null) return cached;
try {
const s = await mget(store, `/stockItems/${encodeURIComponent(sku)}`);
return stockCache.set(ck, { in_stock: !!s.is_in_stock, qty: s.qty });
} catch {
return stockCache.set(ck, { in_stock: false, qty: 0 });
}
}
// ----------------------------- Endpoint ------------------------------------
app.get('/api/related-products', async (req, res) => {
try {
const store = pickStore(req);
const keywords = String(req.query.q || 'Cisco')
.split(',').map((s) => s.trim()).filter(Boolean);
const count = Math.min(Math.max(parseInt(req.query.count, 10) || 16, 1), 20);
// 1) Gom ứng viên theo nhiều keyword (cụ thể -> tổng quát), khử trùng SKU
const seen = new Set();
const candidates = [];
for (const kw of keywords) {
if (candidates.length >= Number(POOL) * 1.5) break;
let items = [];
try { items = await searchByName(store, kw); } catch (_) { /* bỏ qua keyword lỗi */ }
for (const it of items) {
if (!seen.has(it.sku)) { seen.add(it.sku); candidates.push(it); }
}
}
// 2) Lọc cơ bản: có ảnh + đang bật + không phải "not visible individually"
const usable = shuffle(candidates.filter(
(it) => imageOf(it, store) && Number(it.status) === 1 && Number(it.visibility) !== 1
));
// 3) Random + check tồn kho lazy cho tới khi đủ count
const picked = [];
for (const it of usable) {
if (picked.length >= count) break;
const st = await inStock(store, it.sku);
if (st.in_stock) {
picked.push({
sku: it.sku,
name: it.name,
image: imageOf(it, store),
url: urlOf(it, store),
price: priceOf(it, store),
qty: st.qty,
});
}
}
res.set('Cache-Control', 'public, max-age=60');
res.json(picked);
} catch (err) {
console.error('[related-products]', err);
res.status(500).json({ error: 'failed', message: String(err.message || err) });
}
});
app.get('/health', (_req, res) => res.json({ ok: true, stores: STORE_LIST }));
app.listen(PORT, () => {
console.log(`Prology related-products API: http://localhost:${PORT}`);
console.log(`Stores: ${STORE_LIST.join(', ')} (default: ${DEFAULT_STORE})`);
console.log(`Try: http://localhost:${PORT}/api/related-products?q=Catalyst%209300,Cisco&count=16&store=au`);
});