Fixes merge conflicts
This commit is contained in:
@@ -35,7 +35,6 @@
|
|||||||
"@babel/runtime": "^7.9.6",
|
"@babel/runtime": "^7.9.6",
|
||||||
"@hapi/joi": "^16.1.8",
|
"@hapi/joi": "^16.1.8",
|
||||||
"chalk": "^4.0.0",
|
"chalk": "^4.0.0",
|
||||||
"clipboardy": "^2.3.0",
|
|
||||||
"core-js": "^3.6.5",
|
"core-js": "^3.6.5",
|
||||||
"fs-exists-cached": "^1.0.0",
|
"fs-exists-cached": "^1.0.0",
|
||||||
"joi-objectid": "^3.0.1",
|
"joi-objectid": "^3.0.1",
|
||||||
|
|||||||
@@ -3,9 +3,7 @@ const resolveCwd = require(`resolve-cwd`)
|
|||||||
const yargs = require(`yargs`)
|
const yargs = require(`yargs`)
|
||||||
const { getLocalMedusaVersion } = require(`./util/version`)
|
const { getLocalMedusaVersion } = require(`./util/version`)
|
||||||
const { didYouMean } = require(`./did-you-mean`)
|
const { didYouMean } = require(`./did-you-mean`)
|
||||||
const envinfo = require(`envinfo`)
|
|
||||||
const existsSync = require(`fs-exists-cached`).sync
|
const existsSync = require(`fs-exists-cached`).sync
|
||||||
const clipboardy = require(`clipboardy`)
|
|
||||||
|
|
||||||
const handlerP = fn => (...args) => {
|
const handlerP = fn => (...args) => {
|
||||||
Promise.resolve(fn(...args)).then(
|
Promise.resolve(fn(...args)).then(
|
||||||
|
|||||||
@@ -1247,11 +1247,6 @@ anymatch@^3.0.3:
|
|||||||
normalize-path "^3.0.0"
|
normalize-path "^3.0.0"
|
||||||
picomatch "^2.0.4"
|
picomatch "^2.0.4"
|
||||||
|
|
||||||
arch@^2.1.1:
|
|
||||||
version "2.1.1"
|
|
||||||
resolved "https://registry.yarnpkg.com/arch/-/arch-2.1.1.tgz#8f5c2731aa35a30929221bb0640eed65175ec84e"
|
|
||||||
integrity sha512-BLM56aPo9vLLFVa8+/+pJLnrZ7QGGTVHWsCwieAWT9o9K8UeGaQbzZbGoabWLOo2ksBCztoXdqBZBplqLDDCSg==
|
|
||||||
|
|
||||||
argparse@^1.0.7:
|
argparse@^1.0.7:
|
||||||
version "1.0.10"
|
version "1.0.10"
|
||||||
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
|
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911"
|
||||||
@@ -1616,15 +1611,6 @@ cli-width@^2.0.0:
|
|||||||
resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.1.tgz#b0433d0b4e9c847ef18868a4ef16fd5fc8271c48"
|
resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-2.2.1.tgz#b0433d0b4e9c847ef18868a4ef16fd5fc8271c48"
|
||||||
integrity sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==
|
integrity sha512-GRMWDxpOB6Dgk2E5Uo+3eEBvtOOlimMmpbFiKuLFnQzYDavtLFY3K5ona41jgN/WdRZtG7utuVSVTL4HbZHGkw==
|
||||||
|
|
||||||
clipboardy@^2.3.0:
|
|
||||||
version "2.3.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/clipboardy/-/clipboardy-2.3.0.tgz#3c2903650c68e46a91b388985bc2774287dba290"
|
|
||||||
integrity sha512-mKhiIL2DrQIsuXMgBgnfEHOZOryC7kY7YO//TN6c63wlEm3NG5tz+YgY5rVi29KCmq/QQjKYvM7a19+MDOTHOQ==
|
|
||||||
dependencies:
|
|
||||||
arch "^2.1.1"
|
|
||||||
execa "^1.0.0"
|
|
||||||
is-wsl "^2.1.1"
|
|
||||||
|
|
||||||
cliui@^6.0.0:
|
cliui@^6.0.0:
|
||||||
version "6.0.0"
|
version "6.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/cliui/-/cliui-6.0.0.tgz#511d702c0c4e41ca156d7d0e96021f23e13225b1"
|
resolved "https://registry.yarnpkg.com/cliui/-/cliui-6.0.0.tgz#511d702c0c4e41ca156d7d0e96021f23e13225b1"
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"plugins": [
|
||||||
|
"@babel/plugin-proposal-class-properties",
|
||||||
|
"@babel/plugin-transform-instanceof",
|
||||||
|
"@babel/plugin-transform-classes"
|
||||||
|
],
|
||||||
|
"presets": ["@babel/preset-env"],
|
||||||
|
"env": {
|
||||||
|
"test": {
|
||||||
|
"plugins": ["@babel/plugin-transform-runtime"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"plugins": ["prettier"],
|
||||||
|
"extends": ["prettier"],
|
||||||
|
"rules": {
|
||||||
|
"prettier/prettier": "error",
|
||||||
|
"semi": "error",
|
||||||
|
"no-unused-expressions": "true"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/lib
|
||||||
|
node_modules
|
||||||
|
.DS_store
|
||||||
|
.env*
|
||||||
|
/*.js
|
||||||
|
!index.js
|
||||||
|
!jest.config.js
|
||||||
|
|
||||||
|
dist
|
||||||
|
|
||||||
@@ -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 @@
|
|||||||
|
// noop
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
testEnvironment: "node",
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "medusa-payment-klarna",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Klarna Payment provider for Medusa Commerce",
|
||||||
|
"main": "index.js",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/medusajs/medusa",
|
||||||
|
"directory": "packages/medusa-payment-klarna"
|
||||||
|
},
|
||||||
|
"author": "Oliver Juhl",
|
||||||
|
"license": "AGPL-3.0-or-later",
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/cli": "^7.7.5",
|
||||||
|
"@babel/core": "^7.7.5",
|
||||||
|
"@babel/node": "^7.7.4",
|
||||||
|
"@babel/plugin-proposal-class-properties": "^7.7.4",
|
||||||
|
"@babel/plugin-transform-instanceof": "^7.8.3",
|
||||||
|
"@babel/plugin-transform-runtime": "^7.7.6",
|
||||||
|
"@babel/preset-env": "^7.7.5",
|
||||||
|
"@babel/register": "^7.7.4",
|
||||||
|
"@babel/runtime": "^7.9.6",
|
||||||
|
"client-sessions": "^0.8.0",
|
||||||
|
"cross-env": "^5.2.1",
|
||||||
|
"eslint": "^6.8.0",
|
||||||
|
"jest": "^25.5.2"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "babel src -d dist",
|
||||||
|
"prepare": "cross-env NODE_ENV=production npm run build",
|
||||||
|
"watch": "babel -w src --out-dir . --ignore **/__tests__",
|
||||||
|
"test": "jest"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@babel/plugin-transform-classes": "^7.9.5",
|
||||||
|
"axios": "^0.19.2",
|
||||||
|
"body-parser": "^1.19.0",
|
||||||
|
"express": "^4.17.1",
|
||||||
|
"medusa-core-utils": "^0.3.0",
|
||||||
|
"medusa-interfaces": "^0.3.0",
|
||||||
|
"medusa-test-utils": "^0.3.0"
|
||||||
|
},
|
||||||
|
"gitHead": "35e0930650d5f4aedf2610749cd131ae8b7e17cc"
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
const mockAxios = jest.genMockFromModule("axios")
|
||||||
|
|
||||||
|
mockAxios.create = jest.fn(() => mockAxios)
|
||||||
|
|
||||||
|
export default mockAxios
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { IdMap } from "medusa-test-utils"
|
||||||
|
|
||||||
|
export const carts = {
|
||||||
|
frCart: {
|
||||||
|
_id: IdMap.getId("fr-cart"),
|
||||||
|
email: "lebron@james.com",
|
||||||
|
title: "test",
|
||||||
|
region_id: IdMap.getId("region-france"),
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
_id: IdMap.getId("line"),
|
||||||
|
title: "merge line",
|
||||||
|
description: "This is a new line",
|
||||||
|
thumbnail: "test-img-yeah.com/thumb",
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
unit_price: 8,
|
||||||
|
variant: {
|
||||||
|
_id: IdMap.getId("eur-8-us-10"),
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
_id: IdMap.getId("product"),
|
||||||
|
},
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
unit_price: 10,
|
||||||
|
variant: {
|
||||||
|
_id: IdMap.getId("eur-10-us-12"),
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
_id: IdMap.getId("product"),
|
||||||
|
},
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
quantity: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
_id: IdMap.getId("existingLine"),
|
||||||
|
title: "merge line",
|
||||||
|
description: "This is a new line",
|
||||||
|
thumbnail: "test-img-yeah.com/thumb",
|
||||||
|
content: {
|
||||||
|
unit_price: 10,
|
||||||
|
variant: {
|
||||||
|
_id: IdMap.getId("eur-10-us-12"),
|
||||||
|
},
|
||||||
|
product: {
|
||||||
|
_id: IdMap.getId("product"),
|
||||||
|
},
|
||||||
|
quantity: 1,
|
||||||
|
},
|
||||||
|
quantity: 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
shipping_methods: [
|
||||||
|
{
|
||||||
|
_id: IdMap.getId("freeShipping"),
|
||||||
|
profile_id: "default_profile",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
shipping_options: [
|
||||||
|
{
|
||||||
|
_id: IdMap.getId("freeShipping"),
|
||||||
|
profile_id: "default_profile",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
payment_sessions: [
|
||||||
|
{
|
||||||
|
provider_id: "stripe",
|
||||||
|
data: {
|
||||||
|
id: "pi_123456789",
|
||||||
|
customer: IdMap.getId("not-lebron"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
payment_method: {
|
||||||
|
provider_id: "stripe",
|
||||||
|
data: {
|
||||||
|
id: "pi_123456789",
|
||||||
|
customer: IdMap.getId("not-lebron"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
shipping_address: {},
|
||||||
|
billing_address: {},
|
||||||
|
discounts: [
|
||||||
|
{
|
||||||
|
code: "MEDUSA_FREE",
|
||||||
|
discount_rule: {
|
||||||
|
type: "percent",
|
||||||
|
value: 20,
|
||||||
|
allocation: "item",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
customer_id: IdMap.getId("lebron"),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CartServiceMock = {
|
||||||
|
retrieve: jest.fn().mockImplementation((cartId) => {
|
||||||
|
if (cartId === IdMap.getId("fr-cart")) {
|
||||||
|
return Promise.resolve(carts.frCart)
|
||||||
|
}
|
||||||
|
return Promise.resolve(undefined)
|
||||||
|
}),
|
||||||
|
updatePaymentSession: jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation((cartId, stripe, paymentIntent) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const mock = jest.fn().mockImplementation(() => {
|
||||||
|
return CartServiceMock
|
||||||
|
})
|
||||||
|
|
||||||
|
export default mock
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { IdMap } from "medusa-test-utils"
|
||||||
|
|
||||||
|
export const RegionServiceMock = {
|
||||||
|
retrieve: jest.fn().mockImplementation((regionId) => {
|
||||||
|
return Promise.resolve({
|
||||||
|
_id: IdMap.getId("testRegion"),
|
||||||
|
name: "Test Region",
|
||||||
|
countries: ["DK", "US", "DE"],
|
||||||
|
tax_rate: 0.25,
|
||||||
|
payment_providers: ["default_provider", "unregistered"],
|
||||||
|
fulfillment_providers: ["test_shipper"],
|
||||||
|
currency_code: "usd",
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const mock = jest.fn().mockImplementation(() => {
|
||||||
|
return RegionServiceMock
|
||||||
|
})
|
||||||
|
|
||||||
|
export default mock
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
export const TotalsServiceMock = {
|
||||||
|
getTotal: jest.fn(),
|
||||||
|
getTaxTotal: jest.fn(),
|
||||||
|
getAllocationItemDiscounts: jest.fn(),
|
||||||
|
}
|
||||||
|
|
||||||
|
const mock = jest.fn().mockImplementation(() => {
|
||||||
|
return TotalsServiceMock
|
||||||
|
})
|
||||||
|
|
||||||
|
export default mock
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Router } from "express"
|
||||||
|
import hooks from "./routes/hooks"
|
||||||
|
|
||||||
|
export default (container) => {
|
||||||
|
const app = Router()
|
||||||
|
|
||||||
|
hooks(app)
|
||||||
|
|
||||||
|
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,39 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
// In Medusa, we store the cart id in merchant_data
|
||||||
|
const { shipping_address, merchant_data } = req.body
|
||||||
|
|
||||||
|
try {
|
||||||
|
const cartService = req.resolve("cartService")
|
||||||
|
const klarnaProviderService = req.resolve("pp_klarna")
|
||||||
|
|
||||||
|
const cart = await cartService.retrieve(merchant_data)
|
||||||
|
|
||||||
|
if (shipping_address) {
|
||||||
|
const updatedAddress = {
|
||||||
|
email: shipping_address.email,
|
||||||
|
street_address: shipping_address.address_1,
|
||||||
|
street_address2: shipping_address.address_2,
|
||||||
|
postal_code: shipping_address.postal_code,
|
||||||
|
city: shipping_address.city,
|
||||||
|
country: shipping_address.country_code,
|
||||||
|
}
|
||||||
|
|
||||||
|
await cartService.update(cart._id, {
|
||||||
|
email: shipping_address.email,
|
||||||
|
shipping_address: updatedAddress,
|
||||||
|
billing_address: updatedAddress,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Fetch and return updated Klarna order
|
||||||
|
const updatedCart = await cartService.retrieve(cart._id)
|
||||||
|
const order = klarnaProviderService.cartToKlarnaOrder(updatedCart)
|
||||||
|
res.json(order)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
res.sendStatus(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Router } from "express"
|
||||||
|
import middlewares from "../../middlewares"
|
||||||
|
|
||||||
|
const route = Router()
|
||||||
|
|
||||||
|
export default (app) => {
|
||||||
|
app.use("/hooks", route)
|
||||||
|
|
||||||
|
route.post("/shipping", middlewares.wrap(require("./shippping").default))
|
||||||
|
route.post("/address", middlewares.wrap(require("./address").default))
|
||||||
|
route.post("/push", middlewares.wrap(require("./push").default))
|
||||||
|
|
||||||
|
return app
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
const { klarna_order_id } = req.query
|
||||||
|
|
||||||
|
try {
|
||||||
|
const orderService = req.resolve("orderService")
|
||||||
|
const klarnaProviderService = req.resolve("pp_klarna")
|
||||||
|
|
||||||
|
const klarnaOrder = await klarnaProviderService.retrieveCompletedOrder(
|
||||||
|
klarna_order_id
|
||||||
|
)
|
||||||
|
|
||||||
|
const cartId = klarnaOrder.merchant_data
|
||||||
|
const order = await orderService.list({ cart_id: cartId })[0]
|
||||||
|
|
||||||
|
await klarnaProviderService.acknowledgeOrder(klarnaOrder.id, order._id)
|
||||||
|
res.sendStatus(200)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
// In Medusa, we store the cart id in merchant_data
|
||||||
|
const { merchant_data, selected_shipping_option } = req.body
|
||||||
|
|
||||||
|
try {
|
||||||
|
const cartService = req.resolve("cartService")
|
||||||
|
const klarnaProviderService = req.resolve("pp_klarna")
|
||||||
|
|
||||||
|
const cart = await cartService.retrieve(merchant_data)
|
||||||
|
const updatedMethod = cart.shipping_options.find(
|
||||||
|
(so) => so._id === selected_shipping_option.id
|
||||||
|
)
|
||||||
|
|
||||||
|
if (updatedMethod) {
|
||||||
|
await cartService.update(cart._id, {
|
||||||
|
shipping_methods: [updatedMethod],
|
||||||
|
})
|
||||||
|
|
||||||
|
// Fetch and return updated Klarna order
|
||||||
|
const updatedCart = await cartService.retrieve(cart._id)
|
||||||
|
const order = klarnaProviderService.cartToKlarnaOrder(updatedCart)
|
||||||
|
res.json(order)
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
res.sendStatus(400)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { IdMap } from "medusa-test-utils"
|
||||||
|
|
||||||
|
export const KlarnaProviderServiceMock = {
|
||||||
|
retrievePayment: jest.fn().mockImplementation((cart) => {
|
||||||
|
if (cart._id === IdMap.getId("fr-cart")) {
|
||||||
|
return Promise.resolve({
|
||||||
|
order_id: "123456789",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return Promise.resolve(undefined)
|
||||||
|
}),
|
||||||
|
cancelPayment: jest.fn().mockImplementation((cart) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
}),
|
||||||
|
updatePayment: jest.fn().mockImplementation((cart) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
}),
|
||||||
|
capturePayment: jest.fn().mockImplementation((cart) => {
|
||||||
|
if (cart._id === IdMap.getId("fr-cart")) {
|
||||||
|
return Promise.resolve({
|
||||||
|
id: "123456789",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return Promise.resolve(undefined)
|
||||||
|
}),
|
||||||
|
createPayment: jest.fn().mockImplementation((cart) => {
|
||||||
|
if (cart._id === IdMap.getId("fr-cart")) {
|
||||||
|
return Promise.resolve({
|
||||||
|
id: "123456789",
|
||||||
|
order_amount: 100,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return Promise.resolve(undefined)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
|
||||||
|
const mock = jest.fn().mockImplementation(() => {
|
||||||
|
return KlarnaProviderServiceMock
|
||||||
|
})
|
||||||
|
|
||||||
|
export default mock
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
import KlarnaProviderService from "../klarna-provider"
|
||||||
|
import mockAxios from "../../__mocks__/axios"
|
||||||
|
import { carts } from "../../__mocks__/cart"
|
||||||
|
import { TotalsServiceMock } from "../../__mocks__/totals"
|
||||||
|
import { RegionServiceMock } from "../../__mocks__/region"
|
||||||
|
|
||||||
|
describe("KlarnaProviderService", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockAxios.mockClear()
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("createPayment", () => {
|
||||||
|
let result
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
regionService: RegionServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
merchant_urls: {
|
||||||
|
terms: "terms",
|
||||||
|
checkout: "checkout",
|
||||||
|
confirmation: "confirmation",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
it("creates Klarna order", async () => {
|
||||||
|
mockAxios.post.mockImplementation(() => {
|
||||||
|
return Promise.resolve({
|
||||||
|
order_id: "123456789",
|
||||||
|
order_amount: 100,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.createPayment(carts.frCart)
|
||||||
|
expect(result).toEqual({
|
||||||
|
order_id: "123456789",
|
||||||
|
order_amount: 100,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("retrievePayment", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns Klarna order", async () => {
|
||||||
|
mockAxios.get.mockImplementation((data) => {
|
||||||
|
return Promise.resolve({
|
||||||
|
order_id: "123456789",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.retrievePayment({
|
||||||
|
payment_method: {
|
||||||
|
data: {
|
||||||
|
id: "123456789",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
order_id: "123456789",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("retrieveCompletedOrder", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns completed Klarna order", async () => {
|
||||||
|
mockAxios.get.mockImplementation((data) => {
|
||||||
|
return Promise.resolve({
|
||||||
|
order_id: "123456789",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.retrieveCompletedOrder({
|
||||||
|
payment_method: {
|
||||||
|
data: {
|
||||||
|
id: "123456789",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
order_id: "123456789",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("updatePayment", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns updated Klarna order", async () => {
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve({
|
||||||
|
order_id: "123456789",
|
||||||
|
order_amount: 1000,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.updatePayment(
|
||||||
|
{
|
||||||
|
payment_method: {
|
||||||
|
data: {
|
||||||
|
id: "123456789",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
order_amount: 1000,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
order_id: "123456789",
|
||||||
|
order_amount: 1000,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("cancelPayment", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns order id", async () => {
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.cancelPayment({ id: "123456789" })
|
||||||
|
|
||||||
|
expect(result).toEqual("123456789")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("acknowledgeOrder", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns order id", async () => {
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve({})
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.acknowledgeOrder("123456789")
|
||||||
|
|
||||||
|
expect(result).toEqual("123456789")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("addOrderToKlarnaOrder", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns order id", async () => {
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.addOrderToKlarnaOrder(
|
||||||
|
"123456789",
|
||||||
|
"order123456789"
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).toEqual("123456789")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("capturePayment", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns order id", async () => {
|
||||||
|
mockAxios.get.mockImplementation((data) => {
|
||||||
|
return Promise.resolve({
|
||||||
|
order: { order_amount: 1000 },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.capturePayment({
|
||||||
|
id: "123456789",
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(result).toEqual("123456789")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe("refundPayment", () => {
|
||||||
|
let result
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
const klarnaProviderService = new KlarnaProviderService(
|
||||||
|
{
|
||||||
|
totalsService: TotalsServiceMock,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
url: "medusajs/tests",
|
||||||
|
user: "lebronjames",
|
||||||
|
password: "123456789",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
it("returns order id", async () => {
|
||||||
|
mockAxios.post.mockImplementation((data) => {
|
||||||
|
return Promise.resolve()
|
||||||
|
})
|
||||||
|
|
||||||
|
result = await klarnaProviderService.capturePayment(
|
||||||
|
{
|
||||||
|
id: "123456789",
|
||||||
|
},
|
||||||
|
1000
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(result).toEqual("123456789")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
import _ from "lodash"
|
||||||
|
import axios from "axios"
|
||||||
|
import { PaymentService } from "medusa-interfaces"
|
||||||
|
|
||||||
|
class KlarnaProviderService extends PaymentService {
|
||||||
|
static identifier = "klarna"
|
||||||
|
|
||||||
|
constructor({ totalsService, regionService }, options) {
|
||||||
|
super()
|
||||||
|
|
||||||
|
this.options_ = options
|
||||||
|
|
||||||
|
this.klarna_ = axios.create({
|
||||||
|
baseURL: options.url,
|
||||||
|
auth: {
|
||||||
|
username: options.user,
|
||||||
|
password: options.password,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
this.klarnaOrderUrl_ = "/checkout/v3/orders"
|
||||||
|
|
||||||
|
this.klarnaOrderManagementUrl_ = "/ordermanagement/v1/orders"
|
||||||
|
|
||||||
|
this.backendUrl_ = process.env.BACKEND_URL || ""
|
||||||
|
|
||||||
|
this.totalsService_ = totalsService
|
||||||
|
|
||||||
|
this.regionService_ = regionService
|
||||||
|
}
|
||||||
|
|
||||||
|
async lineItemsToOrderLines_(cart, taxRate) {
|
||||||
|
let order_lines = []
|
||||||
|
// Find the discount, that is not free shipping
|
||||||
|
const discount = cart.discounts.find(
|
||||||
|
({ discount_rule }) => discount_rule.type !== "free_shipping"
|
||||||
|
)
|
||||||
|
// If the discount has an item specific allocation method,
|
||||||
|
// we need to fetch the discount for each item
|
||||||
|
const itemDiscounts = await this.totalsService_.getAllocationItemDiscounts(
|
||||||
|
discount,
|
||||||
|
cart
|
||||||
|
)
|
||||||
|
|
||||||
|
cart.items.forEach((item) => {
|
||||||
|
// For bundles, we create an order line for each item in the bundle
|
||||||
|
if (Array.isArray(item.content)) {
|
||||||
|
item.content.forEach((c) => {
|
||||||
|
const total_amount = c.unit_price * c.quantity * (taxRate + 1)
|
||||||
|
const total_tax_amount = total_amount * taxRate
|
||||||
|
|
||||||
|
order_lines.push({
|
||||||
|
unit_price: c.unit_price,
|
||||||
|
// Medusa does not allow discount on bundles
|
||||||
|
total_discount_amount: 0,
|
||||||
|
quantity: c.quantity,
|
||||||
|
tax_rate: taxRate,
|
||||||
|
total_amount,
|
||||||
|
total_tax_amount,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
const total_amount =
|
||||||
|
item.content.unit_price * item.content.quantity * (taxRate + 1)
|
||||||
|
const total_tax_amount = total_amount * taxRate
|
||||||
|
|
||||||
|
// Find the discount for current item and default to 0
|
||||||
|
const itemDiscount =
|
||||||
|
(itemDiscounts &&
|
||||||
|
itemDiscounts.find((el) => el.lineItem._id === item._id)) ||
|
||||||
|
0
|
||||||
|
|
||||||
|
// Withdraw discount from the total item amount
|
||||||
|
const total_discount_amount =
|
||||||
|
total_amount - itemDiscount * (taxRate + 1)
|
||||||
|
|
||||||
|
order_lines.push({
|
||||||
|
unit_price: item.content.unit_price,
|
||||||
|
quantity: item.content.quantity,
|
||||||
|
total_discount_amount,
|
||||||
|
tax_rate: taxRate,
|
||||||
|
total_amount,
|
||||||
|
total_tax_amount,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async cartToKlarnaOrder(cart) {
|
||||||
|
let order = {
|
||||||
|
// Cart id is stored, such that we can use it for hooks
|
||||||
|
merchant_data: cart._id,
|
||||||
|
// TODO: Investigate if other locales are needed
|
||||||
|
locale: "en-US",
|
||||||
|
}
|
||||||
|
|
||||||
|
const { tax_rate, currency_code } = await this.regionService_.retrieve(
|
||||||
|
cart.region_id
|
||||||
|
)
|
||||||
|
|
||||||
|
order.order_lines = this.lineItemsToOrderLines_(cart, tax_rate)
|
||||||
|
|
||||||
|
if (cart.billing_address) {
|
||||||
|
order.billing_address = {
|
||||||
|
email: cart.email,
|
||||||
|
street_address: cart.billing_address.address_1,
|
||||||
|
street_address2: cart.billing_address.address_2,
|
||||||
|
postal_code: cart.billing_address.postal_code,
|
||||||
|
city: cart.billing_address.city,
|
||||||
|
country: cart.billing_address.country_code,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Check if country matches ISO
|
||||||
|
if (cart.billing_address.country) {
|
||||||
|
order.purchase_country = cart.billing_address.country
|
||||||
|
} else {
|
||||||
|
// Defaults to Sweden
|
||||||
|
order.purchase_country = "SE"
|
||||||
|
}
|
||||||
|
|
||||||
|
order.order_amount = this.totalsService_.getTotal(cart)
|
||||||
|
order.order_tax_amount = this.totalsService_.getTaxTotal(cart)
|
||||||
|
// TODO: Check if currency matches ISO
|
||||||
|
order.purchase_currency = currency_code
|
||||||
|
|
||||||
|
order.merchant_urls = {
|
||||||
|
terms: this.options_.merchant_urls.terms,
|
||||||
|
checkout: this.options_.merchant_urls.checkout,
|
||||||
|
confirmation: this.options_.merchant_urls.confirmation,
|
||||||
|
push: `${this.backendUrl_}/klarna/hooks/push`,
|
||||||
|
shipping_option_update: `${this.backendUrl_}/klarna/hooks/shipping`,
|
||||||
|
address_update: `${this.backendUrl_}/klarna/hooks/address`,
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the cart does not have shipping methods yet, preselect one from
|
||||||
|
// shipping_options and set the selected shipping method
|
||||||
|
if (!cart.shipping_methods) {
|
||||||
|
const shipping_method = cart.shipping_options[0]
|
||||||
|
order.selected_shipping_option = {
|
||||||
|
id: shipping_method._id,
|
||||||
|
// TODO: Add shipping method name
|
||||||
|
name: shipping_method.provider_id,
|
||||||
|
price: shipping_method.price * (1 + tax_rate) * 100,
|
||||||
|
tax_amount: shipping_method.price * tax_rate * 100,
|
||||||
|
// Medusa tax rate of e.g. 0.25 (25%) needs to be 2500 in Klarna
|
||||||
|
tax_rate: tax_rate * 10000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the cart does have shipping methods, set the selected shipping method
|
||||||
|
if (cart.shipping_methods) {
|
||||||
|
const shipping_method = cart.shipping_methods[0]
|
||||||
|
order.selected_shipping_option = {
|
||||||
|
id: shipping_method._id,
|
||||||
|
name: shipping_method.provider_id,
|
||||||
|
price: shipping_method.price * (1 + tax_rate) * 100,
|
||||||
|
tax_amount: shipping_method.price * tax_rate * 100,
|
||||||
|
tax_rate: tax_rate * 10000,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
order.shipping_options = cart.shipping_options.map((so) => ({
|
||||||
|
id: so._id,
|
||||||
|
name: so.provider_id,
|
||||||
|
price: so.price * (1 + tax_rate) * 100,
|
||||||
|
tax_amount: so.price * tax_rate * 100,
|
||||||
|
tax_rate: tax_rate * 10000,
|
||||||
|
preselected:
|
||||||
|
cart.shipping_methods[0] &&
|
||||||
|
`${cart.shipping_methods[0].provider_id}` === `${so.provider_id}`,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Status for Klarna order.
|
||||||
|
* @param {Object} paymentData - payment method data from cart
|
||||||
|
* @returns {string} the status of the Klarna order
|
||||||
|
*/
|
||||||
|
async getStatus(paymentData) {
|
||||||
|
try {
|
||||||
|
const { id } = paymentData
|
||||||
|
const order = await this.klarna_.get(`${this.klarnaOrderUrl_}/${id}`)
|
||||||
|
// TODO: Klarna docs does not provide a list of statues, so we need to
|
||||||
|
// play around our selves to figure it out
|
||||||
|
let status = "initial"
|
||||||
|
return status
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates Stripe PaymentIntent.
|
||||||
|
* @param {string} cart - the cart to create a payment for
|
||||||
|
* @param {number} amount - the amount to create a payment for
|
||||||
|
* @returns {string} id of payment intent
|
||||||
|
*/
|
||||||
|
async createPayment(cart) {
|
||||||
|
try {
|
||||||
|
const order = await this.cartToKlarnaOrder(cart)
|
||||||
|
return this.klarna_.post(this.klarnaOrderUrl__, order)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves Klarna Order.
|
||||||
|
* @param {string} cart - the cart to retrieve order for
|
||||||
|
* @returns {Object} Klarna order
|
||||||
|
*/
|
||||||
|
async retrievePayment(cart) {
|
||||||
|
try {
|
||||||
|
const { data } = cart.payment_method
|
||||||
|
return this.klarna_.get(`${this.klarnaOrderUrl_}/${data.id}`)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves completed Klarna Order.
|
||||||
|
* @param {string} klarnaOrderId - id of the order to retrieve
|
||||||
|
* @returns {Object} Klarna order
|
||||||
|
*/
|
||||||
|
async retrieveCompletedOrder(klarnaOrderId) {
|
||||||
|
try {
|
||||||
|
return this.klarna_.get(
|
||||||
|
`${this.klarnaOrderManagementUrl_}/${klarnaOrderId}`
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acknowledges a Klarna order as part of the order completion process
|
||||||
|
* @param {string} klarnaOrderId - id of the order to acknowledge
|
||||||
|
* @returns {string} id of acknowledged order
|
||||||
|
*/
|
||||||
|
async acknowledgeOrder(klarnaOrderId) {
|
||||||
|
try {
|
||||||
|
await this.klarna_.post(
|
||||||
|
`${this.klarnaOrderManagementUrl_}/${klarnaOrderId}/acknowledge`,
|
||||||
|
{}
|
||||||
|
)
|
||||||
|
return klarnaOrderId
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds the id of the Medusa order to the Klarna Order to create a relation
|
||||||
|
* @param {string} klarnaOrderId - id of the klarna order
|
||||||
|
* @param {string} orderId - id of the Medusa order
|
||||||
|
* @returns {string} id of updated order
|
||||||
|
*/
|
||||||
|
async addOrderToKlarnaOrder(klarnaOrderId, orderId) {
|
||||||
|
try {
|
||||||
|
await this.klarna_.post(
|
||||||
|
`${this.klarnaOrderManagementUrl_}/${klarnaOrderId}/merchant-references`,
|
||||||
|
{
|
||||||
|
merchant_reference1: orderId,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return klarnaOrderId
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates Klarna order.
|
||||||
|
* @param {string} order - the order to update
|
||||||
|
* @param {Object} data - the update object
|
||||||
|
* @returns {Object} updated order
|
||||||
|
*/
|
||||||
|
async updatePayment(order, update) {
|
||||||
|
try {
|
||||||
|
const { data } = order.payment_method
|
||||||
|
return this.klarna_.post(`${this.klarnaOrderUrl_}/${data.id}`, update)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Captures Klarna order.
|
||||||
|
* @param {Object} paymentData - payment method data from cart
|
||||||
|
* @returns {string} id of captured order
|
||||||
|
*/
|
||||||
|
async capturePayment(paymentData) {
|
||||||
|
try {
|
||||||
|
const { id } = paymentData
|
||||||
|
const orderData = await this.klarna_.get(`${this.klarnaOrderUrl_}/${id}`)
|
||||||
|
const { order_amount } = orderData.order
|
||||||
|
|
||||||
|
await this.klarna_.post(
|
||||||
|
`${this.klarnaOrderManagementUrl_}/${id}/captures`,
|
||||||
|
{
|
||||||
|
captured_amount: order_amount,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return id
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refunds payment for Klarna Order.
|
||||||
|
* @param {Object} paymentData - payment method data from cart
|
||||||
|
* @returns {string} id of refunded order
|
||||||
|
*/
|
||||||
|
async refundPayment(paymentData, amount) {
|
||||||
|
try {
|
||||||
|
const { id } = paymentData
|
||||||
|
await this.klarna_.post(
|
||||||
|
`${this.klarnaOrderManagementUrl_}/${id}/refunds`,
|
||||||
|
{
|
||||||
|
refunded_amount: amount,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return id
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancels payment for Klarna Order.
|
||||||
|
* @param {Object} paymentData - payment method data from cart
|
||||||
|
* @returns {string} id of cancelled order
|
||||||
|
*/
|
||||||
|
async cancelPayment(paymentData) {
|
||||||
|
try {
|
||||||
|
const { id } = paymentData
|
||||||
|
await this.klarna_.post(`${this.klarnaOrderUrl_}/${id}/cancel`)
|
||||||
|
return id
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default KlarnaProviderService
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
|||||||
import axios from "axios"
|
import axios from "axios"
|
||||||
import moment from "moment"
|
import moment from "moment"
|
||||||
import { BaseService } from "medusa-interfaces"
|
import { BaseService } from "medusa-interfaces"
|
||||||
|
import { MedusaError } from "medusa-core-utils"
|
||||||
|
|
||||||
ECONOMIC_BASE_URL = "https://restapi.e-conomic.com"
|
ECONOMIC_BASE_URL = "https://restapi.e-conomic.com"
|
||||||
|
|
||||||
@@ -134,7 +135,7 @@ class EconomicService extends BaseService {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async createInvoiceFromOrder(order, lineItems) {
|
async createInvoiceFromOrder(order) {
|
||||||
// Fetch currency code from order region
|
// Fetch currency code from order region
|
||||||
const {
|
const {
|
||||||
currency_code,
|
currency_code,
|
||||||
@@ -145,6 +146,8 @@ class EconomicService extends BaseService {
|
|||||||
billing_address.country
|
billing_address.country
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const lines = await this.createEconomicLinesFromOrder(order)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
date: moment().format("YYYY-MM-DD"),
|
date: moment().format("YYYY-MM-DD"),
|
||||||
currency: currency_code,
|
currency: currency_code,
|
||||||
@@ -189,6 +192,33 @@ class EconomicService extends BaseService {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async bookEconomicInvoice(orderId) {
|
||||||
|
try {
|
||||||
|
const order = await this.orderService_.retrieve(orderId)
|
||||||
|
const { economicDraftId } = order.setMetadata
|
||||||
|
|
||||||
|
if (!economicDraftId) {
|
||||||
|
throw new MedusaError(
|
||||||
|
MedusaError.Types.INVALID_ARGUMENT,
|
||||||
|
"The order does not have an invoice number"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const bookInvoiceRequest = {
|
||||||
|
draftInvoice: {
|
||||||
|
draftInvoiceNumber: parseInt(economicDraftId),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.economic_.post(
|
||||||
|
`${ECONOMIC_BASE_URL}/invoices/booked`,
|
||||||
|
bookInvoiceRequest
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default EconomicService
|
export default EconomicService
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
class OrderSubscriber {
|
||||||
|
constructor({ economicService, eventBusService }) {
|
||||||
|
this.economicService_ = economicService
|
||||||
|
|
||||||
|
this.eventBus_ = eventBusService
|
||||||
|
|
||||||
|
this.eventBus_.subscribe("order.placed", async (order) => {
|
||||||
|
await this.economicService_.draftEconomicInvoice(order)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default OrderSubscriber
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { Validator, MedusaError } from "medusa-core-utils"
|
||||||
|
|
||||||
|
export default async (req, res) => {
|
||||||
|
const schema = Validator.object().keys({
|
||||||
|
email: Validator.string()
|
||||||
|
.email()
|
||||||
|
.required(),
|
||||||
|
first_name: Validator.string().required(),
|
||||||
|
last_name: Validator.string().required(),
|
||||||
|
password: Validator.string().required(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const { value, error } = schema.validate(req.body)
|
||||||
|
if (error) {
|
||||||
|
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
const customer = await customerService.create(value)
|
||||||
|
const data = await customerService.decorate(customer, ["_id", "email"])
|
||||||
|
res.status(201).json({ customer: data })
|
||||||
|
} catch (err) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
const { id } = req.params
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
let customer = await customerService.retrieve(id)
|
||||||
|
customer = customerService.decorate(customer, [
|
||||||
|
"email",
|
||||||
|
"first_name",
|
||||||
|
"last_name",
|
||||||
|
])
|
||||||
|
res.json({ customer })
|
||||||
|
} catch (err) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { Router } from "express"
|
||||||
|
import middlewares from "../../../middlewares"
|
||||||
|
|
||||||
|
const route = Router()
|
||||||
|
|
||||||
|
export default app => {
|
||||||
|
app.use("/customers", route)
|
||||||
|
|
||||||
|
route.get("/", middlewares.wrap(require("./list-customers").default))
|
||||||
|
route.get("/:id", middlewares.wrap(require("./get-customer").default))
|
||||||
|
|
||||||
|
route.post("/", middlewares.wrap(require("./create-customer").default))
|
||||||
|
route.post("/:id", middlewares.wrap(require("./update-customer").default))
|
||||||
|
return app
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
const selector = {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
const customers = await customerService.list(selector)
|
||||||
|
|
||||||
|
res.json({ customers })
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Validator, MedusaError } from "medusa-core-utils"
|
||||||
|
|
||||||
|
export default async (req, res) => {
|
||||||
|
const { id } = req.params
|
||||||
|
|
||||||
|
const schema = Validator.object().keys({
|
||||||
|
first_name: Validator.string(),
|
||||||
|
last_name: Validator.string(),
|
||||||
|
password: Validator.string(),
|
||||||
|
})
|
||||||
|
|
||||||
|
const { value, error } = schema.validate(req.body)
|
||||||
|
if (error) {
|
||||||
|
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
await customerService.update(id, value)
|
||||||
|
|
||||||
|
const customer = await customerService.retrieve(id)
|
||||||
|
const data = await customerService.decorate(customer)
|
||||||
|
res.status(200).json({ customer: data })
|
||||||
|
} catch (err) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import discountRoutes from "./discounts"
|
|||||||
import orderRoutes from "./orders"
|
import orderRoutes from "./orders"
|
||||||
import storeRoutes from "./store"
|
import storeRoutes from "./store"
|
||||||
import uploadRoutes from "./uploads"
|
import uploadRoutes from "./uploads"
|
||||||
|
import customerRoutes from "./customers"
|
||||||
|
|
||||||
const route = Router()
|
const route = Router()
|
||||||
|
|
||||||
@@ -48,6 +49,7 @@ export default (app, container, config) => {
|
|||||||
orderRoutes(route)
|
orderRoutes(route)
|
||||||
storeRoutes(route)
|
storeRoutes(route)
|
||||||
uploadRoutes(route)
|
uploadRoutes(route)
|
||||||
|
customerRoutes(route)
|
||||||
|
|
||||||
return app
|
return app
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ describe("POST /admin/products/:id/options", () => {
|
|||||||
`/admin/products/${IdMap.getId("productWithOptions")}/options`,
|
`/admin/products/${IdMap.getId("productWithOptions")}/options`,
|
||||||
{
|
{
|
||||||
payload: {
|
payload: {
|
||||||
option_title: "Test option",
|
title: "Test option",
|
||||||
},
|
},
|
||||||
adminSession: {
|
adminSession: {
|
||||||
jwt: {
|
jwt: {
|
||||||
|
|||||||
@@ -39,6 +39,19 @@ describe("POST /admin/products/:id/variants/:variantId", () => {
|
|||||||
variant_id: IdMap.getId("variant1"),
|
variant_id: IdMap.getId("variant1"),
|
||||||
object: "product-variant",
|
object: "product-variant",
|
||||||
deleted: true,
|
deleted: true,
|
||||||
|
product: {
|
||||||
|
_id: IdMap.getId("productWithOptions"),
|
||||||
|
decorated: true,
|
||||||
|
options: [
|
||||||
|
{
|
||||||
|
_id: IdMap.getId("option1"),
|
||||||
|
title: "Test",
|
||||||
|
values: [IdMap.getId("optionValue1")],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
title: "Test",
|
||||||
|
variants: [IdMap.getId("variant1")],
|
||||||
|
},
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
+1
-3
@@ -13,7 +13,6 @@ describe("POST /admin/shipping-options", () => {
|
|||||||
region_id: "testregion",
|
region_id: "testregion",
|
||||||
provider_id: "test_provider",
|
provider_id: "test_provider",
|
||||||
data: { id: "test" },
|
data: { id: "test" },
|
||||||
profile_id: "test",
|
|
||||||
price: {
|
price: {
|
||||||
type: "flat_rate",
|
type: "flat_rate",
|
||||||
amount: 100,
|
amount: 100,
|
||||||
@@ -34,7 +33,6 @@ describe("POST /admin/shipping-options", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it("returns 200", () => {
|
it("returns 200", () => {
|
||||||
console.log(subject)
|
|
||||||
expect(subject.status).toEqual(200)
|
expect(subject.status).toEqual(200)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -45,7 +43,7 @@ describe("POST /admin/shipping-options", () => {
|
|||||||
region_id: "testregion",
|
region_id: "testregion",
|
||||||
provider_id: "test_provider",
|
provider_id: "test_provider",
|
||||||
data: { id: "test" },
|
data: { id: "test" },
|
||||||
profile_id: "test",
|
profile_id: expect.stringMatching(/.*/),
|
||||||
price: {
|
price: {
|
||||||
type: "flat_rate",
|
type: "flat_rate",
|
||||||
amount: 100,
|
amount: 100,
|
||||||
|
|||||||
+2
-2
@@ -2,8 +2,8 @@ import { IdMap } from "medusa-test-utils"
|
|||||||
import { request } from "../../../../../helpers/test-request"
|
import { request } from "../../../../../helpers/test-request"
|
||||||
import { ShippingOptionServiceMock } from "../../../../../services/__mocks__/shipping-option"
|
import { ShippingOptionServiceMock } from "../../../../../services/__mocks__/shipping-option"
|
||||||
|
|
||||||
describe("POST /admin/shipping-options", () => {
|
describe("DELETE /admin/shipping-options/{id}", () => {
|
||||||
describe("successful creation", () => {
|
describe("successful deletion", () => {
|
||||||
let subject
|
let subject
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
|
|||||||
+1
-1
@@ -22,7 +22,7 @@ describe("GET /admin/shipping-options", () => {
|
|||||||
|
|
||||||
it("calls service retrieve", () => {
|
it("calls service retrieve", () => {
|
||||||
expect(ShippingOptionServiceMock.list).toHaveBeenCalledTimes(1)
|
expect(ShippingOptionServiceMock.list).toHaveBeenCalledTimes(1)
|
||||||
expect(ShippingOptionServiceMock.list).toHaveBeenCalledWith()
|
expect(ShippingOptionServiceMock.list).toHaveBeenCalledWith({})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -43,7 +43,6 @@ export default async (req, res) => {
|
|||||||
|
|
||||||
res.status(200).json({ shipping_option: data })
|
res.status(200).json({ shipping_option: data })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(err)
|
|
||||||
throw err
|
throw err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,22 +57,6 @@ describe("POST /store/carts", () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("returns invalid data if region_id is not set", () => {
|
|
||||||
let subject
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
|
||||||
subject = await request("POST", `/store/carts`)
|
|
||||||
})
|
|
||||||
|
|
||||||
afterAll(() => {
|
|
||||||
jest.clearAllMocks()
|
|
||||||
})
|
|
||||||
|
|
||||||
it("returns error", () => {
|
|
||||||
expect(subject.status).toEqual(400)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("creates cart with line items", () => {
|
describe("creates cart with line items", () => {
|
||||||
let subject
|
let subject
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
const { id } = req.params
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
let customer = await customerService.retrieve(id)
|
||||||
|
customer = customerService.decorate(customer._id, [
|
||||||
|
"email",
|
||||||
|
"first_name",
|
||||||
|
"last_name",
|
||||||
|
])
|
||||||
|
res.json({ customer })
|
||||||
|
} catch (err) {
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,7 +6,11 @@ const route = Router()
|
|||||||
export default app => {
|
export default app => {
|
||||||
app.use("/customers", route)
|
app.use("/customers", route)
|
||||||
|
|
||||||
|
route.get("/", middlewares.wrap(require("./list-customers").default))
|
||||||
|
route.get("/:id", middlewares.wrap(require("./get-customer").default))
|
||||||
|
|
||||||
route.post("/", middlewares.wrap(require("./create-customer").default))
|
route.post("/", middlewares.wrap(require("./create-customer").default))
|
||||||
|
|
||||||
route.post(
|
route.post(
|
||||||
"/password-reset",
|
"/password-reset",
|
||||||
middlewares.wrap(require("./reset-password").default)
|
middlewares.wrap(require("./reset-password").default)
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
export default async (req, res) => {
|
||||||
|
const selector = {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const customerService = req.scope.resolve("customerService")
|
||||||
|
const customers = await customerService.list(selector)
|
||||||
|
|
||||||
|
res.json({ customers })
|
||||||
|
} catch (error) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ class OrderModel extends BaseModel {
|
|||||||
// awaiting, captured, refunded
|
// awaiting, captured, refunded
|
||||||
payment_status: { type: String, default: "awaiting" },
|
payment_status: { type: String, default: "awaiting" },
|
||||||
email: { type: String, required: true },
|
email: { type: String, required: true },
|
||||||
|
cart_id: { type: String },
|
||||||
billing_address: { type: AddressSchema, required: true },
|
billing_address: { type: AddressSchema, required: true },
|
||||||
shipping_address: { type: AddressSchema, required: true },
|
shipping_address: { type: AddressSchema, required: true },
|
||||||
items: { type: [LineItemSchema], required: true },
|
items: { type: [LineItemSchema], required: true },
|
||||||
|
|||||||
@@ -255,7 +255,7 @@ class CustomerService extends BaseService {
|
|||||||
* @param {string[]} expandFields - fields to expand.
|
* @param {string[]} expandFields - fields to expand.
|
||||||
* @return {Customer} return the decorated customer.
|
* @return {Customer} return the decorated customer.
|
||||||
*/
|
*/
|
||||||
async decorate(customer, fields, expandFields = []) {
|
decorate(customer, fields, expandFields = []) {
|
||||||
const requiredFields = ["_id", "metadata"]
|
const requiredFields = ["_id", "metadata"]
|
||||||
const decorated = _.pick(customer, fields.concat(requiredFields))
|
const decorated = _.pick(customer, fields.concat(requiredFields))
|
||||||
return decorated
|
return decorated
|
||||||
|
|||||||
@@ -123,6 +123,14 @@ class OrderService extends BaseService {
|
|||||||
return updatedMethods
|
return updatedMethods
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Object} selector - the query object for find
|
||||||
|
* @return {Promise} the result of the find operation
|
||||||
|
*/
|
||||||
|
list(selector) {
|
||||||
|
return this.orderModel_.find(selector)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets an order by id.
|
* Gets an order by id.
|
||||||
* @param {string} orderId - id of order to retrieve
|
* @param {string} orderId - id of order to retrieve
|
||||||
|
|||||||
Reference in New Issue
Block a user