fix merge conflicts from develop

This commit is contained in:
olivermrbl committed 2021-05-25 15:44:26 +02:00
commit e3343f74a7
251 files changed
+25580 -4521

No files matched your search

@@ -3,6 +3,30 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.3](https://github.com/medusajs/medusa/compare/babel-preset-medusa-package@1.1.0...babel-preset-medusa-package@1.1.3) (2021-04-28)
**Note:** Version bump only for package babel-preset-medusa-package
## [1.1.2](https://github.com/medusajs/medusa/compare/babel-preset-medusa-package@1.1.1...babel-preset-medusa-package@1.1.2) (2021-04-20)
**Note:** Version bump only for package babel-preset-medusa-package
## [1.1.1](https://github.com/medusajs/medusa/compare/babel-preset-medusa-package@1.1.0...babel-preset-medusa-package@1.1.1) (2021-04-20)
**Note:** Version bump only for package babel-preset-medusa-package
# [1.1.0](https://github.com/medusajs/medusa/compare/babel-preset-medusa-package@1.0.1...babel-preset-medusa-package@1.1.0) (2021-01-26)
**Note:** Version bump only for package babel-preset-medusa-package
@@ -1,6 +1,6 @@
{
"name": "babel-preset-medusa-package",
"version": "1.1.0",
"version": "1.1.3",
"author": "Sebastian Rindom <sebastian@mrbltech.com>",
"repository": {
"type": "git",
@@ -26,5 +26,5 @@
"engines": {
"node": ">=10.14.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
+2
View File
@@ -1,2 +1,4 @@
dist/
node_modules/
.env
+1
View File
@@ -3,3 +3,4 @@ src
.eslintrc
.gitignore
.prettierrc
.env
+62
View File
@@ -3,6 +3,68 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.8](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.7...@medusajs/medusa-cli@1.1.8) (2021-05-05)
**Note:** Version bump only for package @medusajs/medusa-cli
## [1.1.7](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.4...@medusajs/medusa-cli@1.1.7) (2021-04-28)
**Note:** Version bump only for package @medusajs/medusa-cli
## [1.1.6](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.5...@medusajs/medusa-cli@1.1.6) (2021-04-20)
**Note:** Version bump only for package @medusajs/medusa-cli
## [1.1.5](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.4...@medusajs/medusa-cli@1.1.5) (2021-04-20)
**Note:** Version bump only for package @medusajs/medusa-cli
## [1.1.4](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.3...@medusajs/medusa-cli@1.1.4) (2021-03-17)
**Note:** Version bump only for package @medusajs/medusa-cli
## [1.1.3](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.0...@medusajs/medusa-cli@1.1.3) (2021-03-17)
### Features
* dev cli ([#203](https://github.com/medusajs/medusa/issues/203)) ([695b1fd](https://github.com/medusajs/medusa/commit/695b1fd0a54a247502cb48ffb73d060356293b76)), closes [#199](https://github.com/medusajs/medusa/issues/199)
## [1.1.2](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.1.0...@medusajs/medusa-cli@1.1.2) (2021-03-17)
### Features
* dev cli ([#203](https://github.com/medusajs/medusa/issues/203)) ([695b1fd](https://github.com/medusajs/medusa/commit/695b1fd0a54a247502cb48ffb73d060356293b76)), closes [#199](https://github.com/medusajs/medusa/issues/199)
# [1.1.0](https://github.com/medusajs/medusa/compare/@medusajs/medusa-cli@1.0.11...@medusajs/medusa-cli@1.1.0) (2021-01-26)
**Note:** Version bump only for package @medusajs/medusa-cli
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
require("./dist/index.js")
+38 -30
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-cli",
"version": "1.1.0",
"version": "1.1.8",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -1795,11 +1795,6 @@
}
}
},
"arch": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/arch/-/arch-2.1.2.tgz",
"integrity": "sha512-NTBIIbAfkJeIletyABbVtdPgeKfDafR+1mZV/AyyfC1UkVkp9iUjV+wwmqtUgphHYajbI86jejBJp5e+jkGTiQ=="
},
"argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
@@ -2298,16 +2293,6 @@
"integrity": "sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==",
"dev": true
},
"clipboardy": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-2.3.0.tgz",
"integrity": "sha512-mKhiIL2DrQIsuXMgBgnfEHOZOryC7kY7YO//TN6c63wlEm3NG5tz+YgY5rVi29KCmq/QQjKYvM7a19+MDOTHOQ==",
"requires": {
"arch": "^2.1.1",
"execa": "^1.0.0",
"is-wsl": "^2.1.1"
}
},
"cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -2437,6 +2422,7 @@
"version": "6.0.5",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz",
"integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==",
"dev": true,
"requires": {
"nice-try": "^1.0.4",
"path-key": "^2.0.1",
@@ -2631,6 +2617,7 @@
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"dev": true,
"requires": {
"once": "^1.4.0"
}
@@ -2919,6 +2906,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz",
"integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==",
"dev": true,
"requires": {
"cross-spawn": "^6.0.0",
"get-stream": "^4.0.0",
@@ -3287,6 +3275,7 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz",
"integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==",
"dev": true,
"requires": {
"pump": "^3.0.0"
}
@@ -3665,7 +3654,9 @@
"is-docker": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.0.0.tgz",
"integrity": "sha512-pJEdRugimx4fBMra5z2/5iRdZ63OhYV0vr0Dwm5+xtW4D1FvRkB8hamMIhnWfyJeDdyr/aa7BDyNbtG38VxgoQ=="
"integrity": "sha512-pJEdRugimx4fBMra5z2/5iRdZ63OhYV0vr0Dwm5+xtW4D1FvRkB8hamMIhnWfyJeDdyr/aa7BDyNbtG38VxgoQ==",
"dev": true,
"optional": true
},
"is-extendable": {
"version": "0.1.1",
@@ -3732,7 +3723,8 @@
"is-stream": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz",
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ="
"integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=",
"dev": true
},
"is-typedarray": {
"version": "1.0.0",
@@ -3750,6 +3742,8 @@
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz",
"integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==",
"dev": true,
"optional": true,
"requires": {
"is-docker": "^2.0.0"
}
@@ -3763,7 +3757,8 @@
"isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA="
"integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=",
"dev": true
},
"isobject": {
"version": "3.0.1",
@@ -5150,7 +5145,8 @@
"nice-try": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz",
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ=="
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==",
"dev": true
},
"node-int64": {
"version": "0.4.0",
@@ -5215,6 +5211,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz",
"integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=",
"dev": true,
"requires": {
"path-key": "^2.0.0"
}
@@ -5302,6 +5299,7 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"dev": true,
"requires": {
"wrappy": "1"
}
@@ -5344,7 +5342,8 @@
"p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
"integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4="
"integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=",
"dev": true
},
"p-limit": {
"version": "2.3.0",
@@ -5421,7 +5420,8 @@
"path-key": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz",
"integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A="
"integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=",
"dev": true
},
"path-parse": {
"version": "1.0.6",
@@ -5540,6 +5540,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
"integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
"dev": true,
"requires": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
@@ -5935,7 +5936,8 @@
"semver": {
"version": "5.7.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz",
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ=="
"integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==",
"dev": true
},
"set-blocking": {
"version": "2.0.0",
@@ -5969,6 +5971,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz",
"integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=",
"dev": true,
"requires": {
"shebang-regex": "^1.0.0"
}
@@ -5976,7 +5979,8 @@
"shebang-regex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz",
"integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM="
"integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=",
"dev": true
},
"shellwords": {
"version": "0.1.1",
@@ -5988,7 +5992,8 @@
"signal-exit": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz",
"integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA=="
"integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==",
"dev": true
},
"sisteransi": {
"version": "1.0.5",
@@ -6357,7 +6362,8 @@
"strip-eof": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz",
"integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8="
"integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=",
"dev": true
},
"strip-final-newline": {
"version": "2.0.0",
@@ -6846,6 +6852,7 @@
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
"integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==",
"dev": true,
"requires": {
"isexe": "^2.0.0"
}
@@ -6874,7 +6881,8 @@
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
"dev": true
},
"write": {
"version": "1.0.3",
@@ -6916,9 +6924,9 @@
"dev": true
},
"y18n": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz",
"integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w=="
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.1.tgz",
"integrity": "sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ=="
},
"yargs": {
"version": "15.3.1",
+3 -3
View File
@@ -1,10 +1,10 @@
{
"name": "@medusajs/medusa-cli",
"version": "1.1.0",
"version": "1.1.8",
"description": "Command Line interface for Medusa Commerce",
"main": "dist/index.js",
"bin": {
"medusa": "dist/index.js"
"medusa": "cli.js"
},
"repository": {
"type": "git",
@@ -48,5 +48,5 @@
"resolve-cwd": "^3.0.0",
"yargs": "^15.3.1"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
+3 -3
View File
@@ -4905,9 +4905,9 @@ xmlchars@^2.1.1:
integrity sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==
y18n@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.0.tgz#95ef94f85ecc81d007c264e190a120f0a3c8566b"
integrity sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==
version "4.0.1"
resolved "https://registry.yarnpkg.com/y18n/-/y18n-4.0.1.tgz#8db2b83c31c5d75099bb890b23f3094891e247d4"
integrity sha512-wNcy4NvjMYL8gogWWYAO7ZFWFfHcbdbE57tZO8e4cbpj8tfUcwrwqSl3ad8HxpYWCdXcJUCeKKZS62Av1affwQ==
yargs-parser@^18.1.1:
version "18.1.3"
+83
View File
@@ -3,6 +3,89 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.6...medusa-core-utils@1.1.9) (2021-04-28)
**Note:** Version bump only for package medusa-core-utils
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.7...medusa-core-utils@1.1.8) (2021-04-20)
**Note:** Version bump only for package medusa-core-utils
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.6...medusa-core-utils@1.1.7) (2021-04-20)
**Note:** Version bump only for package medusa-core-utils
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.5...medusa-core-utils@1.1.6) (2021-04-13)
**Note:** Version bump only for package medusa-core-utils
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.4...medusa-core-utils@1.1.5) (2021-04-09)
**Note:** Version bump only for package medusa-core-utils
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.3...medusa-core-utils@1.1.4) (2021-03-30)
### Bug Fixes
* don't divide zero decimal currencies ([cfab2d4](https://github.com/medusajs/medusa/commit/cfab2d408a296a938266d0989b1de67d060b2ed5))
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.2...medusa-core-utils@1.1.3) (2021-03-17)
**Note:** Version bump only for package medusa-core-utils
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.0...medusa-core-utils@1.1.2) (2021-03-17)
### Features
* **medusa:** Add support for filtering with gt, lt, gte and lte ([#190](https://github.com/medusajs/medusa/issues/190)) ([dd0491f](https://github.com/medusajs/medusa/commit/dd0491f52132aed24f642589b12fcf636b719580))
* **medusa:** cart context ([#201](https://github.com/medusajs/medusa/issues/201)) ([dd7b306](https://github.com/medusajs/medusa/commit/dd7b306333fbe1042f5cf2bed614bce84ea9475f))
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.1.0...medusa-core-utils@1.1.1) (2021-03-17)
### Features
* **medusa:** Add support for filtering with gt, lt, gte and lte ([#190](https://github.com/medusajs/medusa/issues/190)) ([dd0491f](https://github.com/medusajs/medusa/commit/dd0491f52132aed24f642589b12fcf636b719580))
* **medusa:** cart context ([#201](https://github.com/medusajs/medusa/issues/201)) ([dd7b306](https://github.com/medusajs/medusa/commit/dd7b306333fbe1042f5cf2bed614bce84ea9475f))
# [1.1.0](https://github.com/medusajs/medusa/compare/medusa-core-utils@1.0.11...medusa-core-utils@1.1.0) (2021-01-26)
**Note:** Version bump only for package medusa-core-utils
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-core-utils",
"version": "1.1.0",
"version": "1.1.9",
"description": "Core utils for Medusa",
"main": "dist/index.js",
"repository": {
@@ -17,13 +17,13 @@
"author": "Sebastian Rindom",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/cli": "^7.13.0",
"@babel/core": "^7.13.8",
"@babel/plugin-proposal-class-properties": "^7.13.0",
"@babel/plugin-transform-classes": "^7.9.5",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/runtime": "^7.9.6",
"@babel/preset-env": "^7.13.9",
"@babel/runtime": "^7.13.9",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
@@ -33,5 +33,5 @@
"joi": "^17.3.0",
"joi-objectid": "^3.0.1"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -0,0 +1,13 @@
import zeroDecimalCurrencies from "./zero-decimal-currencies"
const humanizeAmount = (amount, currency) => {
let divisor = 100
if (zeroDecimalCurrencies.includes(currency.toLowerCase())) {
divisor = 1
}
return amount / divisor
}
export default humanizeAmount
+2
View File
@@ -5,3 +5,5 @@ export { default as MedusaError } from "./errors"
export { default as getConfigFile } from "./get-config-file"
export { default as createRequireFromPath } from "./create-require-from-path"
export { default as compareObjectsByProp } from "./compare-objects"
export { default as zeroDecimalCurrencies } from "./zero-decimal-currencies"
export { default as humanizeAmount } from "./humanize-amount"
@@ -0,0 +1,20 @@
const zeroDecimalCurrencies = [
"bif",
"clp",
"djf",
"gnf",
"jpy",
"kmf",
"krw",
"mga",
"pyg",
"rwf",
"ugx",
"vnd",
"vuv",
"xaf",
"xof",
"xpf",
]
export default zeroDecimalCurrencies
File diff suppressed because it is too large. Load diff
+3
View File
@@ -0,0 +1,3 @@
{
"presets": [["babel-preset-medusa-package"]]
}
+33
View File
@@ -0,0 +1,33 @@
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git
node_modules
decls
dist
# verdaccio local storage
verdaccio
+3
View File
@@ -0,0 +1,3 @@
src
flow-typed
verdaccio
+66
View File
@@ -0,0 +1,66 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.0.8](https://github.com/medusajs/medusa/compare/medusa-dev-cli@0.0.5...medusa-dev-cli@0.0.8) (2021-04-28)
**Note:** Version bump only for package medusa-dev-cli
## [0.0.7](https://github.com/medusajs/medusa/compare/medusa-dev-cli@0.0.6...medusa-dev-cli@0.0.7) (2021-04-20)
**Note:** Version bump only for package medusa-dev-cli
## [0.0.6](https://github.com/medusajs/medusa/compare/medusa-dev-cli@0.0.5...medusa-dev-cli@0.0.6) (2021-04-20)
**Note:** Version bump only for package medusa-dev-cli
## [0.0.5](https://github.com/medusajs/medusa/compare/medusa-dev-cli@0.0.4...medusa-dev-cli@0.0.5) (2021-04-13)
### Bug Fixes
* working ([a9b1d75](https://github.com/medusajs/medusa/commit/a9b1d75074d2786df6dfca9064b3d9657a664d6d))
* yarn lon ([3c49467](https://github.com/medusajs/medusa/commit/3c4946762c25220c18913f46537f777a55a209ec))
## [0.0.4](https://github.com/medusajs/medusa/compare/medusa-dev-cli@0.0.3...medusa-dev-cli@0.0.4) (2021-03-17)
**Note:** Version bump only for package medusa-dev-cli
## 0.0.3 (2021-03-17)
### Features
* dev cli ([#203](https://github.com/medusajs/medusa/issues/203)) ([695b1fd](https://github.com/medusajs/medusa/commit/695b1fd0a54a247502cb48ffb73d060356293b76)), closes [#199](https://github.com/medusajs/medusa/issues/199)
## 0.0.2 (2021-03-17)
### Features
* dev cli ([#203](https://github.com/medusajs/medusa/issues/203)) ([695b1fd](https://github.com/medusajs/medusa/commit/695b1fd0a54a247502cb48ffb73d060356293b76)), closes [#199](https://github.com/medusajs/medusa/issues/199)
+74
View File
@@ -0,0 +1,74 @@
# medusa-dev-cli
A command-line tool for local Medusa development. When doing development work on
Medusa core, this tool allows you to copy the changes to the various
Medusa packages to Medusa projects.
## Install
`npm install -g medusa-dev-cli`
## Configuration / First time setup
The medusa-dev-cli tool needs to know where your cloned Medusa repository is
located. You typically only need to configure this once.
`medusa-dev --set-path-to-repo /path/to/my/cloned/version/medusa`
## How to use
Navigate to the project you want to link to your forked Medusa repository and
run:
`medusa-dev`
The tool will then scan your project's package.json to find its Medusa
dependencies and copy the latest source from your cloned version of Medusa into
your project's node_modules folder. A watch task is then created to re-copy any
modules that might change while you're working on the code, so you can leave
this program running.
Typically you'll also want to run `npm run watch` in the Medusa repo to set up
watchers to build Medusa source code.
## Revert to current packages
If you've recently run `medusa-dev` your `node_modules` will be out of sync with current published packages. In order to undo this, you can remove the `node_modules` directory or run:
```shell
git checkout package.json; yarn --force
```
or
```shell
git checkout package.json; npm install --force
```
### Other commands
#### `--packages`
You can prevent the automatic dependencies scan and instead specify a list of
packages you want to link by using the `--packages` option:
`medusa-dev --packages @medusajs/medusa medusa-interfaces`
#### `--scan-once`
With this flag, the tool will do an initial scan and copy and then quit. This is
useful for setting up automated testing/builds of Medusa projects from the latest
code.
#### `--quiet`
Don't output anything except for a success message when used together with
`--scan-once`.
#### `--copy-all`
Copy all modules/files in the medusa source repo in packages/
#### `--force-install`
Disables copying files into node_modules and forces usage of local npm repository.
+51
View File
@@ -0,0 +1,51 @@
{
"name": "medusa-dev-cli",
"description": "CLI helpers for contributors working on Medusa",
"version": "0.0.8",
"author": "Sebastian Rindom <skrindom@gmail.com>",
"bin": {
"medusa-dev": "./dist/index.js"
},
"dependencies": {
"@babel/runtime": "^7.12.5",
"chokidar": "^3.5.0",
"configstore": "^5.0.1",
"del": "^6.0.0",
"execa": "^4.1.0",
"find-yarn-workspace-root": "^2.0.0",
"fs-extra": "^9.0.1",
"got": "^10.7.0",
"is-absolute": "^1.0.0",
"lodash": "^4.17.21",
"signal-exit": "^3.0.3",
"verdaccio": "^4.10.0",
"yargs": "^15.4.1"
},
"devDependencies": {
"@babel/cli": "^7.12.1",
"@babel/core": "^7.12.3",
"babel-preset-medusa-package": "^1.1.3",
"cross-env": "^7.0.3"
},
"homepage": "https://github.com/medusajs/medusa/tree/master/packages/medusa-dev-cli#readme",
"keywords": [
"medusa"
],
"license": "MIT",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa.git",
"directory": "packages/medusa-dev-cli"
},
"scripts": {
"build": "babel src --out-dir dist --ignore \"**/__tests__\"",
"prepare": "cross-env NODE_ENV=production npm run build",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "babel -w src --out-dir dist --ignore \"**/__tests__\""
},
"engines": {
"node": ">=12.13.0"
},
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env node
const Configstore = require(`configstore`);
const pkg = require(`../package.json`);
const _ = require(`lodash`);
const path = require(`path`);
const os = require(`os`);
const watch = require(`./watch`);
const { getVersionInfo } = require(`./utils/version`);
const argv = require(`yargs`)
.usage(`Usage: medusa-dev [options]`)
.alias(`q`, `quiet`)
.nargs(`q`, 0)
.describe(`q`, `Do not output copy file information`)
.alias(`s`, `scan-once`)
.nargs(`s`, 0)
.describe(`s`, `Scan once. Do not start file watch`)
.alias(`p`, `set-path-to-repo`)
.nargs(`p`, 1)
.describe(
`p`,
`Set path to Medusa repository.
You typically only need to configure this once.`
)
.nargs(`force-install`, 0)
.describe(
`force-install`,
`Disables copying files into node_modules and forces usage of local npm repository.`
)
.alias(`C`, `copy-all`)
.nargs(`C`, 0)
.describe(
`C`,
`Copy all contents in packages/ instead of just medusa packages`
)
.array(`packages`)
.describe(`packages`, `Explicitly specify packages to copy`)
.help(`h`)
.alias(`h`, `help`)
.nargs(`v`, 0)
.alias(`v`, `version`)
.describe(`v`, `Print the currently installed version of Medusa Dev CLI`)
.argv;
if (argv.version) {
console.log(getVersionInfo());
process.exit();
}
const conf = new Configstore(pkg.name);
const fs = require(`fs-extra`);
let pathToRepo = argv.setPathToRepo;
if (pathToRepo) {
if (pathToRepo.includes(`~`)) {
pathToRepo = path.join(os.homedir(), pathToRepo.split(`~`).pop());
}
conf.set(`medusa-location`, path.resolve(pathToRepo));
process.exit();
}
const havePackageJsonFile = fs.existsSync(`package.json`);
if (!havePackageJsonFile) {
console.error(`Current folder must have a package.json file!`);
process.exit();
}
const medusaLocation = conf.get(`medusa-location`);
if (!medusaLocation) {
console.error(
`
You haven't set the path yet to your cloned
version of medusa. Do so now by running:
medusa-dev --set-path-to-repo /path/to/my/cloned/version/medusa
`
);
process.exit();
}
// get list of packages from monorepo
const monoRepoPackages = [];
const pkgsDirs = fs.readdirSync(path.join(medusaLocation, `packages`));
for (const dir of pkgsDirs) {
const pack = JSON.parse(
fs.readFileSync(path.join(medusaLocation, `packages`, dir, `package.json`))
);
monoRepoPackages.push(pack.name);
}
const localPkg = JSON.parse(fs.readFileSync(`package.json`));
// intersect dependencies with monoRepoPackages to get list of packages that are used
const localPackages = _.intersection(
monoRepoPackages,
Object.keys(_.merge({}, localPkg.dependencies, localPkg.devDependencies))
);
if (!argv.packages && _.isEmpty(localPackages)) {
console.error(
`
You haven't got any medusa dependencies into your current package.json
You probably want to pass in a list of packages to start
developing on! For example:
medusa-dev --packages @medusajs/medusa
If you prefer to place them in your package.json dependencies instead,
medusa-dev will pick them up.
`
);
if (!argv.forceInstall) {
process.exit();
} else {
console.log(
`Continuing other dependencies installation due to "--forceInstall" flag`
);
}
}
watch(medusaLocation, argv.packages, {
localPackages,
quiet: argv.quiet,
scanOnce: argv.scanOnce,
forceInstall: argv.forceInstall,
monoRepoPackages,
});
@@ -0,0 +1,19 @@
const signalExit = require(`signal-exit`);
const cleanupTasks = new Set();
exports.registerCleanupTask = (taskFn) => {
cleanupTasks.add(taskFn);
return () => {
const result = taskFn();
cleanupTasks.delete(taskFn);
return result;
};
};
signalExit(() => {
if (cleanupTasks.size) {
console.log(`Process exitted in middle of publishing - cleaning up`);
cleanupTasks.forEach((taskFn) => taskFn());
}
});
@@ -0,0 +1,75 @@
const startVerdaccio = require(`verdaccio`).default;
const fs = require(`fs-extra`);
const _ = require(`lodash`);
let VerdaccioInitPromise = null;
const { verdaccioConfig } = require(`./verdaccio-config`);
const { publishPackage } = require(`./publish-package`);
const { installPackages } = require(`./install-packages`);
const startServer = () => {
if (VerdaccioInitPromise) {
return VerdaccioInitPromise;
}
console.log(`Starting local verdaccio server`);
// clear storage
fs.removeSync(verdaccioConfig.storage);
VerdaccioInitPromise = new Promise((resolve) => {
startVerdaccio(
verdaccioConfig,
verdaccioConfig.port,
verdaccioConfig.storage,
`1.0.0`,
`medusa-dev`,
(webServer, addr, pkgName, pkgVersion) => {
// console.log(webServer)
webServer.listen(addr.port || addr.path, addr.host, () => {
console.log(`Started local verdaccio server`);
resolve();
});
}
);
});
return VerdaccioInitPromise;
};
exports.startVerdaccio = startServer;
exports.publishPackagesLocallyAndInstall = async ({
packagesToPublish,
localPackages,
root,
ignorePackageJSONChanges,
yarnWorkspaceRoot,
}) => {
await startServer();
const versionPostFix = Date.now();
const newlyPublishedPackageVersions = {};
for (const packageName of packagesToPublish) {
newlyPublishedPackageVersions[packageName] = await publishPackage({
packageName,
packagesToPublish,
root,
versionPostFix,
ignorePackageJSONChanges,
});
}
const packagesToInstall = _.intersection(packagesToPublish, localPackages);
await installPackages({
packagesToInstall,
yarnWorkspaceRoot,
newlyPublishedPackageVersions,
});
};
@@ -0,0 +1,151 @@
const path = require(`path`)
const fs = require(`fs-extra`)
const { promisifiedSpawn } = require(`../utils/promisified-spawn`)
const { registryUrl } = require(`./verdaccio-config`)
const installPackages = async ({
packagesToInstall,
yarnWorkspaceRoot,
newlyPublishedPackageVersions,
}) => {
console.log(
`Installing packages from local registry:\n${packagesToInstall
.map(packageAndVersion => ` - ${packageAndVersion}`)
.join(`\n`)}`
)
let installCmd
if (yarnWorkspaceRoot) {
// this is very hacky - given root, we run `yarn workspaces info`
// to get list of all workspaces and their locations, and manually
// edit package.json file for packages we want to install
// to make sure there are no mismatched versions of same package
// in workspaces which should preserve node_modules structure
// (packages being mostly hoisted to top-level node_modules)
const { stdout } = await promisifiedSpawn([
`yarn`,
[`workspaces`, `info`, `--json`],
{ stdio: `pipe` },
])
let workspacesLayout
try {
workspacesLayout = JSON.parse(JSON.parse(stdout).data)
} catch (e) {
/*
Yarn 1.22 doesn't output pure json - it has leading and trailing text:
```
$ yarn workspaces info --json
yarn workspaces v1.22.0
{
"z": {
"location": "z",
"workspaceDependencies": [],
"mismatchedWorkspaceDependencies": []
},
"y": {
"location": "y",
"workspaceDependencies": [],
"mismatchedWorkspaceDependencies": []
}
}
Done in 0.48s.
```
So we need to do some sanitization. We find JSON by matching substring
that starts with `{` and ends with `}`
*/
const regex = /^[^{]*({.*})[^}]*$/gs
const sanitizedStdOut = regex.exec(stdout)
if (sanitizedStdOut?.length >= 2) {
// pick content of first (and only) capturing group
const jsonString = sanitizedStdOut[1]
try {
workspacesLayout = JSON.parse(jsonString)
} catch (e) {
console.error(
`Failed to parse "sanitized" output of "yarn workspaces info" command.\n\nSanitized string: "${jsonString}`
)
// not exitting here, because we have general check for `workspacesLayout` being set below
}
}
}
if (!workspacesLayout) {
console.error(
`Couldn't parse output of "yarn workspaces info" command`,
stdout
)
process.exit(1)
}
const handleDeps = deps => {
if (!deps) {
return false
}
let changed = false
Object.keys(deps).forEach(depName => {
if (packagesToInstall.includes(depName)) {
deps[depName] = `gatsby-dev`
changed = true
}
})
return changed
}
Object.keys(workspacesLayout).forEach(workspaceName => {
const { location } = workspacesLayout[workspaceName]
const pkgJsonPath = path.join(yarnWorkspaceRoot, location, `package.json`)
if (!fs.existsSync(pkgJsonPath)) {
return
}
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, `utf8`))
let changed = false
changed |= handleDeps(pkg.dependencies)
changed |= handleDeps(pkg.devDependencies)
changed |= handleDeps(pkg.peerDependencies)
if (changed) {
console.log(`Changing deps in ${pkgJsonPath} to use @gatsby-dev`)
fs.outputJSONSync(pkgJsonPath, pkg, {
spaces: 2,
})
}
})
// package.json files are changed - so we just want to install
// using verdaccio registry
installCmd = [
`yarn`,
[`install`, `--registry=${registryUrl}`, `--ignore-engines`],
]
} else {
installCmd = [
`yarn`,
[
`add`,
...packagesToInstall.map(packageName => {
const packageVersion = newlyPublishedPackageVersions[packageName]
return `${packageName}@${packageVersion}`
}),
`--registry=${registryUrl}`,
`--exact`,
`--ignore-engines`,
],
]
}
try {
await promisifiedSpawn(installCmd)
console.log(`Installation complete`)
} catch (error) {
console.error(`Installation failed`, error)
process.exit(1)
}
}
exports.installPackages = installPackages
@@ -0,0 +1,153 @@
const fs = require(`fs-extra`);
const path = require(`path`);
const { promisifiedSpawn } = require(`../utils/promisified-spawn`);
const { registryUrl } = require(`./verdaccio-config`);
const NPMRCContent = `${registryUrl.replace(
/https?:/g,
``
)}/:_authToken="medusa-dev"`;
const {
getMonorepoPackageJsonPath,
} = require(`../utils/get-monorepo-package-json-path`);
const { registerCleanupTask } = require(`./cleanup-tasks`);
/**
* Edit package.json to:
* - adjust version to temporary one
* - change version selectors for dependencies that
* will be published, to make sure that yarn
* install them in local site
*/
const adjustPackageJson = ({
monoRepoPackageJsonPath,
packageName,
versionPostFix,
packagesToPublish,
ignorePackageJSONChanges,
root,
}) => {
// we need to check if package depend on any other package to will be published and
// adjust version selector to point to dev version of package so local registry is used
// for dependencies.
const monorepoPKGjsonString = fs.readFileSync(
monoRepoPackageJsonPath,
`utf-8`
);
const monorepoPKGjson = JSON.parse(monorepoPKGjsonString);
monorepoPKGjson.version = `${monorepoPKGjson.version}-dev-${versionPostFix}`;
packagesToPublish.forEach((packageThatWillBePublished) => {
if (
monorepoPKGjson.dependencies &&
monorepoPKGjson.dependencies[packageThatWillBePublished]
) {
const currentVersion = JSON.parse(
fs.readFileSync(
getMonorepoPackageJsonPath({
packageName: packageThatWillBePublished,
root,
}),
`utf-8`
)
).version;
monorepoPKGjson.dependencies[
packageThatWillBePublished
] = `${currentVersion}-dev-${versionPostFix}`;
}
});
const temporaryMonorepoPKGjsonString = JSON.stringify(monorepoPKGjson);
const unignorePackageJSONChanges = ignorePackageJSONChanges(packageName, [
monorepoPKGjsonString,
temporaryMonorepoPKGjsonString,
]);
// change version and dependency versions
fs.outputFileSync(monoRepoPackageJsonPath, temporaryMonorepoPKGjsonString);
return {
newPackageVersion: monorepoPKGjson.version,
unadjustPackageJson: registerCleanupTask(() => {
// restore original package.json
fs.outputFileSync(monoRepoPackageJsonPath, monorepoPKGjsonString);
unignorePackageJSONChanges();
}),
};
};
/**
* Anonymous publishing require dummy .npmrc
* See https://github.com/verdaccio/verdaccio/issues/212#issuecomment-308578500
* This is `npm publish` (as in linked comment) and `yarn publish` requirement.
* This is not verdaccio restriction.
*/
const createTemporaryNPMRC = ({ pathToPackage }) => {
const NPMRCPath = path.join(pathToPackage, `.npmrc`);
fs.outputFileSync(NPMRCPath, NPMRCContent);
return registerCleanupTask(() => {
fs.removeSync(NPMRCPath);
});
};
const publishPackage = async ({
packageName,
packagesToPublish,
root,
versionPostFix,
ignorePackageJSONChanges,
}) => {
const monoRepoPackageJsonPath = getMonorepoPackageJsonPath({
packageName,
root,
});
const { unadjustPackageJson, newPackageVersion } = adjustPackageJson({
monoRepoPackageJsonPath,
packageName,
root,
versionPostFix,
packagesToPublish,
ignorePackageJSONChanges,
});
const pathToPackage = path.dirname(monoRepoPackageJsonPath);
const uncreateTemporaryNPMRC = createTemporaryNPMRC({ pathToPackage });
// npm publish
const publishCmd = [
`npm`,
[`publish`, `--tag`, `medusa-dev`, `--registry=${registryUrl}`],
{
cwd: pathToPackage,
},
];
console.log(
`Publishing ${packageName}@${newPackageVersion} to local registry`
);
try {
await promisifiedSpawn(publishCmd);
console.log(
`Published ${packageName}@${newPackageVersion} to local registry`
);
} catch (e) {
console.error(`Failed to publish ${packageName}@${newPackageVersion}`, e);
process.exit(1);
}
uncreateTemporaryNPMRC();
unadjustPackageJson();
return newPackageVersion;
};
exports.publishPackage = publishPackage;
@@ -0,0 +1,33 @@
const path = require(`path`)
const os = require(`os`)
const verdaccioConfig = {
storage: path.join(os.tmpdir(), `verdaccio`, `storage`),
port: 4873, // default
max_body_size: `1000mb`,
web: {
enable: true,
title: `gatsby-dev`,
},
logs: [{ type: `stdout`, format: `pretty-timestamped`, level: `warn` }],
packages: {
"**": {
access: `$all`,
publish: `$all`,
proxy: `npmjs`,
},
},
uplinks: {
npmjs: {
url: `https://registry.npmjs.org/`,
// default is 2 max_fails - on flaky networks that cause a lot of failed installations
max_fails: 10,
},
},
}
exports.verdaccioConfig = verdaccioConfig
const registryUrl = `http://localhost:${verdaccioConfig.port}`
exports.registryUrl = registryUrl
@@ -0,0 +1,29 @@
const { getDependantPackages } = require(`../get-dependant-packages`)
describe(`getDependantPackages`, () => {
it(`handles deep dependency chains`, () => {
const packagesToPublish = getDependantPackages({
packageName: `package-a-dep1-dep1`,
depTree: {
"package-a-dep1": new Set([`package-a`]),
"package-a-dep1-dep1": new Set([`package-a-dep1`]),
"not-related": new Set([`also-not-related`]),
},
})
expect(packagesToPublish).toEqual(
new Set([`package-a`, `package-a-dep1`, `package-a-dep1-dep1`])
)
})
it(`doesn't get stuck in circular dependency loops`, () => {
const packagesToPublish = getDependantPackages({
packageName: `package-a`,
depTree: {
"package-a": new Set([`package-b`]),
"package-b": new Set([`package-a`]),
},
})
expect(packagesToPublish).toEqual(new Set([`package-a`, `package-b`]))
})
})
@@ -0,0 +1,68 @@
const path = require(`path`)
const { traversePackagesDeps } = require(`../traverse-package-deps`)
jest.doMock(
path.join(...`<monorepo-path>/packages/package-a/package.json`.split(`/`)),
() => {
return {
dependencies: {
"unrelated-package": `*`,
"package-a-dep1": `*`,
},
}
},
{ virtual: true }
)
jest.doMock(
path.join(
...`<monorepo-path>/packages/package-a-dep1/package.json`.split(`/`)
),
() => {
return {
dependencies: {
"package-a-dep1-dep1": `*`,
},
}
},
{ virtual: true }
)
jest.doMock(
path.join(
...`<monorepo-path>/packages/package-a-dep1-dep1/package.json`.split(`/`)
),
() => {
return {
dependencies: {},
}
},
{ virtual: true }
)
describe(`traversePackageDeps`, () => {
it(`handles deep dependency chains`, () => {
const { seenPackages, depTree } = traversePackagesDeps({
root: `<monorepo-path>`,
packages: [`package-a`, `doesnt-exist`],
monoRepoPackages: [
`package-a`,
`package-a-dep1`,
`package-a-dep1-dep1`,
`package-not-used`,
],
})
expect(seenPackages).toEqual([
`package-a`,
`package-a-dep1`,
`package-a-dep1-dep1`,
])
expect(depTree).toEqual({
"package-a-dep1": new Set([`package-a`]),
"package-a-dep1-dep1": new Set([`package-a-dep1`]),
})
})
})
@@ -0,0 +1,190 @@
const fs = require(`fs-extra`);
const _ = require(`lodash`);
const {
getMonorepoPackageJsonPath,
} = require(`./get-monorepo-package-json-path`);
const got = require(`got`);
function difference(object, base) {
function changes(object, base) {
return _.transform(object, function (result, value, key) {
if (!_.isEqual(value, base[key])) {
result[key] =
_.isObject(value) && _.isObject(base[key])
? changes(value, base[key])
: value;
}
});
}
return changes(object, base);
}
/**
* Compare dependencies of installed packages and monorepo package.
* It will skip dependencies that are removed in monorepo package.
*
* If local package is not installed, it will check unpkg.com.
* This allow medusa-dev to skip publishing unnecesairly and
* let install packages from public npm repository if nothing changed.
*/
exports.checkDepsChanges = async ({
newPath,
packageName,
monoRepoPackages,
root,
isInitialScan,
ignoredPackageJSON,
}) => {
let localPKGjson;
let packageNotInstalled = false;
try {
localPKGjson = JSON.parse(fs.readFileSync(newPath, `utf-8`));
} catch {
packageNotInstalled = true;
// there is no local package - so we still need to install deps
// this is nice because devs won't need to do initial package installation - we can handle this.
if (!isInitialScan) {
console.log(
`'${packageName}' doesn't seem to be installed. Restart medusa-dev to publish it`
);
return {
didDepsChanged: false,
packageNotInstalled,
};
}
// if package is not installed, we will do http GET request to
// unkpg to check if dependency in package published in public
// npm repository are different
// this allow us to not publish to local repository
// and save some time/work
try {
const response = await got(
`https://unpkg.com/${packageName}/package.json`
);
if (response?.statusCode !== 200) {
throw new Error(`No response or non 200 code`);
}
localPKGjson = JSON.parse(response.body);
} catch {
console.log(
`'${packageName}' doesn't seem to be installed and is not published on NPM.`
);
return {
didDepsChanged: true,
packageNotInstalled,
};
}
}
const monoDir = packageName.startsWith("@medusajs")
? packageName.split("/")[1]
: packageName;
const monoRepoPackageJsonPath = getMonorepoPackageJsonPath({
packageName: monoDir,
root,
});
const monorepoPKGjsonString = fs.readFileSync(
monoRepoPackageJsonPath,
`utf-8`
);
const monorepoPKGjson = JSON.parse(monorepoPKGjsonString);
if (ignoredPackageJSON.has(packageName)) {
if (ignoredPackageJSON.get(packageName).includes(monorepoPKGjsonString)) {
// we are in middle of publishing and content of package.json is one set during publish process,
// so we need to not cause false positives
return {
didDepsChanged: false,
packageNotInstalled,
};
}
}
if (!monorepoPKGjson.dependencies) monorepoPKGjson.dependencies = {};
if (!localPKGjson.dependencies) localPKGjson.dependencies = {};
const areDepsEqual = _.isEqual(
monorepoPKGjson.dependencies,
localPKGjson.dependencies
);
if (!areDepsEqual) {
const diff = difference(
monorepoPKGjson.dependencies,
localPKGjson.dependencies
);
const diff2 = difference(
localPKGjson.dependencies,
monorepoPKGjson.dependencies
);
let needPublishing = false;
let isPublishing = false;
const depChangeLog = _.uniq(Object.keys({ ...diff, ...diff2 }))
.reduce((acc, key) => {
if (monorepoPKGjson.dependencies[key] === `medusa-dev`) {
// if we are in middle of publishing to local repository - ignore
isPublishing = true;
return acc;
}
if (localPKGjson.dependencies[key] === `medusa-dev`) {
// monorepo packages will restore version, but after installation
// in local site - it will use `medusa-dev` dist tag - we need
// to ignore changes that
return acc;
}
if (
localPKGjson.dependencies[key] &&
monorepoPKGjson.dependencies[key]
) {
// Check only for version changes in packages
// that are not from medusa repo.
// Changes in medusa packages will be copied over
// from monorepo - and if those contain other dependency
// changes - they will be covered
if (!monoRepoPackages.includes(key)) {
acc.push(
` - '${key}' changed version from ${localPKGjson.dependencies[key]} to ${monorepoPKGjson.dependencies[key]}`
);
needPublishing = true;
}
} else if (monorepoPKGjson.dependencies[key]) {
acc.push(
` - '${key}@${monorepoPKGjson.dependencies[key]}' was added`
);
needPublishing = true;
} else {
acc.push(` - '${key}@${localPKGjson.dependencies[key]}' was removed`);
// this doesn't need publishing really, so will skip this
}
return acc;
}, [])
.join(`\n`);
if (!isPublishing && depChangeLog.length > 0) {
console.log(`Dependencies of '${packageName}' changed:\n${depChangeLog}`);
if (isInitialScan) {
console.log(
`Will ${!needPublishing ? `not ` : ``}publish to local npm registry.`
);
} else {
console.warn(
`Installation of dependencies after initial scan is not implemented`
);
}
return {
didDepsChanged: needPublishing,
packageNotInstalled,
};
}
}
return {
didDepsChanged: false,
packageNotInstalled,
};
};
@@ -0,0 +1,30 @@
/**
* Recursively get set of packages that depend on given package.
* Set also includes passed package.
*/
const getDependantPackages = ({
packageName,
depTree,
packagesToPublish = new Set(),
}) => {
if (packagesToPublish.has(packageName)) {
// bail early if package was already handled
return packagesToPublish
}
packagesToPublish.add(packageName)
const dependants = depTree[packageName]
if (dependants) {
dependants.forEach(dependant =>
getDependantPackages({
packageName: dependant,
depTree,
packagesToPublish,
})
)
}
return packagesToPublish
}
exports.getDependantPackages = getDependantPackages
@@ -0,0 +1,11 @@
const path = require(`path`);
exports.getMonorepoPackageJsonPath = ({ packageName, root }) => {
let dirName = packageName;
if (packageName.startsWith("@medusajs")) {
const [, directory] = packageName.split("/");
dirName = directory;
}
return path.join(root, `packages`, dirName, `package.json`);
};
@@ -0,0 +1,29 @@
const execa = require(`execa`)
const defaultSpawnArgs = {
cwd: process.cwd(),
stdio: `inherit`,
}
exports.setDefaultSpawnStdio = stdio => {
defaultSpawnArgs.stdio = stdio
}
exports.promisifiedSpawn = async ([cmd, args = [], spawnArgs = {}]) => {
const spawnOptions = {
...defaultSpawnArgs,
...spawnArgs,
}
try {
return await execa(cmd, args, spawnOptions)
} catch (e) {
if (spawnOptions.stdio === `ignore`) {
console.log(
`\nCommand "${cmd} ${args.join(
` `
)}" failed.\nTo see details of failed command, rerun "medusa-dev" without "--quiet" or "-q" switch\n`
)
}
throw e
}
}
@@ -0,0 +1,76 @@
const _ = require(`lodash`);
const path = require(`path`);
/**
* @typedef {Object} TraversePackagesDepsReturn
* @property {Object} depTree Lookup table to check dependants for given package.
* Used to determine which packages need to be published.
*/
/**
* Compile final list of packages to watch
* This will include packages explicitly defined packages and all their dependencies
* Also creates dependency graph that is used later to determine which packages
* would need to be published when their dependencies change
* @param {Object} $0
* @param {String} $0.root Path to root of medusa monorepo repository
* @param {String[]} $0.packages Initial array of packages to watch
* This can be extracted from project dependencies or explicitly set by `--packages` flag
* @param {String[]} $0.monoRepoPackages Array of packages in medusa monorepo
* @param {String[]} [$0.seenPackages] Array of packages that were already traversed.
* This makes sure dependencies are extracted one time for each package and avoid any
* infinite loops.
* @param {DepTree} [$0.depTree] Used internally to recursively construct dependency graph.
* @return {TraversePackagesDepsReturn}
*/
const traversePackagesDeps = ({
root,
packages,
monoRepoPackages,
seenPackages = [...packages],
depTree = {},
}) => {
packages.forEach((p) => {
if (p.startsWith("@medusajs")) {
p = p.split("/")[1];
}
let pkgJson;
try {
pkgJson = require(path.join(root, `packages`, p, `package.json`));
} catch {
console.error(`"${p}" package doesn't exist in monorepo.`);
// remove from seenPackages
seenPackages = seenPackages.filter((seenPkg) => seenPkg !== p);
return;
}
const fromMonoRepo = _.intersection(
Object.keys({ ...pkgJson.dependencies }),
monoRepoPackages
);
fromMonoRepo.forEach((pkgName) => {
depTree[pkgName] = (depTree[pkgName] || new Set()).add(p);
});
// only traverse not yet seen packages to avoid infinite loops
const newPackages = _.difference(fromMonoRepo, seenPackages);
if (newPackages.length) {
newPackages.forEach((depFromMonorepo) => {
seenPackages.push(depFromMonorepo);
});
traversePackagesDeps({
root,
packages: fromMonoRepo,
monoRepoPackages,
seenPackages,
depTree,
});
}
});
return { seenPackages, depTree };
};
exports.traversePackagesDeps = traversePackagesDeps;
@@ -0,0 +1,4 @@
exports.getVersionInfo = () => {
const { version: devCliVersion } = require(`../../package.json`);
return `Medusa Dev CLI version: ${devCliVersion}`;
};
+352
View File
@@ -0,0 +1,352 @@
const chokidar = require(`chokidar`);
const _ = require(`lodash`);
const del = require(`del`);
const fs = require(`fs-extra`);
const path = require(`path`);
const findWorkspaceRoot = require(`find-yarn-workspace-root`);
const { publishPackagesLocallyAndInstall } = require(`./local-npm-registry`);
const { checkDepsChanges } = require(`./utils/check-deps-changes`);
const { getDependantPackages } = require(`./utils/get-dependant-packages`);
const {
setDefaultSpawnStdio,
promisifiedSpawn,
} = require(`./utils/promisified-spawn`);
const { traversePackagesDeps } = require(`./utils/traverse-package-deps`);
let numCopied = 0;
const quit = () => {
console.log(`Copied ${numCopied} files`);
process.exit();
};
const MAX_COPY_RETRIES = 3;
/*
* non-existent packages break on('ready')
* See: https://github.com/paulmillr/chokidar/issues/449
*/
async function watch(
root,
packages,
{ scanOnce, quiet, forceInstall, monoRepoPackages, localPackages }
) {
setDefaultSpawnStdio(quiet ? `ignore` : `inherit`);
// determine if in yarn workspace - if in workspace, force using verdaccio
// as current logic of copying files will not work correctly.
const yarnWorkspaceRoot = findWorkspaceRoot();
if (yarnWorkspaceRoot && process.env.NODE_ENV !== `test`) {
console.log(`Yarn workspace found.`);
forceInstall = true;
}
let afterPackageInstallation = false;
let queuedCopies = [];
const realCopyPath = (arg) => {
const { oldPath, newPath, quiet, resolve, reject, retry = 0 } = arg;
fs.copy(oldPath, newPath, (err) => {
if (err) {
if (retry >= MAX_COPY_RETRIES) {
console.error(err);
reject(err);
return;
} else {
setTimeout(
() => realCopyPath({ ...arg, retry: retry + 1 }),
500 * Math.pow(2, retry)
);
return;
}
}
// When the medusa binary is copied over, it is not setup with the executable
// permissions that it is given when installed via yarn.
// This fixes the issue where after running meduas-dev, running `yarn medusa develop`
// fails with a permission issue.
if (/(bin\/meduas.js|medusa(-cli)?\/cli.js)$/.test(newPath)) {
fs.chmodSync(newPath, `0755`);
}
numCopied += 1;
if (!quiet) {
console.log(`Copied ${oldPath} to ${newPath}`);
}
resolve();
});
};
const copyPath = (oldPath, newPath, quiet, packageName) =>
new Promise((resolve, reject) => {
const argObj = { oldPath, newPath, quiet, packageName, resolve, reject };
if (afterPackageInstallation) {
realCopyPath(argObj);
} else {
queuedCopies.push(argObj);
}
});
const runQueuedCopies = () => {
afterPackageInstallation = true;
queuedCopies.forEach((argObj) => realCopyPath(argObj));
queuedCopies = [];
};
const clearJSFilesFromNodeModules = async () => {
const packagesToClear = queuedCopies.reduce((acc, { packageName }) => {
if (packageName) {
acc.add(packageName);
}
return acc;
}, new Set());
await Promise.all(
[...packagesToClear].map(
async (packageToClear) =>
await del([
`node_modules/${packageToClear}/**/*.{js,js.map}`,
`!node_modules/${packageToClear}/node_modules/**/*.{js,js.map}`,
`!node_modules/${packageToClear}/src/**/*.{js,js.map}`,
])
)
);
};
// check packages deps and if they depend on other packages from monorepo
// add them to packages list
const { seenPackages, depTree } = traversePackagesDeps({
root,
packages: _.uniq(localPackages),
monoRepoPackages,
});
const allPackagesToWatch = packages
? _.intersection(packages, seenPackages)
: seenPackages;
const ignoredPackageJSON = new Map();
const ignorePackageJSONChanges = (packageName, contentArray) => {
ignoredPackageJSON.set(packageName, contentArray);
return () => {
ignoredPackageJSON.delete(packageName);
};
};
if (forceInstall) {
try {
if (allPackagesToWatch.length > 0) {
await publishPackagesLocallyAndInstall({
packagesToPublish: allPackagesToWatch,
root,
localPackages,
ignorePackageJSONChanges,
yarnWorkspaceRoot,
});
} else {
// run `yarn`
const yarnInstallCmd = [`yarn`];
console.log(`Installing packages from public NPM registry`);
await promisifiedSpawn(yarnInstallCmd);
console.log(`Installation complete`);
}
} catch (e) {
console.log(e);
}
process.exit();
}
if (allPackagesToWatch.length === 0) {
console.error(`There are no packages to watch.`);
return;
}
const cleanToWatch = allPackagesToWatch.map((pkgName) => {
if (pkgName.startsWith(`@medusajs`)) {
return pkgName.split("/")[1];
}
return pkgName;
});
const ignored = [
/[/\\]node_modules[/\\]/i,
/\.git/i,
/\.DS_Store/,
/[/\\]__tests__[/\\]/i,
/[/\\]__mocks__[/\\]/i,
/\.npmrc/i,
].concat(
cleanToWatch.map((p) => new RegExp(`${p}[\\/\\\\]src[\\/\\\\]`, `i`))
);
const watchers = _.uniq(
cleanToWatch
.map((p) => path.join(root, `/packages/`, p))
.filter((p) => fs.existsSync(p))
);
let allCopies = [];
const packagesToPublish = new Set();
let isInitialScan = true;
let isPublishing = false;
const waitFor = new Set();
let anyPackageNotInstalled = false;
const watchEvents = [`change`, `add`];
chokidar
.watch(watchers, {
ignored: [(filePath) => _.some(ignored, (reg) => reg.test(filePath))],
})
.on(`all`, async (event, filePath) => {
if (!watchEvents.includes(event)) {
return;
}
const [pack] = filePath
.split(/packages[/\\]/)
.pop()
.split(/[/\\]/);
const sourcePkg = JSON.parse(
fs.readFileSync(path.join(root, `/packages/`, pack, `package.json`))
);
const packageName = sourcePkg.name;
const prefix = path.join(root, `/packages/`, pack);
// Copy it over local version.
// Don't copy over the medusa bin file as that breaks the NPM symlink.
if (_.includes(filePath, `dist/medusa-cli.js`)) {
return;
}
const relativePackageFile = path.relative(prefix, filePath);
const newPath = path.join(
`./node_modules/${packageName}`,
relativePackageFile
);
if (relativePackageFile === `package.json`) {
// package.json files will change during publish to adjust version of package (and dependencies), so ignore
// changes during this process
if (isPublishing) {
return;
}
// Compare dependencies with local version
const didDepsChangedPromise = checkDepsChanges({
newPath,
packageName,
monoRepoPackages,
root,
isInitialScan,
ignoredPackageJSON,
});
if (isInitialScan) {
// normally checkDepsChanges would be sync,
// but because it also can do async GET request
// to unpkg if local package is not installed
// keep track of it to make sure all of it
// finish before installing
waitFor.add(didDepsChangedPromise);
}
const {
didDepsChanged,
packageNotInstalled,
} = await didDepsChangedPromise;
if (packageNotInstalled) {
anyPackageNotInstalled = true;
}
if (didDepsChanged) {
if (isInitialScan) {
waitFor.delete(didDepsChangedPromise);
// handle dependency change only in initial scan - this is for sure doable to
// handle this in watching mode correctly - but for the sake of shipping
// this I limit more work/time consuming edge cases.
// Dependency changed - now we need to figure out
// the packages that actually need to be published.
// If package with changed dependencies is dependency of other
// medusa package - like for example `medusa-plugin-page-creator`
// we need to publish both `medusa-plugin-page-creator` and `medusa`
// and install `medusa` in example site project.
getDependantPackages({
packageName,
depTree,
packages,
}).forEach((packageToPublish) => {
// scheduling publish - we will publish when `ready` is emitted
// as we can do single publish then
packagesToPublish.add(packageToPublish);
});
}
}
// don't ever copy package.json as this will mess up any future dependency
// changes checks
return;
}
const localCopies = [copyPath(filePath, newPath, quiet, packageName)];
// If this is from "cache-dir" also copy it into the site's .cache
if (_.includes(filePath, `cache-dir`)) {
const newCachePath = path.join(
`.cache/`,
path.relative(path.join(prefix, `cache-dir`), filePath)
);
localCopies.push(copyPath(filePath, newCachePath, quiet));
}
allCopies = allCopies.concat(localCopies);
})
.on(`ready`, async () => {
// wait for all async work needed to be done
// before publishing / installing
await Promise.all(Array.from(waitFor));
if (isInitialScan) {
isInitialScan = false;
if (packagesToPublish.size > 0) {
isPublishing = true;
await publishPackagesLocallyAndInstall({
packagesToPublish: Array.from(packagesToPublish),
root,
localPackages,
ignorePackageJSONChanges,
});
packagesToPublish.clear();
isPublishing = false;
} else if (anyPackageNotInstalled) {
// run `yarn`
const yarnInstallCmd = [`yarn`];
console.log(`Installing packages from public NPM registry`);
await promisifiedSpawn(yarnInstallCmd);
console.log(`Installation complete`);
}
await clearJSFilesFromNodeModules();
runQueuedCopies();
}
// all files watched, quit once all files are copied if necessary
Promise.all(allCopies).then(() => {
if (scanOnce) {
quit();
}
});
});
}
module.exports = watch;
File diff suppressed because it is too large. Load diff
+76
View File
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.9...medusa-file-spaces@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.10...medusa-file-spaces@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.9...medusa-file-spaces@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.8...medusa-file-spaces@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.7...medusa-file-spaces@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.6...medusa-file-spaces@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.5...medusa-file-spaces@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.3...medusa-file-spaces@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.3...medusa-file-spaces@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-file-spaces
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-file-spaces@1.1.2...medusa-file-spaces@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-file-spaces
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-file-spaces",
"version": "1.1.3",
"version": "1.1.12",
"description": "Digital Ocean Spaces file connector for Medusa",
"main": "index.js",
"repository": {
@@ -40,9 +40,9 @@
"aws-sdk": "^2.710.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3",
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12",
"stripe": "^8.50.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,78 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.6...medusa-fulfillment-manual@1.1.9) (2021-04-28)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.7...medusa-fulfillment-manual@1.1.8) (2021-04-20)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.6...medusa-fulfillment-manual@1.1.7) (2021-04-20)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.5...medusa-fulfillment-manual@1.1.6) (2021-04-13)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.4...medusa-fulfillment-manual@1.1.5) (2021-04-09)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.3...medusa-fulfillment-manual@1.1.4) (2021-03-30)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.2...medusa-fulfillment-manual@1.1.3) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.0...medusa-fulfillment-manual@1.1.2) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-manual
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.1.0...medusa-fulfillment-manual@1.1.1) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-manual
# [1.1.0](https://github.com/medusajs/medusa/compare/medusa-fulfillment-manual@1.0.12...medusa-fulfillment-manual@1.1.0) (2021-01-26)
**Note:** Version bump only for package medusa-fulfillment-manual
@@ -1,6 +1,6 @@
{
"name": "medusa-fulfillment-manual",
"version": "1.1.0",
"version": "1.1.9",
"description": "A manual fulfillment provider for Medusa",
"main": "index.js",
"repository": {
@@ -36,7 +36,7 @@
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/runtime": "^7.7.6",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0"
"medusa-core-utils": "^1.1.9"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,104 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.12...medusa-fulfillment-webshipper@1.1.13) (2021-05-05)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.9...medusa-fulfillment-webshipper@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.10...medusa-fulfillment-webshipper@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.9...medusa-fulfillment-webshipper@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.8...medusa-fulfillment-webshipper@1.1.9) (2021-04-13)
### Bug Fixes
* gitignore ([fa1fe9d](https://github.com/medusajs/medusa/commit/fa1fe9d619e19a277db6ee3a25ebb177222fa04b))
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
### Features
* adds support for certificate of origin ([f21dae8](https://github.com/medusajs/medusa/commit/f21dae827ad64522fd1f4d6317740c6b0ded0536))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.7...medusa-fulfillment-webshipper@1.1.8) (2021-04-13)
### Bug Fixes
* gitignore ([fa1fe9d](https://github.com/medusajs/medusa/commit/fa1fe9d619e19a277db6ee3a25ebb177222fa04b))
### Features
* adds support for certificate of origin ([f21dae8](https://github.com/medusajs/medusa/commit/f21dae827ad64522fd1f4d6317740c6b0ded0536))
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.6...medusa-fulfillment-webshipper@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.5...medusa-fulfillment-webshipper@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.3...medusa-fulfillment-webshipper@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.3...medusa-fulfillment-webshipper@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-fulfillment-webshipper
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-fulfillment-webshipper@1.1.3-next.0...medusa-fulfillment-webshipper@1.1.3) (2021-02-25)
**Note:** Version bump only for package medusa-fulfillment-webshipper
@@ -12,4 +12,5 @@ A webhook listener is exposed at `/webshipper/shipments` to listen for shipment
api_token: [a webshipper api token] (required)
order_channel_id: [the channel id to register orders on] (required)
webhook_secret: [the webhook secret used to listen for shipments] (required)
coo_countries: [an array of countries in which a Certificate of Origin will be attached] (default: "all")
```
@@ -1,6 +1,6 @@
{
"name": "medusa-fulfillment-webshipper",
"version": "1.1.3",
"version": "1.1.13",
"description": "Webshipper Fulfillment provider for Medusa",
"main": "index.js",
"repository": {
@@ -14,6 +14,7 @@
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-transform-instanceof": "^7.12.13",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/runtime": "^7.9.6",
@@ -36,7 +37,7 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0"
"medusa-core-utils": "^1.1.9"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -9,6 +9,16 @@ class WebshipperFulfillmentService extends FulfillmentService {
this.options_ = options
if (!options.coo_countries) {
this.options_.coo_countries = ["all"]
} else if (Array.isArray(options.coo_countries)) {
this.options_.coo_countries = options.coo_countries.map((c) =>
c.toLowerCase()
)
} else if (typeof options.coo_countries === "string") {
this.options_.coo_countries = [options.coo_countries]
}
/** @private @const {logger} */
this.logger_ = logger
@@ -242,8 +252,12 @@ class WebshipperFulfillmentService extends FulfillmentService {
webshipperOrder = await this.client_.orders.retrieve(existing)
}
const { shipping_address } = fromOrder
if (!webshipperOrder) {
let invoice
let certificateOfOrigin
if (this.invoiceGenerator_) {
const base64Invoice = await this.invoiceGenerator_.createInvoice(
fromOrder,
@@ -263,6 +277,34 @@ class WebshipperFulfillmentService extends FulfillmentService {
.catch((err) => {
throw err
})
const cooCountries = this.options_.coo_countries
if (
(cooCountries.includes("all") ||
cooCountries.includes(
shipping_address.country_code.toLowerCase()
)) &&
this.invoiceGenerator_.createCertificateOfOrigin
) {
const base64Coo = await this.invoiceGenerator_.createCertificateOfOrigin(
fromOrder,
fulfillmentItems
)
certificateOfOrigin = await this.client_.documents
.create({
type: "documents",
attributes: {
document_size: this.options_.document_size || "A4",
document_format: "PDF",
base64: base64Coo,
document_type: "certificate",
},
})
.catch((err) => {
throw err
})
}
}
let id = fulfillment.id
@@ -274,7 +316,6 @@ class WebshipperFulfillmentService extends FulfillmentService {
visible_ref = `S-${fromOrder.display_id}`
}
const { shipping_address } = fromOrder
const newOrder = {
type: "orders",
attributes: {
@@ -335,14 +376,25 @@ class WebshipperFulfillmentService extends FulfillmentService {
country_code: methodData.drop_point_country_code.toUpperCase(),
}
}
if (invoice) {
if (invoice || certificateOfOrigin) {
const docData = []
if (invoice) {
docData.push({
id: invoice.data.id,
type: invoice.data.type,
})
}
if (certificateOfOrigin) {
docData.push({
id: certificateOfOrigin.data.id,
type: certificateOfOrigin.data.type,
})
}
newOrder.relationships.documents = {
data: [
{
id: invoice.data.id,
type: invoice.data.type,
},
],
data: docData,
}
}
+78
View File
@@ -3,6 +3,84 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.7...medusa-interfaces@1.1.10) (2021-04-28)
**Note:** Version bump only for package medusa-interfaces
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.8...medusa-interfaces@1.1.9) (2021-04-20)
**Note:** Version bump only for package medusa-interfaces
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.7...medusa-interfaces@1.1.8) (2021-04-20)
**Note:** Version bump only for package medusa-interfaces
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.6...medusa-interfaces@1.1.7) (2021-04-13)
**Note:** Version bump only for package medusa-interfaces
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.5...medusa-interfaces@1.1.6) (2021-04-09)
**Note:** Version bump only for package medusa-interfaces
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.4...medusa-interfaces@1.1.5) (2021-03-30)
**Note:** Version bump only for package medusa-interfaces
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.3...medusa-interfaces@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-interfaces
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.1...medusa-interfaces@1.1.3) (2021-03-17)
### Features
* **medusa:** Add support for filtering with gt, lt, gte and lte ([#190](https://github.com/medusajs/medusa/issues/190)) ([dd0491f](https://github.com/medusajs/medusa/commit/dd0491f52132aed24f642589b12fcf636b719580))
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.1...medusa-interfaces@1.1.2) (2021-03-17)
### Features
* **medusa:** Add support for filtering with gt, lt, gte and lte ([#190](https://github.com/medusajs/medusa/issues/190)) ([dd0491f](https://github.com/medusajs/medusa/commit/dd0491f52132aed24f642589b12fcf636b719580))
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-interfaces@1.1.0...medusa-interfaces@1.1.1) (2021-02-17)
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-interfaces",
"version": "1.1.1",
"version": "1.1.10",
"description": "Core interfaces for Medusa",
"main": "dist/index.js",
"repository": {
@@ -35,7 +35,7 @@
"typeorm": "0.x"
},
"dependencies": {
"medusa-core-utils": "^1.1.0"
"medusa-core-utils": "^1.1.9"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.9...medusa-payment-adyen@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.10...medusa-payment-adyen@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.9...medusa-payment-adyen@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.8...medusa-payment-adyen@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.7...medusa-payment-adyen@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.6...medusa-payment-adyen@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.5...medusa-payment-adyen@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.3...medusa-payment-adyen@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.3...medusa-payment-adyen@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-payment-adyen
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-payment-adyen@1.1.2...medusa-payment-adyen@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-payment-adyen
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-adyen",
"version": "1.1.3",
"version": "1.1.12",
"description": "Adyen Payment provider for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -24,7 +24,7 @@
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.3"
"medusa-test-utils": "^1.1.12"
},
"scripts": {
"build": "babel src -d .",
@@ -42,7 +42,7 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0"
"medusa-core-utils": "^1.1.9"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,99 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.10...medusa-payment-klarna@1.1.13) (2021-04-28)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.11...medusa-payment-klarna@1.1.12) (2021-04-20)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.10...medusa-payment-klarna@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.9...medusa-payment-klarna@1.1.10) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.8...medusa-payment-klarna@1.1.9) (2021-04-13)
### Bug Fixes
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.8...medusa-payment-klarna@1.1.8) (2021-03-30)
### Bug Fixes
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.7...medusa-payment-klarna@1.1.8) (2021-03-23)
### Bug Fixes
* klarna doesn't treat negative discounts well ([e275184](https://github.com/medusajs/medusa/commit/e27518435ea1fafe556168c36475916a4243eabe))
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.6...medusa-payment-klarna@1.1.7) (2021-03-17)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.4...medusa-payment-klarna@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.4...medusa-payment-klarna@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-payment-klarna
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-payment-klarna@1.1.3...medusa-payment-klarna@1.1.4) (2021-02-17)
**Note:** Version bump only for package medusa-payment-klarna
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-klarna",
"version": "1.1.4",
"version": "1.1.13",
"description": "Klarna Payment provider for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -40,8 +40,8 @@
"axios": "^0.21.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3"
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -102,7 +102,7 @@ class KlarnaProviderService extends PaymentService {
order.order_lines = await this.lineItemsToOrderLines_(cart, region.tax_rate)
if (discount_total) {
if (discount_total > 0) {
order.order_lines.push({
name: `Discount`,
quantity: 1,
@@ -113,6 +113,16 @@ class KlarnaProviderService extends PaymentService {
total_amount: -discount_total * (1 + taxRate),
total_tax_amount: -discount_total * taxRate,
})
} else if (discount_total < 0) {
order.order_lines.push({
name: `Discount Payback`,
quantity: 1,
type: "surcharge",
unit_price: -discount_total * (1 + taxRate),
tax_rate: taxRate * 10000,
total_amount: -discount_total * (1 + taxRate),
total_tax_amount: -discount_total * taxRate,
})
}
if (gift_card_total) {
@@ -3,6 +3,89 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.0.13](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.12...medusa-payment-paypal@1.0.13) (2021-04-29)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.12](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.9...medusa-payment-paypal@1.0.12) (2021-04-28)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.11](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.10...medusa-payment-paypal@1.0.11) (2021-04-20)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.10](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.9...medusa-payment-paypal@1.0.10) (2021-04-20)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.9](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.8...medusa-payment-paypal@1.0.9) (2021-04-13)
### Bug Fixes
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.0.8](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.7...medusa-payment-paypal@1.0.8) (2021-04-13)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.7](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.6...medusa-payment-paypal@1.0.7) (2021-03-30)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.6](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.5...medusa-payment-paypal@1.0.6) (2021-03-17)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.5](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.3...medusa-payment-paypal@1.0.5) (2021-03-17)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.4](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.3...medusa-payment-paypal@1.0.4) (2021-03-17)
**Note:** Version bump only for package medusa-payment-paypal
## [1.0.3](https://github.com/medusajs/medusa/compare/medusa-payment-paypal@1.0.2...medusa-payment-paypal@1.0.3) (2021-02-17)
**Note:** Version bump only for package medusa-payment-paypal
+7 -6
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-paypal",
"version": "1.0.3",
"version": "1.0.13",
"description": "Paypal Payment provider for Meduas Commerce",
"main": "index.js",
"repository": {
@@ -26,12 +26,13 @@
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.3"
"medusa-interfaces": "^1.1.10",
"medusa-test-utils": "^1.1.12"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
"build": "babel src -d . --ignore **/__tests__,**/__mocks__",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__",
"watch": "babel -w src --out-dir . --ignore **/__tests__,**/__mocks__",
"test": "jest"
},
"peerDependencies": {
@@ -41,7 +42,7 @@
"@paypal/checkout-server-sdk": "^1.0.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0"
"medusa-core-utils": "^1.1.9"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -0,0 +1,87 @@
export const PayPalClientMock = {
execute: jest.fn().mockImplementation((r) => {
return {
result: r.result,
}
}),
}
export const PayPalMock = {
core: {
SandboxEnvironment: function () {
this.env = {
sandbox: true,
live: false,
}
},
LiveEnvironment: function () {
this.env = {
sandbox: false,
live: true,
}
},
PayPalHttpClient: function () {
return PayPalClientMock
},
},
payments: {
AuthorizationsGetRequest: jest.fn().mockImplementation(() => {}),
AuthorizationsVoidRequest: jest.fn().mockImplementation(() => {}),
AuthorizationsCaptureRequest: jest.fn().mockImplementation(() => {
return {
result: {
id: "test",
},
capture: true,
}
}),
CapturesRefundRequest: jest.fn().mockImplementation(() => {
return {
result: {
id: "test",
},
body: null,
requestBody: function (d) {
this.body = d
},
}
}),
},
orders: {
OrdersCreateRequest: jest.fn().mockImplementation(() => {
return {
result: {
id: "test",
},
order: true,
body: null,
requestBody: function (d) {
this.body = d
},
}
}),
OrdersPatchRequest: jest.fn().mockImplementation(() => {
return {
result: {
id: "test",
},
order: true,
body: null,
requestBody: function (d) {
this.body = d
},
}
}),
OrdersGetRequest: jest.fn().mockImplementation(() => {
return {
result: {
id: "test",
},
}
}),
},
}
export default PayPalMock
@@ -0,0 +1,346 @@
import PayPalProviderService from "../paypal-provider"
import {
PayPalMock,
PayPalClientMock,
} from "../../__mocks__/@paypal/checkout-server-sdk"
const TotalsServiceMock = {
getTotal: jest.fn().mockImplementation((c) => c.total),
}
const RegionServiceMock = {
retrieve: jest.fn().mockImplementation((id) =>
Promise.resolve({
currency_code: "eur",
})
),
}
describe("PaypalProviderService", () => {
describe("createPayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("creates paypal order", async () => {
result = await paypalProviderService.createPayment({
id: "test_cart",
region_id: "fr",
total: 1000,
})
expect(PayPalMock.orders.OrdersCreateRequest).toHaveBeenCalledTimes(1)
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(1)
expect(PayPalClientMock.execute).toHaveBeenCalledWith(
expect.objectContaining({
order: true,
body: {
intent: "AUTHORIZE",
application_context: {
shipping_preference: "NO_SHIPPING",
},
purchase_units: [
{
custom_id: "test_cart",
amount: {
currency_code: "EUR",
value: "10.00",
},
},
],
},
})
)
expect(result.id).toEqual("test")
})
})
describe("retrievePayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("retrieves paypal order", async () => {
result = await paypalProviderService.retrievePayment({ id: "test" })
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledTimes(1)
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(1)
expect(result.id).toEqual("test")
})
})
describe("updatePayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("updates paypal order", async () => {
result = await paypalProviderService.updatePayment(
{ id: "test" },
{
id: "test_cart",
region_id: "fr",
total: 1000,
}
)
expect(PayPalMock.orders.OrdersPatchRequest).toHaveBeenCalledTimes(1)
expect(PayPalMock.orders.OrdersPatchRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(1)
expect(PayPalClientMock.execute).toHaveBeenCalledWith(
expect.objectContaining({
order: true,
body: [
{
op: "replace",
path: "/purchase_units/@reference_id=='default'",
value: {
amount: {
currency_code: "EUR",
value: "10.00",
},
},
},
],
})
)
expect(result.id).toEqual("test")
})
})
describe("capturePayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("updates paypal order", async () => {
result = await paypalProviderService.capturePayment({
data: {
id: "test",
purchase_units: [
{
payments: {
authorizations: [
{
id: "test_auth",
},
],
},
},
],
},
})
expect(
PayPalMock.payments.AuthorizationsCaptureRequest
).toHaveBeenCalledTimes(1)
expect(
PayPalMock.payments.AuthorizationsCaptureRequest
).toHaveBeenCalledWith("test_auth")
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(2)
expect(result.id).toEqual("test")
})
})
describe("refundPayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("refunds payment", async () => {
result = await paypalProviderService.refundPayment(
{
currency_code: "eur",
data: {
id: "test",
purchase_units: [
{
payments: {
captures: [
{
id: "test_cap",
},
],
},
},
],
},
},
2000
)
expect(PayPalMock.payments.CapturesRefundRequest).toHaveBeenCalledWith(
"test_cap"
)
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(2)
expect(PayPalClientMock.execute).toHaveBeenCalledWith(
expect.objectContaining({
body: {
amount: {
currency_code: "EUR",
value: "20.00",
},
},
})
)
expect(result.id).toEqual("test")
})
it("doesn't refund without captures", async () => {
await expect(
paypalProviderService.refundPayment(
{
currency_code: "eur",
data: {
id: "test",
purchase_units: [
{
payments: {
captures: [],
},
},
],
},
},
2000
)
).rejects.toThrow("Order not yet captured")
})
})
describe("cancelPayment", () => {
let result
const paypalProviderService = new PayPalProviderService(
{
regionService: RegionServiceMock,
totalsService: TotalsServiceMock,
},
{
api_key: "test",
}
)
beforeEach(async () => {
jest.clearAllMocks()
})
it("refunds if captured", async () => {
result = await paypalProviderService.cancelPayment({
captured_at: "true",
currency_code: "eur",
data: {
id: "test",
purchase_units: [
{
payments: {
captures: [
{
id: "test_cap",
},
],
},
},
],
},
})
expect(PayPalMock.payments.CapturesRefundRequest).toHaveBeenCalledWith(
"test_cap"
)
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(2)
expect(result.id).toEqual("test")
})
it("voids if not captured", async () => {
result = await paypalProviderService.cancelPayment({
currency_code: "eur",
data: {
id: "test",
purchase_units: [
{
payments: {
authorizations: [
{
id: "test_auth",
},
],
},
},
],
},
})
expect(
PayPalMock.payments.AuthorizationsVoidRequest
).toHaveBeenCalledWith("test_auth")
expect(PayPalMock.orders.OrdersGetRequest).toHaveBeenCalledWith("test")
expect(PayPalClientMock.execute).toHaveBeenCalledTimes(2)
expect(result.id).toEqual("test")
})
})
})
@@ -5,7 +5,7 @@ import { PaymentService } from "medusa-interfaces"
class PayPalProviderService extends PaymentService {
static identifier = "paypal"
constructor({ customerService, totalsService, regionService }, options) {
constructor({ totalsService, regionService }, options) {
super()
/**
@@ -35,9 +35,6 @@ class PayPalProviderService extends PaymentService {
/** @private @const {PayPalHttpClient} */
this.paypal_ = new PayPal.core.PayPalHttpClient(environment)
/** @private @const {CustomerService} */
this.customerService_ = customerService
/** @private @const {RegionService} */
this.regionService_ = regionService
@@ -196,7 +193,7 @@ class PayPalProviderService extends PaymentService {
value: {
amount: {
currency_code: currency_code.toUpperCase(),
value: (cart.total / 100).toFixed(),
value: (cart.total / 100).toFixed(2),
},
},
},
@@ -240,7 +237,7 @@ class PayPalProviderService extends PaymentService {
* Refunds a given amount.
* @param {object} payment - payment to refund
* @param {number} amountToRefund - amount to refund
* @returns {string} the resulting PayPal order
* @returns {Promise<Object>} the resulting PayPal order
*/
async refundPayment(payment, amountToRefund) {
const { purchase_units } = payment.data
@@ -257,13 +254,13 @@ class PayPalProviderService extends PaymentService {
request.requestBody({
amount: {
currency_code: payment.currency_code.toUpperCase(),
value: (amountToRefund / 100).toFixed(),
value: (amountToRefund / 100).toFixed(2),
},
})
await this.paypal_.execute(request)
return this.retrievePayment(payment.id)
return this.retrievePayment(payment.data)
} catch (error) {
throw error
}
@@ -272,7 +269,7 @@ class PayPalProviderService extends PaymentService {
/**
* Cancels payment for Stripe payment intent.
* @param {object} paymentData - payment method data from cart
* @returns {object} canceled payment intent
* @returns {Promise<object>} canceled payment intent
*/
async cancelPayment(payment) {
try {
@@ -3,6 +3,89 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.9...medusa-payment-stripe@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.10...medusa-payment-stripe@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.9...medusa-payment-stripe@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.8...medusa-payment-stripe@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.7...medusa-payment-stripe@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.6...medusa-payment-stripe@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.5...medusa-payment-stripe@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-payment-stripe
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.3...medusa-payment-stripe@1.1.5) (2021-03-17)
### Bug Fixes
* floor amounts ([5e2f550](https://github.com/medusajs/medusa/commit/5e2f550ae10a3eb7636edf6bf99197517a1fa7b3))
* round instead of floor ([74a6b67](https://github.com/medusajs/medusa/commit/74a6b67f9db0a66fdf3cf69be6db62ae0deea635))
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.3...medusa-payment-stripe@1.1.4) (2021-03-17)
### Bug Fixes
* floor amounts ([5e2f550](https://github.com/medusajs/medusa/commit/5e2f550ae10a3eb7636edf6bf99197517a1fa7b3))
* round instead of floor ([74a6b67](https://github.com/medusajs/medusa/commit/74a6b67f9db0a66fdf3cf69be6db62ae0deea635))
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-payment-stripe@1.1.2...medusa-payment-stripe@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-payment-stripe
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-payment-stripe",
"version": "1.1.3",
"version": "1.1.12",
"description": "Stripe Payment provider for Meduas Commerce",
"main": "index.js",
"repository": {
@@ -26,7 +26,7 @@
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.3"
"medusa-test-utils": "^1.1.12"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
@@ -40,8 +40,8 @@
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-core-utils": "^1.1.9",
"stripe": "^8.50.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.9...medusa-plugin-add-ons@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.10...medusa-plugin-add-ons@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.9...medusa-plugin-add-ons@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.8...medusa-plugin-add-ons@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.7...medusa-plugin-add-ons@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.6...medusa-plugin-add-ons@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.5...medusa-plugin-add-ons@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.3...medusa-plugin-add-ons@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.3...medusa-plugin-add-ons@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.2...medusa-plugin-add-ons@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-add-ons
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-add-ons",
"version": "1.1.3",
"version": "1.1.12",
"description": "Add-on plugin for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -25,7 +25,7 @@
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.3"
"medusa-test-utils": "^1.1.12"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
@@ -37,8 +37,8 @@
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-core-utils": "^1.1.9",
"redis": "^3.0.2"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,129 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.15](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.13...medusa-plugin-brightpearl@1.1.15) (2021-04-28)
### Bug Fixes
* better inventory sync ([9eaf027](https://github.com/medusajs/medusa/commit/9eaf02762ff1ad455ac5020668ee9106db7c705a))
## [1.1.14](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.13...medusa-plugin-brightpearl@1.1.14) (2021-04-20)
### Features
* **medusa:** Swaps on swaps ([#229](https://github.com/medusajs/medusa/issues/229)) ([f8f1f57](https://github.com/medusajs/medusa/commit/f8f1f57fa1bcdc6f7ae4183e657a07e2641b1345))
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.13...medusa-plugin-brightpearl@1.1.13) (2021-04-20)
### Features
* **medusa:** Swaps on swaps ([#229](https://github.com/medusajs/medusa/issues/229)) ([f8f1f57](https://github.com/medusajs/medusa/commit/f8f1f57fa1bcdc6f7ae4183e657a07e2641b1345))
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.12...medusa-plugin-brightpearl@1.1.13) (2021-04-14)
**Note:** Version bump only for package medusa-plugin-brightpearl
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.11...medusa-plugin-brightpearl@1.1.12) (2021-04-13)
### Bug Fixes
* bp swaps ([e105d4e](https://github.com/medusajs/medusa/commit/e105d4edde5793f40e867291606b3db5e44dc24f))
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
* typo ([37ab52b](https://github.com/medusajs/medusa/commit/37ab52b19514fb1dfd864f0c218efd7ad205ff30))
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.10...medusa-plugin-brightpearl@1.1.11) (2021-04-13)
### Bug Fixes
* bp swaps ([e105d4e](https://github.com/medusajs/medusa/commit/e105d4edde5793f40e867291606b3db5e44dc24f))
* typo ([37ab52b](https://github.com/medusajs/medusa/commit/37ab52b19514fb1dfd864f0c218efd7ad205ff30))
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.9...medusa-plugin-brightpearl@1.1.10) (2021-04-01)
### Bug Fixes
* don't divide zero decimal currencies ([cfab2d4](https://github.com/medusajs/medusa/commit/cfab2d408a296a938266d0989b1de67d060b2ed5))
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.9...medusa-plugin-brightpearl@1.1.9) (2021-03-30)
### Bug Fixes
* don't divide zero decimal currencies ([cfab2d4](https://github.com/medusajs/medusa/commit/cfab2d408a296a938266d0989b1de67d060b2ed5))
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.8...medusa-plugin-brightpearl@1.1.9) (2021-03-25)
**Note:** Version bump only for package medusa-plugin-brightpearl
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.7...medusa-plugin-brightpearl@1.1.8) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-brightpearl
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.5...medusa-plugin-brightpearl@1.1.7) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-brightpearl
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.5...medusa-plugin-brightpearl@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-brightpearl
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-brightpearl@1.1.4...medusa-plugin-brightpearl@1.1.5) (2021-02-25)
**Note:** Version bump only for package medusa-plugin-brightpearl
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-brightpearl",
"version": "1.1.5",
"version": "1.1.15",
"description": "Brightpearl plugin for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -27,7 +27,7 @@
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.3",
"medusa-test-utils": "^1.1.12",
"prettier": "^2.0.5"
},
"scripts": {
@@ -43,8 +43,8 @@
"axios": "^0.19.2",
"axios-rate-limit": "^1.2.1",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-core-utils": "^1.1.9",
"randomatic": "^3.1.1"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -65,7 +65,7 @@ export default (container) => {
throw new Error("Already sent to BP")
}
await brightpearlService.createSalesOrder(order)
await brightpearlService.createSalesOrder(order.id)
res.sendStatus(200)
} catch (err) {
res.status(400).json(err)
@@ -5,13 +5,9 @@ const inventorySync = async (container, options) => {
const brightpearlService = container.resolve("brightpearlService")
const eventBus = container.resolve("eventBusService")
try {
const client = await brightpearlService.getClient()
const pattern = options.inventory_sync_cron
eventBus.createCronJob(
"inventory-sync",
{},
pattern,
brightpearlService.syncInventory
eventBus.createCronJob("inventory-sync", {}, pattern, () =>
brightpearlService.syncInventory()
)
} catch (err) {
if (err.name === "not_allowed") {
@@ -1,4 +1,4 @@
import { MedusaError } from "medusa-core-utils"
import { MedusaError, humanizeAmount } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import Brightpearl from "../utils/brightpearl"
@@ -126,7 +126,6 @@ class BrightpearlService extends BaseService {
async syncInventory() {
const client = await this.getClient()
const variants = await this.productVariantService_.list()
let search = true
let bpProducts = []
@@ -141,31 +140,39 @@ class BrightpearlService extends BaseService {
}
if (bpProducts.length) {
const productRange = `${bpProducts[0].productId}-${
bpProducts[bpProducts.length - 1].productId
}`
const productRange = bpProducts
.map(({ productId }) => productId)
.join(",")
const availabilities = await client.products.retrieveAvailability(
productRange
)
return Promise.all(
variants.map(async (v) => {
const brightpearlProduct = bpProducts.find(
(prod) => prod.SKU === v.sku
)
if (!brightpearlProduct) {
return
bpProducts.map(async (bpProduct) => {
const { SKU: sku, productId } = bpProduct
const variant = await this.productVariantService_
.retrieveBySKU(sku, {
select: ["id", "manage_inventory", "inventory_quantity"],
})
.catch((_) => undefined)
const prodAvail = availabilities[productId]
let onHand = 0
if (
prodAvail &&
prodAvail.warehouses &&
prodAvail.warehouses[`${this.options.warehouse}`]
) {
onHand = prodAvail.warehouses[`${this.options.warehouse}`].onHand
}
const { productId } = brightpearlProduct
const availability = availabilities[productId]
if (availability) {
const onHand = availability.total.onHand
// Only update if the inventory levels have changed
if (parseInt(v.inventory_quantity) !== parseInt(onHand)) {
return this.productVariantService_.update(v.id, {
inventory_quantity: onHand,
if (variant && variant.manage_inventory) {
if (parseInt(variant.inventory_quantity) !== parseInt(onHand)) {
return this.productVariantService_.update(variant.id, {
inventory_quantity: parseInt(onHand),
})
}
}
@@ -182,7 +189,16 @@ class BrightpearlService extends BaseService {
if (availability) {
const brightpearlProduct = await client.products.retrieve(productId)
const onHand = availability[productId].total.onHand
const prodAvail = availability[productId]
let onHand = 0
if (
prodAvail.warehouses &&
prodAvail.warehouses[`${this.options.warehouse}`]
) {
onHand = prodAvail.warehouses[`${this.options.warehouse}`].onHand
}
const sku = brightpearlProduct.identity.sku
if (!sku) return
@@ -290,10 +306,12 @@ class BrightpearlService extends BaseService {
taxCode: region.tax_code,
net: this.bpnum_(
fromRefund.amount,
fromOrder.currency_code,
10000 / (100 + fromOrder.tax_rate)
),
tax: this.bpnum_(
fromRefund.amount * (1 - 100 / (100 + fromOrder.tax_rate))
fromRefund.amount * (1 - 100 / (100 + fromOrder.tax_rate)),
fromOrder.currency_code
),
nominalCode: accountingCode,
},
@@ -311,7 +329,7 @@ class BrightpearlService extends BaseService {
paymentMethodCode: this.options.payment_method_code || "1220",
orderId: creditId,
currencyIsoCode: fromOrder.currency_code.toUpperCase(),
amountPaid: this.bpnum_(fromRefund.amount),
amountPaid: this.bpnum_(fromRefund.amount, fromOrder.currency_code),
paymentDate: new Date(),
paymentType,
}
@@ -338,7 +356,11 @@ class BrightpearlService extends BaseService {
const region = fromOrder.region
const client = await this.getClient()
const authData = await this.getAuthData()
const orderId = fromOrder.metadata.brightpearl_sales_order_id
const orderIds = this.gatherOrders(fromOrder)
const orderId = orderIds[0]
const parentRows = await this.gatherRowsFromOrderIds(orderIds)
if (orderId) {
const parentSo = await client.orders.retrieve(orderId)
const order = {
@@ -351,7 +373,7 @@ class BrightpearlService extends BaseService {
delivery: parentSo.delivery,
parentId: orderId,
rows: fromReturn.items.map((i) => {
const parentRow = parentSo.rows.find((row) => {
const parentRow = parentRows.find((row) => {
return row.externalRef === i.item_id
})
return {
@@ -380,8 +402,15 @@ class BrightpearlService extends BaseService {
name: "Difference",
quantity: 1,
taxCode: region.tax_code,
net: this.bpnum_(difference, 10000 / (100 + fromOrder.tax_rate)),
tax: this.bpnum_(difference * (1 - 100 / (100 + fromOrder.tax_rate))),
net: this.bpnum_(
difference,
fromOrder.currency_code,
10000 / (100 + fromOrder.tax_rate)
),
tax: this.bpnum_(
difference * (1 - 100 / (100 + fromOrder.tax_rate)),
fromOrder.currency_code
),
nominalCode: this.options.sales_account_code || "4000",
})
}
@@ -397,7 +426,10 @@ class BrightpearlService extends BaseService {
paymentMethodCode: this.options.payment_method_code || "1220",
orderId: creditId,
currencyIsoCode: fromOrder.currency_code.toUpperCase(),
amountPaid: this.bpnum_(fromReturn.refund_amount),
amountPaid: this.bpnum_(
fromReturn.refund_amount,
fromOrder.currency_code
),
paymentDate: new Date(),
paymentType,
}
@@ -488,7 +520,9 @@ class BrightpearlService extends BaseService {
const order = await client.orders.retrieve(salesOrderId)
await client.warehouses
.createReservation(order, this.options.warehouse)
.catch(() => {})
.catch((err) => {
console.log("Failed to allocate for order:", salesOrderId)
})
return salesOrderId
})
.then((salesOrderId) => {
@@ -577,6 +611,7 @@ class BrightpearlService extends BaseService {
},
},
rows: await this.getBrightpearlRows({
currency_code: fromOrder.currency_code,
region: fromOrder.region,
discounts: fromOrder.discounts,
tax_rate: fromOrder.tax_rate,
@@ -588,7 +623,11 @@ class BrightpearlService extends BaseService {
return client.orders.create(order).then(async (salesOrderId) => {
const order = await client.orders.retrieve(salesOrderId)
await client.warehouses.createReservation(order, this.options.warehouse)
await client.warehouses
.createReservation(order, this.options.warehouse)
.catch((err) => {
console.log("Failed to allocate for order:", salesOrderId)
})
const total = order.rows.reduce((acc, next) => {
return acc + parseFloat(next.net) + parseFloat(next.tax)
@@ -640,10 +679,12 @@ class BrightpearlService extends BaseService {
name: `#${fromOrder.display_id}: Claim ${fromClaim.id}`,
net: this.bpnum_(
fromClaim.refund_amount,
fromOrder.currency_code,
10000 / (100 + fromOrder.tax_rate)
),
tax: this.bpnum_(
fromClaim.refund_amount * (1 - 100 / (100 + fromOrder.tax_rate))
fromClaim.refund_amount * (1 - 100 / (100 + fromOrder.tax_rate)),
fromOrder.currency_code
),
taxCode: region.tax_code,
nominalCode: this.options.sales_account_code || `4000`,
@@ -663,7 +704,10 @@ class BrightpearlService extends BaseService {
paymentMethodCode: this.options.payment_method_code || "1220",
orderId: creditId,
currencyIsoCode: fromOrder.currency_code.toUpperCase(),
amountPaid: this.bpnum_(fromClaim.refund_amount),
amountPaid: this.bpnum_(
fromClaim.refund_amount,
fromOrder.currency_code
),
paymentDate: new Date(),
paymentType,
}
@@ -674,11 +718,43 @@ class BrightpearlService extends BaseService {
}
}
gatherOrders(fromOrder) {
const ids = []
if (fromOrder.metadata && fromOrder.metadata.brightpearl_sales_order_id) {
ids.push(fromOrder.metadata.brightpearl_sales_order_id)
}
if (fromOrder.swaps) {
for (const s of fromOrder.swaps) {
if (s.metadata && s.metadata.brightpearl_sales_order_id) {
ids.push(s.metadata.brightpearl_sales_order_id)
}
}
}
return ids
}
async gatherRowsFromOrderIds(ids) {
const client = await this.getClient()
const orders = await Promise.all(ids.map((i) => client.orders.retrieve(i)))
let rows = []
for (const o of orders) {
rows = rows.concat(o.rows)
}
return rows
}
async createSwapCredit(fromOrder, fromSwap) {
const region = fromOrder.region
const client = await this.getClient()
const authData = await this.getAuthData()
const orderId = fromOrder.metadata.brightpearl_sales_order_id
const orderIds = this.gatherOrders(fromOrder)
const orderId = orderIds[0]
const parentRows = await this.gatherRowsFromOrderIds(orderIds)
const sIndex = fromOrder.swaps.findIndex((s) => fromSwap.id === s.id)
if (orderId) {
@@ -693,7 +769,7 @@ class BrightpearlService extends BaseService {
delivery: parentSo.delivery,
parentId: orderId,
rows: fromSwap.return_order.items.map((i) => {
const parentRow = parentSo.rows.find((row) => {
const parentRow = parentRows.find((row) => {
return row.externalRef === i.item_id
})
return {
@@ -775,7 +851,7 @@ class BrightpearlService extends BaseService {
orderId: soId,
paymentDate: new Date(),
currencyIsoCode: fromOrder.currency_code.toUpperCase(),
amountPaid: this.bpnum_(fromOrder.total),
amountPaid: this.bpnum_(fromOrder.total, fromOrder.currency_code),
paymentType,
}
@@ -811,9 +887,13 @@ class BrightpearlService extends BaseService {
}
if (config.include_price) {
row.net = this.bpnum_(item.unit_price * item.quantity - ld.amount)
row.net = this.bpnum_(
item.unit_price * item.quantity - ld.amount,
fromOrder.currency_code
)
row.tax = this.bpnum_(
item.unit_price * item.quantity - ld.amount,
fromOrder.currency_code,
fromOrder.tax_rate
)
} else if (config.is_claim) {
@@ -821,7 +901,11 @@ class BrightpearlService extends BaseService {
bpProduct.productId,
this.options.cost_price_list || `1`
)
row.tax = this.bpnum_(row.net * 100, fromOrder.tax_rate)
row.tax = this.bpnum_(
row.net * 100,
fromOrder.currency_code,
fromOrder.tax_rate
)
}
row.quantity = item.quantity
@@ -847,8 +931,12 @@ class BrightpearlService extends BaseService {
if (gcTotal) {
lines.push({
name: `Gift Card`,
net: this.bpnum_(-1 * gcTotal),
tax: this.bpnum_(-1 * gcTotal, fromOrder.tax_rate),
net: this.bpnum_(-1 * gcTotal, fromOrder.currency_code),
tax: this.bpnum_(
-1 * gcTotal,
fromOrder.currency_code,
fromOrder.tax_rate
),
quantity: 1,
taxCode: region.tax_code,
nominalCode: this.options.gift_card_account_code || "4000",
@@ -863,8 +951,12 @@ class BrightpearlService extends BaseService {
lines.push({
name: `Shipping: ${shippingMethods.map((m) => m.name).join(" + ")}`,
quantity: 1,
net: this.bpnum_(shippingTotal),
tax: this.bpnum_(shippingTotal, fromOrder.tax_rate),
net: this.bpnum_(shippingTotal, fromOrder.currency_code),
tax: this.bpnum_(
shippingTotal,
fromOrder.currency_code,
fromOrder.tax_rate
),
taxCode: region.tax_code,
nominalCode: this.options.shipping_account_code || "4040",
})
@@ -926,6 +1018,7 @@ class BrightpearlService extends BaseService {
},
rows: await this.getBrightpearlRows(
{
currency_code: fromOrder.currency_code,
region: fromOrder.region,
discounts: fromOrder.discounts,
tax_rate: fromOrder.tax_rate,
@@ -940,7 +1033,11 @@ class BrightpearlService extends BaseService {
.create(order)
.then(async (salesOrderId) => {
const order = await client.orders.retrieve(salesOrderId)
await client.warehouses.createReservation(order, this.options.warehouse)
await client.warehouses
.createReservation(order, this.options.warehouse)
.catch((err) => {
console.log("Failed to allocate for order:", salesOrderId)
})
const total = order.rows.reduce((acc, next) => {
return acc + parseFloat(next.net) + parseFloat(next.tax)
@@ -1103,8 +1200,8 @@ class BrightpearlService extends BaseService {
)
}
bpnum_(number, taxRate = 100) {
const bpNumber = number / 100
bpnum_(number, currency, taxRate = 100) {
const bpNumber = humanizeAmount(number, currency)
return this.bpround_(bpNumber * (taxRate / 100))
}
}
@@ -39,7 +39,7 @@ class OrderSubscriber {
"swap.payment_completed",
this.registerSwapPayment
)
eventBusService.subscribe("order.swap_received", this.registerSwap)
eventBusService.subscribe("swap.received", this.registerSwap)
}
sendToBrightpearl = (data) => {
@@ -55,13 +55,13 @@ class OrderSubscriber {
}
registerSwap = async (data) => {
const { id, swap_id } = data
const { id } = data
if (!id && !swap_id) {
if (!id) {
return
}
const fromSwap = await this.swapService_.retrieve(swap_id, {
const fromSwap = await this.swapService_.retrieve(id, {
relations: [
"order",
"order.payments",
@@ -136,7 +136,7 @@ class OrderSubscriber {
const { id, return_id } = data
const order = await this.orderService_.retrieve(id, {
relations: ["region", "payments"],
relations: ["region", "swaps", "payments"],
})
const fromReturn = await this.returnService_.retrieve(return_id, {
@@ -3,6 +3,105 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.10...medusa-plugin-contentful@1.1.13) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-contentful
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.11...medusa-plugin-contentful@1.1.12) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-contentful
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.10...medusa-plugin-contentful@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-contentful
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.9...medusa-plugin-contentful@1.1.10) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.8...medusa-plugin-contentful@1.1.9) (2021-04-13)
### Bug Fixes
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.8...medusa-plugin-contentful@1.1.8) (2021-03-30)
### Bug Fixes
* publish assist ([7719957](https://github.com/medusajs/medusa/commit/7719957b44a0c0d950eff948faf31188fe0e3ef1))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.7...medusa-plugin-contentful@1.1.8) (2021-03-26)
### Bug Fixes
* update all contentful ([806918a](https://github.com/medusajs/medusa/commit/806918a10e42fde60240dcc785d8e175dc8507b5))
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.6...medusa-plugin-contentful@1.1.7) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-contentful
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.4...medusa-plugin-contentful@1.1.6) (2021-03-17)
### Bug Fixes
* contentful sync ([#206](https://github.com/medusajs/medusa/issues/206)) ([227cdb6](https://github.com/medusajs/medusa/commit/227cdb622234126df6087992203ce82ff9446974))
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.4...medusa-plugin-contentful@1.1.5) (2021-03-17)
### Bug Fixes
* contentful sync ([#206](https://github.com/medusajs/medusa/issues/206)) ([227cdb6](https://github.com/medusajs/medusa/commit/227cdb622234126df6087992203ce82ff9446974))
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-contentful@1.1.3...medusa-plugin-contentful@1.1.4) (2021-02-25)
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-contentful",
"version": "1.1.4",
"version": "1.1.13",
"description": "Contentful plugin for Medusa Commerce",
"main": "index.js",
"repository": {
@@ -39,9 +39,9 @@
"body-parser": "^1.19.0",
"contentful-management": "^5.27.1",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3",
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12",
"redis": "^3.0.2"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -11,6 +11,7 @@ const checkContentTypes = async (container) => {
if (!product) {
throw Error("Content type: `product` is missing in Contentful")
}
if (!variant) {
throw Error("Content type: `productVariant` is missing in Contentful")
}
@@ -76,7 +76,7 @@ class ContentfulService extends BaseService {
let assets = []
await Promise.all(
product.images
.filter((image) => image !== product.thumbnail)
.filter((image) => image.url !== product.thumbnail)
.map(async (image, i) => {
const asset = await environment.createAsset({
fields: {
@@ -89,20 +89,22 @@ class ContentfulService extends BaseService {
file: {
"en-US": {
contentType: "image/xyz",
fileName: image,
upload: image,
fileName: image.url,
upload: image.url,
},
},
},
})
await asset.processForAllLocales()
const finalAsset = await asset
.processForAllLocales()
.then((ast) => ast.publish())
assets.push({
sys: {
type: "Link",
linkType: "Asset",
id: asset.sys.id,
id: finalAsset.sys.id,
},
})
})
@@ -231,9 +233,9 @@ class ContentfulService extends BaseService {
fields,
})
const ignoreIds = (await this.getIgnoreIds_("product")) || []
ignoreIds.push(product.id)
this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
// const ignoreIds = (await this.getIgnoreIds_("product")) || []
// ignoreIds.push(product.id)
// this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
return result
} catch (error) {
throw error
@@ -271,38 +273,47 @@ class ContentfulService extends BaseService {
}
)
const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
ignoreIds.push(v.id)
this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
// const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
// ignoreIds.push(v.id)
// this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
return result
} catch (error) {
throw error
}
}
async updateProductInContentful(product) {
async updateProductInContentful(data) {
const updateFields = [
"variants",
"options",
"tags",
"title",
"tags",
"type",
"type_id",
"collection",
"collection_id",
"thumbnail",
]
const found = data.fields.find((f) => updateFields.includes(f))
if (!found) {
return
}
try {
const ignoreIds = (await this.getIgnoreIds_("product")) || []
// const ignoreIds = (await this.getIgnoreIds_("product")) || []
if (ignoreIds.includes(product.id)) {
const newIgnoreIds = ignoreIds.filter((id) => id !== product.id)
this.redis_.set("product_ignore_ids", JSON.stringify(newIgnoreIds))
return
} else {
ignoreIds.push(product.id)
this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
}
// if (ignoreIds.includes(product.id)) {
// const newIgnoreIds = ignoreIds.filter((id) => id !== product.id)
// this.redis_.set("product_ignore_ids", JSON.stringify(newIgnoreIds))
// return
// } else {
// ignoreIds.push(product.id)
// this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
// }
const environment = await this.getContentfulEnvironment_()
// check if product exists
let productEntry = undefined
try {
productEntry = await environment.getEntry(product.id)
} catch (error) {
return this.createProductInContentful(product)
}
const p = await this.productService_.retrieve(product.id, {
const p = await this.productService_.retrieve(data.id, {
relations: [
"options",
"variants",
@@ -313,6 +324,15 @@ class ContentfulService extends BaseService {
],
})
const environment = await this.getContentfulEnvironment_()
// check if product exists
let productEntry = undefined
try {
productEntry = await environment.getEntry(data.id)
} catch (error) {
return this.createProductInContentful(p)
}
const variantEntries = await this.getVariantEntries_(p.variants)
const variantLinks = this.getVariantLinks_(variantEntries)
@@ -332,7 +352,12 @@ class ContentfulService extends BaseService {
},
}
if (p.thumbnail) {
if (data.fields.includes("thumbnail") && p.thumbnail) {
let url = p.thumbnail
if (p.thumbnail.startsWith("//")) {
url = `https:${url}`
}
const thumbnailAsset = await environment.createAsset({
fields: {
title: {
@@ -344,8 +369,8 @@ class ContentfulService extends BaseService {
file: {
"en-US": {
contentType: "image/xyz",
fileName: p.thumbnail,
upload: p.thumbnail,
fileName: url,
upload: url,
},
},
},
@@ -412,20 +437,42 @@ class ContentfulService extends BaseService {
}
async updateProductVariantInContentful(variant) {
try {
const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
const updateFields = [
"title",
"prices",
"sku",
"material",
"weight",
"length",
"height",
"origin_country",
"options",
]
if (ignoreIds.includes(variant.id)) {
const newIgnoreIds = ignoreIds.filter((id) => id !== variant.id)
this.redis_.set(
"product_variant_ignore_ids",
JSON.stringify(newIgnoreIds)
)
// Update came directly from product variant service so only act on a couple
// of fields. When the update comes from the product we want to ensure
// references are set up correctly so we run through everything.
if (variant.fields) {
const found = variant.fields.find((f) => updateFields.includes(f))
if (!found) {
return
} else {
ignoreIds.push(variant.id)
this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
}
}
try {
// const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
//if (ignoreIds.includes(variant.id)) {
// const newIgnoreIds = ignoreIds.filter((id) => id !== variant.id)
// this.redis_.set(
// "product_variant_ignore_ids",
// JSON.stringify(newIgnoreIds)
// )
// return
//} else {
// ignoreIds.push(variant.id)
// this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
//}
const environment = await this.getContentfulEnvironment_()
// check if product exists
@@ -476,19 +523,23 @@ class ContentfulService extends BaseService {
const environment = await this.getContentfulEnvironment_()
const productEntry = await environment.getEntry(productId)
const ignoreIds = (await this.getIgnoreIds_("product")) || []
if (ignoreIds.includes(productId)) {
const newIgnoreIds = ignoreIds.filter((id) => id !== productId)
this.redis_.set("product_ignore_ids", JSON.stringify(newIgnoreIds))
return
} else {
ignoreIds.push(productId)
this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
}
const product = await this.productService_.retrieve(productId)
let update = {
title:
productEntry.fields[this.getCustomField("title", "product")]["en-US"],
//const ignoreIds = (await this.getIgnoreIds_("product")) || []
//if (ignoreIds.includes(productId)) {
// const newIgnoreIds = ignoreIds.filter((id) => id !== productId)
// this.redis_.set("product_ignore_ids", JSON.stringify(newIgnoreIds))
// return
//} else {
// ignoreIds.push(productId)
// this.redis_.set("product_ignore_ids", JSON.stringify(ignoreIds))
//}
let update = {}
const title =
productEntry.fields[this.getCustomField("title", "product")]["en-US"]
if (product.title !== title) {
update.title = title
}
// Get the thumbnail, if present
@@ -497,15 +548,16 @@ class ContentfulService extends BaseService {
productEntry.fields.thumbnail["en-US"].sys.id
)
update.thumbnail = thumb.fields.file["en-US"].url
if (thumb.fields.file["en-US"].url) {
if (!product.thumbnail.includes(thumb.fields.file["en-US"].url)) {
update.thumbnail = thumb.fields.file["en-US"].url
}
}
}
const updatedProduct = await this.productService_.update(
productId,
update
)
return updatedProduct
if (!_.isEmpty(update)) {
await this.productService_.update(productId, update)
}
} catch (error) {
throw error
}
@@ -516,18 +568,18 @@ class ContentfulService extends BaseService {
const environment = await this.getContentfulEnvironment_()
const variantEntry = await environment.getEntry(variantId)
const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
if (ignoreIds.includes(variantId)) {
const newIgnoreIds = ignoreIds.filter((id) => id !== variantId)
this.redis_.set(
"product_variant_ignore_ids",
JSON.stringify(newIgnoreIds)
)
return
} else {
ignoreIds.push(variantId)
this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
}
// const ignoreIds = (await this.getIgnoreIds_("product_variant")) || []
// if (ignoreIds.includes(variantId)) {
// const newIgnoreIds = ignoreIds.filter((id) => id !== variantId)
// this.redis_.set(
// "product_variant_ignore_ids",
// JSON.stringify(newIgnoreIds)
// )
// return
// } else {
// ignoreIds.push(variantId)
// this.redis_.set("product_variant_ignore_ids", JSON.stringify(ignoreIds))
// }
const updatedVariant = await this.productVariantService_.update(
variantId,
@@ -3,6 +3,30 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-discount-generator@1.1.0...medusa-plugin-discount-generator@1.1.3) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-discount-generator
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-plugin-discount-generator@1.1.1...medusa-plugin-discount-generator@1.1.2) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-discount-generator
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-plugin-discount-generator@1.1.0...medusa-plugin-discount-generator@1.1.1) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-discount-generator
# 1.1.0 (2021-01-26)
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-discount-generator",
"version": "1.1.0",
"version": "1.1.3",
"main": "index.js",
"license": "MIT",
"author": "Sebastian Rindom",
@@ -40,5 +40,5 @@
"medusa-core-utils": "^0.1.27",
"randomatic": "^3.1.1"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.9...medusa-plugin-economic@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.10...medusa-plugin-economic@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.9...medusa-plugin-economic@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.8...medusa-plugin-economic@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.7...medusa-plugin-economic@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.6...medusa-plugin-economic@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.5...medusa-plugin-economic@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.3...medusa-plugin-economic@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.3...medusa-plugin-economic@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-economic
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-economic@1.1.2...medusa-plugin-economic@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-economic
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-economic",
"version": "1.1.3",
"version": "1.1.12",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-economic",
"version": "1.1.3",
"version": "1.1.12",
"description": "E-conomic financial reporting",
"main": "index.js",
"repository": {
@@ -39,9 +39,9 @@
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3",
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12",
"moment": "^2.27.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,30 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-ip-lookup@1.1.0...medusa-plugin-ip-lookup@1.1.3) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-ip-lookup
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-plugin-ip-lookup@1.1.1...medusa-plugin-ip-lookup@1.1.2) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-ip-lookup
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-plugin-ip-lookup@1.1.0...medusa-plugin-ip-lookup@1.1.1) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-ip-lookup
# [1.1.0](https://github.com/medusajs/medusa/compare/medusa-plugin-ip-lookup@1.0.11...medusa-plugin-ip-lookup@1.1.0) (2021-01-26)
**Note:** Version bump only for package medusa-plugin-ip-lookup
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-ip-lookup",
"version": "1.1.0",
"version": "1.1.3",
"description": "IP lookup middleware for Medusa core",
"main": "dist/index.js",
"repository": {
@@ -35,5 +35,5 @@
"axios": "^0.20.0",
"mongoose": "^5.8.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.9...medusa-plugin-mailchimp@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.10...medusa-plugin-mailchimp@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.9...medusa-plugin-mailchimp@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.8...medusa-plugin-mailchimp@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.7...medusa-plugin-mailchimp@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.6...medusa-plugin-mailchimp@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.5...medusa-plugin-mailchimp@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.3...medusa-plugin-mailchimp@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.3...medusa-plugin-mailchimp@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-mailchimp
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-mailchimp@1.1.2...medusa-plugin-mailchimp@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-mailchimp
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-mailchimp",
"version": "1.1.3",
"version": "1.1.12",
"description": "Mailchimp newsletter subscriptions",
"main": "index.js",
"repository": {
@@ -40,8 +40,8 @@
"cors": "^2.8.5",
"express": "^4.17.1",
"mailchimp-api-v3": "^1.14.0",
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3"
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -3,6 +3,82 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.9...medusa-plugin-permissions@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.10...medusa-plugin-permissions@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.9...medusa-plugin-permissions@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.8...medusa-plugin-permissions@1.1.9) (2021-04-13)
### Bug Fixes
* merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
* merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.7...medusa-plugin-permissions@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.6...medusa-plugin-permissions@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.5...medusa-plugin-permissions@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.3...medusa-plugin-permissions@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.3...medusa-plugin-permissions@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.2...medusa-plugin-permissions@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-permissions
@@ -1,6 +1,6 @@
{
"name": "medusa-plugin-permissions",
"version": "1.1.3",
"version": "1.1.12",
"description": "Role permission for Medusa core",
"main": "dist/index.js",
"repository": {
@@ -32,9 +32,9 @@
"medusa-interfaces": "1.x"
},
"dependencies": {
"medusa-core-utils": "^1.1.0",
"medusa-test-utils": "^1.1.3",
"medusa-core-utils": "^1.1.9",
"medusa-test-utils": "^1.1.12",
"mongoose": "^5.8.0"
},
"gitHead": "0646bd395a6056657cb0aa93c13699c4a9dbbcdd"
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -0,0 +1,12 @@
let ignore = [`**/dist`]
// Jest needs to compile this code, but generally we don't want this copied
// to output folders
if (process.env.NODE_ENV !== `test`) {
ignore.push(`**/__tests__`)
}
module.exports = {
presets: [["babel-preset-medusa-package"], ["@babel/preset-typescript"]],
ignore,
}
@@ -0,0 +1,9 @@
{
"plugins": ["prettier"],
"extends": ["prettier"],
"rules": {
"prettier/prettier": "error",
"semi": "error",
"no-unused-expressions": "true"
}
}
@@ -0,0 +1,18 @@
/lib
node_modules
.DS_store
.env*
/*.js
!.babelrc*
!index.js
!jest.config.js
/dist
/api
/services
/models
/subscribers
/migrations
/repositories
@@ -0,0 +1,9 @@
/lib
node_modules
.DS_store
.env*
/*.js
!index.js
yarn.lock
@@ -0,0 +1,7 @@
{
"endOfLine": "lf",
"semi": false,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5"
}
@@ -0,0 +1,71 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [0.0.7](https://github.com/medusajs/medusa/compare/medusa-plugin-restock-notification@0.0.6...medusa-plugin-restock-notification@0.0.7) (2021-04-29)
**Note:** Version bump only for package medusa-plugin-restock-notification
## [0.0.6](https://github.com/medusajs/medusa/compare/medusa-plugin-restock-notification@0.0.3...medusa-plugin-restock-notification@0.0.6) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-restock-notification
## [0.0.5](https://github.com/medusajs/medusa/compare/medusa-plugin-restock-notification@0.0.4...medusa-plugin-restock-notification@0.0.5) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-restock-notification
## [0.0.4](https://github.com/medusajs/medusa/compare/medusa-plugin-restock-notification@0.0.3...medusa-plugin-restock-notification@0.0.4) (2021-04-20)
### Features
* **medusa:** Swaps on swaps ([#229](https://github.com/medusajs/medusa/issues/229)) ([f8f1f57](https://github.com/medusajs/medusa/commit/f8f1f57fa1bcdc6f7ae4183e657a07e2641b1345))
## [0.0.3](https://github.com/medusajs/medusa/compare/medusa-plugin-restock-notification@0.0.2...medusa-plugin-restock-notification@0.0.3) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-restock-notification
## 0.0.2 (2021-04-13)
### Bug Fixes
* .gitignore ([684c20a](https://github.com/medusajs/medusa/commit/684c20ab293237f91fc160a269fd072c5de7012b))
* adds tests ([69442a1](https://github.com/medusajs/medusa/commit/69442a1735193aeb010043f114d89037d4d76279))
* cors ([15bbb71](https://github.com/medusajs/medusa/commit/15bbb71a46efe00af3bd46bc16dfd48439204587))
* cors ([e4a30e8](https://github.com/medusajs/medusa/commit/e4a30e8afc84eb201b0ddcb027bbe5674d0aff8f))
* cors ([967134e](https://github.com/medusajs/medusa/commit/967134e797a867fd84064d3764815961a976015b))
* creates restock functionality ([2b25550](https://github.com/medusajs/medusa/commit/2b2555004e52e97c15bfca59e030fdfc3d86ae49))
* deps ([a9ea38c](https://github.com/medusajs/medusa/commit/a9ea38c2005beb63e14ed151e25ecd26819c748c))
* gitignore ([fa1fe9d](https://github.com/medusajs/medusa/commit/fa1fe9d619e19a277db6ee3a25ebb177222fa04b))
* merge ([7897610](https://github.com/medusajs/medusa/commit/78976106209b35730d69817b52595b6008590159))
* peerdependencies ([40725c6](https://github.com/medusajs/medusa/commit/40725c6d0a643369a710cfc7cbf5b5f65a4f1f93))
* restock ([237ed51](https://github.com/medusajs/medusa/commit/237ed5130760645c6b892fa1d5fc09a713b95f58))
* **segment:** swap tracking ([295f0f6](https://github.com/medusajs/medusa/commit/295f0f652a0880292a3788b9c65476a3c5c1b8d4))
* working api ([9d81097](https://github.com/medusajs/medusa/commit/9d810971a7e0de2a586b5c9c372f0aad2818918b))
### Features
* restock service ([8bd5fa8](https://github.com/medusajs/medusa/commit/8bd5fa821286a90f3ab21e8c96993ac543fb7cab))
@@ -0,0 +1,89 @@
# medusa-plugin-restock-notification
## Usage
Install the plugin:
`$ yarn add medusa-plugin-restock-notification`
```js
// medusa-config.js
module.exports = {
...,
plugins: [
...,
`medusa-plugin-restock-notification`
]
}
```
The plugin will migrate your database to include the RestockNotification entity, which consists of a variant id of a sold out item and a jsonb list of arrays that wish to be notified about restocks for the item.
## API endpoint
The plugin exposes an endpoint to sign emails up for restock notifications:
```
POST /restock-notifications/variants/:variant_id
Body
{
"email": "seb@test.com"
}
```
The endpoint responds with `200 OK` on succesful signups. If a signup for an already in stock item is attempted the endpoint will have a 400 response code.
## Restock events
The plugin listens for the `product-variant.updated` call and emits a `restock-notification.restocked` event when a variant with restock signups become available.
The data sent with the `restock-notification.restocked` event is:
```
variant_id: The id of the variant to listen for restock events for.
emails: An array of emails that are to be notified of restocks.
e.g.
{
"variant_id": "variant_1234567890",
"emails": ["seb@test.com", "oli@test.com"]
}
```
*Note: This plugin does not send any communication to the customer, communication logic must be implemented or provided through a communication plugin.*
You may use `medusa-plugin-sendgrid` to orchestrate transactional emails.
## Usage with medusa-plugin-sendgrid
Install the plugins:
`$ yarn add medusa-plugin-restock-notification medusa-plugin-sendgrid`
```js
// medusa-config.js
module.exports = {
...,
plugins: [
...,
`medusa-plugin-restock-notification`,
{
resolve: `medusa-plugin-sendgrid`,
options: {
from: SENDGRID_FROM,
api_key: SENDGRID_API_KEY,
medusa_restock_template: `d-13141234123412342314`
}
}
]
}
```
You should set up a dynamic template in SendGrid which will be send for each of the emails in the restock notification.
@@ -0,0 +1 @@
// noop
@@ -0,0 +1,43 @@
{
"name": "medusa-plugin-restock-notification",
"version": "0.0.7",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-restock-notification"
},
"author": "Sebastian Rindom <seb@medusa-commerce.com>",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/plugin-transform-typescript": "^7.13.0",
"@babel/preset-typescript": "^7.12.7",
"@medusajs/medusa": "^1.1.23",
"babel-preset-medusa-package": "^1.1.3",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.12",
"pg": "^8.5.1",
"ulid": "^2.3.0"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__ --extensions \".ts,.js\"",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__",
"test": "jest"
},
"peerDependencies": {
"@medusajs/medusa": "1.x",
"medusa-interfaces": "1.x"
},
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.9"
},
"gitHead": "982da259ed93fe1b618800c8693a5c9dfe312532"
}
@@ -0,0 +1,11 @@
import { Router } from "express"
import routes from "./routes"
export default (rootDirectory) => {
const app = Router()
routes(app, rootDirectory)
return app
}
@@ -0,0 +1 @@
export default (fn) => (...args) => fn(...args).catch(args[2])
@@ -0,0 +1,5 @@
import { default as wrap } from "./await-middleware"
export default {
wrap,
}
@@ -0,0 +1,25 @@
import { Validator, MedusaError } from "medusa-core-utils"
export default async (req, res) => {
const { variant_id } = req.params
const schema = Validator.object().keys({
email: Validator.string().required(),
})
const { value, error } = schema.validate(req.body)
if (error) {
res.status(400).json({ message: error.message })
return
}
try {
const restockNotificationService = req.scope.resolve(
"restockNotificationService"
)
await restockNotificationService.addEmail(variant_id, value.email)
res.sendStatus(201)
} catch (err) {
res.status(400).json({ message: err.message })
}
}
@@ -0,0 +1,29 @@
import { Router } from "express"
import bodyParser from "body-parser"
import cors from "cors"
import { getConfigFile } from "medusa-core-utils"
import middlewares from "../middleware"
const route = Router()
export default (app, rootDirectory) => {
app.use("/restock-notifications", route)
const { configModule } = getConfigFile(rootDirectory, "medusa-config")
const { projectConfig } = configModule
const corsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}
route.options("/variants/:variant_id", cors(corsOptions))
route.post(
"/variants/:variant_id",
cors(corsOptions),
bodyParser.json(),
middlewares.wrap(require("./add-email").default)
)
return app
}
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from "typeorm"
export class restockNotification1617703530229 implements MigrationInterface {
name = "restockNotification1617703530229"
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "restock_notification" ("variant_id" character varying NOT NULL, "emails" jsonb NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_49181ca04caac807fcec321705a" PRIMARY KEY ("variant_id"))`
)
await queryRunner.query(
`ALTER TABLE "restock_notification" ADD CONSTRAINT "FK_49181ca04caac807fcec321705a" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "restock_notification" DROP CONSTRAINT "FK_49181ca04caac807fcec321705a"`
)
await queryRunner.query(`DROP TABLE "restock_notification"`)
}
}
@@ -0,0 +1,54 @@
import {
Entity,
Index,
BeforeInsert,
Column,
DeleteDateColumn,
CreateDateColumn,
UpdateDateColumn,
PrimaryColumn,
ManyToOne,
JoinColumn,
} from "typeorm"
import { ProductVariant } from "@medusajs/medusa"
@Entity()
export class RestockNotification {
@PrimaryColumn()
variant_id: string
@ManyToOne(() => ProductVariant)
@JoinColumn({ name: "variant_id" })
variant: ProductVariant
@Column({ type: "jsonb" })
emails: string[]
@CreateDateColumn({ type: "timestamptz" })
created_at: Date
@UpdateDateColumn({ type: "timestamptz" })
updated_at: Date
}
/**
* @schema restock_notification
* title: "Restock Notification"
* description: "Holds a list of emails that wish to be notifed when an item is restocked."
* x-resourceId: restock_notification
* properties:
* variant_id:
* type: string
* description: "The id of the variant that customers have signed up to be notified about,"
* emails:
* type: string[]
* description: "The emails of customers who wish to be notified about restocks."
* created_at:
* type: string
* format: date-time
* description: "The date time at which the first restock signup was made."
* updated_at:
* type: string
* format: date-time
* description: "The date time at which the first last signup was made."
*/
@@ -0,0 +1,166 @@
import { MockManager, MockRepository } from "medusa-test-utils"
import RestockNotificationService from "../restock-notification"
describe("RestockNotificationService", () => {
const RestockNotificationModel = MockRepository({
findOne: (q) => {
if (q.where.variant_id === "variant_1234") {
return Promise.resolve({
variant_id: "variant_1234",
emails: ["test@tesmail.com"],
})
}
if (q.where.variant_id === "variant_outofstock") {
return Promise.resolve({
variant_id: "variant_outofstock",
emails: ["test@tesmail.com"],
})
}
return Promise.resolve()
},
})
const ProductVariantService = {
retrieve: (id) => {
if (id === "variant_instock") {
return {
id,
inventory_quantity: 10,
}
}
if (id === "variant_1234") {
return {
id,
inventory_quantity: 10,
}
}
return {
id,
inventory_quantity: 0,
}
},
}
const EventBusService = {
emit: jest.fn(),
withTransaction: function () {
return this
},
}
describe("retrieve", () => {
const restockNotiService = new RestockNotificationService({
manager: MockManager,
productVariantService: ProductVariantService,
restockNotificationModel: RestockNotificationModel,
eventBusService: EventBusService,
})
it("successfully retrieves", async () => {
jest.clearAllMocks()
const result = await restockNotiService.retrieve("variant_1234")
expect(result).toEqual({
variant_id: "variant_1234",
emails: ["test@tesmail.com"],
})
})
it("successfully retrieves with empty response", async () => {
jest.clearAllMocks()
const result = await restockNotiService.retrieve("variant_non")
expect(result).toEqual(undefined)
})
})
describe("addEmail", () => {
const restockNotiService = new RestockNotificationService({
manager: MockManager,
productVariantService: ProductVariantService,
restockNotificationModel: RestockNotificationModel,
eventBusService: EventBusService,
})
it("successfully adds email to non-existing noti", async () => {
jest.clearAllMocks()
await restockNotiService.addEmail("variant_test", "seb@med-test.com")
expect(RestockNotificationModel.create).toHaveBeenCalledTimes(1)
expect(RestockNotificationModel.create).toHaveBeenCalledWith({
variant_id: "variant_test",
emails: ["seb@med-test.com"],
})
expect(RestockNotificationModel.save).toHaveBeenCalledTimes(1)
})
it("successfully adds email to existing noti", async () => {
jest.clearAllMocks()
await restockNotiService.addEmail("variant_1234", "seb@med-test.com")
expect(RestockNotificationModel.save).toHaveBeenCalledTimes(1)
expect(RestockNotificationModel.save).toHaveBeenCalledWith({
variant_id: "variant_1234",
emails: ["test@tesmail.com", "seb@med-test.com"],
})
})
it("fails to add if in stock", async () => {
jest.clearAllMocks()
await expect(
restockNotiService.addEmail("variant_instock", "seb@med-test.com")
).rejects.toThrow(
"You cannot sign up for restock notifications on a product that is not sold out"
)
})
})
describe("triggerRestock", () => {
const restockNotiService = new RestockNotificationService({
manager: MockManager,
productVariantService: ProductVariantService,
restockNotificationModel: RestockNotificationModel,
eventBusService: EventBusService,
})
it("non-existing noti does nothing", async () => {
jest.clearAllMocks()
await expect(restockNotiService.triggerRestock("variant_test")).resolves
})
it("existing noti but out of stock does nothing", async () => {
jest.clearAllMocks()
await expect(restockNotiService.triggerRestock("variant_outofstock"))
.resolves
})
it("existing noti emits and deletes", async () => {
jest.clearAllMocks()
await restockNotiService.triggerRestock("variant_1234")
expect(EventBusService.emit).toHaveBeenCalledTimes(1)
expect(EventBusService.emit).toHaveBeenCalledWith(
"restock-notification.restocked",
{
variant_id: "variant_1234",
emails: ["test@tesmail.com"],
}
)
expect(RestockNotificationModel.delete).toHaveBeenCalledTimes(1)
expect(RestockNotificationModel.delete).toHaveBeenCalledWith(
"variant_1234"
)
})
})
})
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more