feat: new tax api (#979)

* feat: add tax calculation strategy (#885)

* feat: add tax calculation strategy

* fix: adds strategy loader

* fix: eslint ignore

* chore: cleanup

* fix: allow plugin overwrites

* fix: allow plugin overwrites

* fix: fake region

* Update packages/medusa/src/loaders/strategies.ts

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>

* feat: adds tax related db entities + tax provider (#896)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: pr comments

* fix: unit test

* feat: totals service to ts (#911)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: adds TotalsServiceProps

* feat: adds integration tests for automatic tax calculation + shipping tax rates (#945)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: integration test helpers

* fix: adds factories + tests automatic tax rates

* fix: remove verbose

* fix: adds TotalsServiceProps

* fix: add shipping tax lines

* fix: add migration for shipping taxes

* fix: integration tests for shipping taxes

* fix: integration tests for shipping taxes

* fix: jsdoc types

* Feat/manual taxes (#950)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: integration test helpers

* fix: adds factories + tests automatic tax rates

* fix: remove verbose

* fix: adds TotalsServiceProps

* fix: add shipping tax lines

* fix: add migration for shipping taxes

* fix: integration tests for shipping taxes

* fix: integration tests for shipping taxes

* fix: add integration tests for manual taxes

* fix: cart service - cleanup jsdoc

* feat: add /carts/id/taxes to manually calculate taxes

* feat: add integration tests for order tax calculations

* fix: unit tests

* fix: merge

* fix: rm verbose

* fix: unit tests

* fix: object -> cartOrOrder

* fix: rounding

* Feat/complete order w tax lines (#951)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: integration test helpers

* fix: adds factories + tests automatic tax rates

* fix: remove verbose

* fix: adds TotalsServiceProps

* fix: add shipping tax lines

* fix: add migration for shipping taxes

* fix: integration tests for shipping taxes

* fix: integration tests for shipping taxes

* fix: add integration tests for manual taxes

* fix: cart service - cleanup jsdoc

* feat: add /carts/id/taxes to manually calculate taxes

* feat: add integration tests for order tax calculations

* feat: adds cart completion strategy + create order w. tax lines

* fix: unit tests

* fix: merge

* fix: rm verbose

* fix: unit tests

* fix: unit tests

* fix: unit tests

* fix: ensure calculation for list orders

* fix: unit tests

* fix: integration tests

* fix: adds cart order type gaurds

* Docs/tax api (#954)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: integration test helpers

* fix: adds factories + tests automatic tax rates

* fix: remove verbose

* fix: adds TotalsServiceProps

* fix: add shipping tax lines

* fix: add migration for shipping taxes

* fix: integration tests for shipping taxes

* fix: integration tests for shipping taxes

* fix: add integration tests for manual taxes

* fix: cart service - cleanup jsdoc

* feat: add /carts/id/taxes to manually calculate taxes

* feat: add integration tests for order tax calculations

* feat: adds cart completion strategy + create order w. tax lines

* fix: unit tests

* fix: merge

* fix: rm verbose

* fix: unit tests

* fix: unit tests

* fix: unit tests

* fix: ensure calculation for list orders

* fix: unit tests

* fix: integration tests

* docs: documents tax related methods and types

* fix: require either item_id or shipping_method_id

* feat: product type tax rate (#969)

* feat: adds tax related db entities + tax provider

* fix: add tax provider tests

* fix: add tax service unit tests

* fix: tests + migrations

* feat: totals service to ts

* fix: remove totals.js

* fix: add shipping methods

* fix: add inherited tax lines

* chore: rm tax-line repo

* fix: test

* fix: tests

* fix: tests

* fix: unit test

* fix: integration test helpers

* fix: adds factories + tests automatic tax rates

* fix: remove verbose

* fix: adds TotalsServiceProps

* fix: add shipping tax lines

* fix: add migration for shipping taxes

* fix: integration tests for shipping taxes

* fix: integration tests for shipping taxes

* fix: add integration tests for manual taxes

* fix: cart service - cleanup jsdoc

* feat: add /carts/id/taxes to manually calculate taxes

* feat: add integration tests for order tax calculations

* feat: adds cart completion strategy + create order w. tax lines

* fix: unit tests

* fix: merge

* fix: rm verbose

* fix: unit tests

* fix: unit tests

* fix: unit tests

* fix: ensure calculation for list orders

* fix: unit tests

* fix: integration tests

* docs: documents tax related methods and types

* fix: require either item_id or shipping_method_id

* feat: adds returns tests for new tax system

* feat: adds return lines + integration tests for swaps

* feat: return integration tests

* feat: adds product type tax rates

* feat: add tax management endpoints

* fix: create single migration

* fix: adds tax rates to js client

* fix: strats

* Fix/plugin tests (#998)

* plugin testing setup

* fix: test sendgrid plugin

* fix: test sendgrid plugin

* chore: clean

* chore: clean

* fix: clean up tests

* fix: remove dirty import

* fix: sendgrid + brightpearl

* fix: plugin integration tests

* fix: klarna

* fix: shipping method tax

* fix: remove taxrates

* fix: unit tests

* fix: integration

* fix: integration

* fix: plugins tests

* fix: ignore plugins

* fix: tests

* fix: taxes (#1017)

* fix: taxes

* fix: taxes

* fix: faulty ref

* fix: create tax-lines with claim items

* fix: snapshot tax-liens

* fix: allows integration test teardown to force deleting tables

* fix: tests

* fix: merge

* fix: adds tax-rates to client

* fix: adds tax-rates to medusa-react

* fix: tests

* fix: tests

* fix: add product types

* fix: adds tax provider endpoint + cascaded deletes on tax rate relations

* fix: move errors to service layer

* fix: cleanup api

* fix: unit tests

* fix: error handler in base-service

* fix: Add order region to swap on createFulfillment (#1110)

Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
Sebastian RindomandOliver Windall Juhl authored and olivermrbl committed 2022-02-25 18:53:49 +01:00
1 parent d80eaa172d
commit 47588e7a8d
223 files changed
+28546 -2229

No files matched your search

+16 -5
View File
@@ -45,7 +45,7 @@ export class Reporter {
this.ora_ = activityLogger
}
panic = data => {
panic = (data) => {
const parsedPanic = panicHandler(data)
this.loggerInstance_.log({
@@ -66,7 +66,7 @@ export class Reporter {
* @param {string} level - the level to check if logger is configured for
* @return {boolean} whether we should log
*/
shouldLog = level => {
shouldLog = (level) => {
level = this.loggerInstance_.levels[level]
const logLevel = this.loggerInstance_.levels[this.loggerInstance_.level]
return level <= logLevel
@@ -76,7 +76,7 @@ export class Reporter {
* Sets the log level of the logger.
* @param {string} level - the level to set the logger to
*/
setLogLevel = level => {
setLogLevel = (level) => {
this.loggerInstance_.level = level
}
@@ -262,7 +262,18 @@ export class Reporter {
* Logs a message at the info level.
* @param {string} message - the message to log
*/
info = message => {
debug = (message) => {
this.loggerInstance_.log({
level: "debug",
message,
})
}
/**
* Logs a message at the info level.
* @param {string} message - the message to log
*/
info = (message) => {
this.loggerInstance_.log({
level: "info",
message,
@@ -273,7 +284,7 @@ export class Reporter {
* Logs a message at the warn level.
* @param {string} message - the message to log
*/
warn = message => {
warn = (message) => {
this.loggerInstance_.warn({
level: "warn",
message,
@@ -18,6 +18,7 @@
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/runtime": "^7.9.6",
"@medusajs/medusa": "^1.1.62",
"client-sessions": "^0.8.0",
"cross-env": "^5.2.1",
"eslint": "^6.8.0",
@@ -1,10 +1,15 @@
import { TotalsService } from "@medusajs/medusa"
import { humanizeAmount } from "medusa-core-utils"
import { FulfillmentService } from "medusa-interfaces"
import Webshipper from "../utils/webshipper"
class WebshipperFulfillmentService extends FulfillmentService {
static identifier = "webshipper"
constructor({ logger, claimService, swapService, orderService }, options) {
constructor(
{ logger, totalsService, claimService, swapService, orderService },
options
) {
super()
this.options_ = options
@@ -25,6 +30,9 @@ class WebshipperFulfillmentService extends FulfillmentService {
/** @private @const {OrderService} */
this.orderService_ = orderService
/** @private @const {TotalsService} */
this.totalsService_ = totalsService
/** @private @const {SwapService} */
this.swapService_ = swapService
@@ -170,22 +178,38 @@ class WebshipperFulfillmentService extends FulfillmentService {
width: 15,
length: 15,
},
customs_lines: returnOrder.items.map(({ item, quantity }) => {
return {
ext_ref: item.id,
sku: item.variant.sku,
description: item.title,
quantity: quantity,
country_of_origin:
item.variant.origin_country ||
item.variant.product.origin_country,
tarif_number:
item.variant.hs_code || item.variant.product.hs_code,
unit_price: item.unit_price / 100,
vat_percent: fromOrder.tax_rate,
currency: fromOrder.currency_code.toUpperCase(),
}
}),
customs_lines: await Promise.all(
returnOrder.items.map(async ({ item, quantity }) => {
const totals = await this.totalsService_.getLineItemTotals(
item,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
return {
ext_ref: item.id,
sku: item.variant.sku,
description: item.title,
quantity: quantity,
country_of_origin:
item.variant.origin_country ||
item.variant.product.origin_country,
tarif_number:
item.variant.hs_code || item.variant.product.hs_code,
unit_price: humanizeAmount(
totals.unit_price,
fromOrder.currency_code
),
vat_percent: totals.tax_lines.reduce(
(acc, next) => acc + next.rate,
0
),
currency: fromOrder.currency_code.toUpperCase(),
}
})
),
},
],
sender_address: {
@@ -329,21 +353,38 @@ class WebshipperFulfillmentService extends FulfillmentService {
status: "pending",
ext_ref,
visible_ref,
order_lines: fulfillmentItems.map((item) => {
return {
ext_ref: item.id,
sku: item.variant.sku,
description: item.title,
quantity: item.quantity,
country_of_origin:
item.variant.origin_country ||
item.variant.product.origin_country,
tarif_number:
item.variant.hs_code || item.variant.product.hs_code,
unit_price: item.unit_price / 100,
vat_percent: fromOrder.tax_rate,
}
}),
order_lines: await Promise.all(
fulfillmentItems.map(async (item) => {
const totals = await this.totalsService_.getLineItemTotals(
item,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
return {
ext_ref: item.id,
sku: item.variant.sku,
description: item.title,
quantity: item.quantity,
country_of_origin:
item.variant.origin_country ||
item.variant.product.origin_country,
tarif_number:
item.variant.hs_code || item.variant.product.hs_code,
unit_price: humanizeAmount(
totals.unit_price,
fromOrder.currency_code
),
vat_percent: totals.tax_lines.reduce(
(acc, next) => acc + next.rate,
0
),
}
})
),
delivery_address: {
att_contact: `${shipping_address.first_name} ${shipping_address.last_name}`,
address_1: shipping_address.address_1,
@@ -8,12 +8,14 @@ import AdminGiftCardsResource from "./gift-cards"
import AdminInvitesResource from "./invites"
import AdminNotesResource from "./notes"
import AdminProductsResource from "./products"
import AdminProductTypesResource from "./product-types"
import AdminUsersResource from "./users"
import AdminReturnsResource from "./returns"
import AdminOrdersResource from "./orders"
import AdminReturnReasonsResource from "./return-reasons"
import AdminVariantsResource from "./variants"
import AdminSwapsResource from "./swaps"
import AdminTaxRatesResource from "./tax-rates"
import AdminShippingProfilesResource from "./shipping-profiles"
import AdminStoresResource from "./store"
import AdminShippingOptionsResource from "./shipping-options"
@@ -33,6 +35,7 @@ class Admin extends BaseResource {
public notes = new AdminNotesResource(this.client)
public products = new AdminProductsResource(this.client)
public productTags = new AdminProductTagsResource(this.client)
public productTypes = new AdminProductTypesResource(this.client)
public users = new AdminUsersResource(this.client)
public returns = new AdminReturnsResource(this.client)
public orders = new AdminOrdersResource(this.client)
@@ -44,6 +47,7 @@ class Admin extends BaseResource {
public shippingOptions = new AdminShippingOptionsResource(this.client)
public regions = new AdminRegionsResource(this.client)
public notifications = new AdminNotificationsResource(this.client)
public taxRates = new AdminTaxRatesResource(this.client)
public uploads = new AdminUploadsResource(this.client)
}
@@ -22,7 +22,10 @@ import { ResponsePromise } from "../../typings"
import BaseResource from "../base"
class AdminOrdersResource extends BaseResource {
create(payload: AdminPostOrdersReq, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
create(
payload: AdminPostOrdersReq,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders`
return this.client.request("POST", path, payload, {}, customHeaders)
}
@@ -30,17 +33,24 @@ class AdminOrdersResource extends BaseResource {
update(
id: string,
payload: AdminPostOrdersOrderReq,
customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}`
return this.client.request("POST", path, payload, {}, customHeaders)
}
retrieve(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
retrieve(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}`
return this.client.request("GET", path, {}, {}, customHeaders)
}
list(query?: AdminGetOrdersParams, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersListRes> {
list(
query?: AdminGetOrdersParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersListRes> {
let path = `/admin/orders`
if (query) {
@@ -51,12 +61,18 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("GET", path, {}, {}, customHeaders)
}
complete(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
complete(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/complete`
return this.client.request("POST", path, {}, {}, customHeaders)
}
capturePayment(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
capturePayment(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/capture`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -64,7 +80,8 @@ class AdminOrdersResource extends BaseResource {
refundPayment(
id: string,
payload: AdminPostOrdersOrderRefundsReq,
customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/refund`
return this.client.request("POST", path, payload, {}, customHeaders)
}
@@ -72,7 +89,8 @@ class AdminOrdersResource extends BaseResource {
createFulfillment(
id: string,
payload: AdminPostOrdersOrderFulfillmentsReq,
customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/fulfillment`
return this.client.request("POST", path, payload, {}, customHeaders)
}
@@ -124,7 +142,10 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("POST", path, payload, {}, customHeaders)
}
cancel(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
cancel(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/cancel`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -138,7 +159,10 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("POST", path, payload, {}, customHeaders)
}
archive(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
archive(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/archive`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -152,7 +176,11 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("POST", path, payload, {}, customHeaders)
}
cancelSwap(id: string, swapId: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
cancelSwap(
id: string,
swapId: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/swaps/${swapId}/cancel`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -195,7 +223,11 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("POST", path, payload, {}, customHeaders)
}
cancelClaim(id: string, claimId: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
cancelClaim(
id: string,
claimId: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/claims/${claimId}/cancel`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -230,7 +262,11 @@ class AdminOrdersResource extends BaseResource {
return this.client.request("POST", path, payload, {}, customHeaders)
}
deleteMetadata(id: string, key: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminOrdersRes> {
deleteMetadata(
id: string,
key: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminOrdersRes> {
const path = `/admin/orders/${id}/metadata/${key}`
return this.client.request("DELETE", path, {}, {}, customHeaders)
}
@@ -0,0 +1,24 @@
import {
AdminGetProductTypesParams,
AdminProductTypesListRes,
} from "@medusajs/medusa"
import qs from "qs"
import { ResponsePromise } from "../../typings"
import BaseResource from "../base"
class AdminProductTypesResource extends BaseResource {
list(
query?: AdminGetProductTypesParams
): ResponsePromise<AdminProductTypesListRes> {
let path = `/admin/product-types`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/product-types?${queryString}`
}
return this.client.request("GET", path)
}
}
export default AdminProductTypesResource
@@ -20,12 +20,18 @@ import { ResponsePromise } from "../../typings"
import BaseResource from "../base"
class AdminProductsResource extends BaseResource {
create(payload: AdminPostProductsReq, customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsRes> {
create(
payload: AdminPostProductsReq,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsRes> {
const path = `/admin/products/`
return this.client.request("POST", path, payload, {}, customHeaders)
}
retrieve(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsRes> {
retrieve(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsRes> {
const path = `/admin/products/${id}`
return this.client.request("GET", path, {}, {}, customHeaders)
}
@@ -33,17 +39,24 @@ class AdminProductsResource extends BaseResource {
update(
id: string,
payload: AdminPostProductsProductReq,
customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsRes> {
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsRes> {
const path = `/admin/products/${id}`
return this.client.request("POST", path, payload, {}, customHeaders)
}
delete(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsDeleteRes> {
delete(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsDeleteRes> {
const path = `/admin/products/${id}`
return this.client.request("DELETE", path, {}, {}, customHeaders)
}
list(query?: AdminGetProductsParams, customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsListRes> {
list(
query?: AdminGetProductsParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsListRes> {
let path = `/admin/products`
if (query) {
@@ -54,12 +67,16 @@ class AdminProductsResource extends BaseResource {
return this.client.request("GET", path, {}, {}, customHeaders)
}
listTypes(customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsListTypesRes> {
listTypes(
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsListTypesRes> {
const path = `/admin/products/types`
return this.client.request("GET", path, {}, {}, customHeaders)
}
listTags(customHeaders: Record<string, any> = {}): ResponsePromise<AdminProductsListTagsRes> {
listTags(
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminProductsListTagsRes> {
const path = `/admin/products/tag-usage`
return this.client.request("GET", path, {}, {}, customHeaders)
}
@@ -1,5 +1,6 @@
import {
AdminPaymentProvidersList,
AdminTaxProvidersList,
AdminPostStoreReq,
AdminStoresRes,
} from "@medusajs/medusa"
@@ -13,7 +14,10 @@ class AdminStoresResource extends BaseResource {
* @param customHeaders
* @returns the updated store.
*/
update(payload: AdminPostStoreReq, customHeaders: Record<string, any> = {}): ResponsePromise<AdminStoresRes> {
update(
payload: AdminPostStoreReq,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminStoresRes> {
const path = `/admin/store/`
return this.client.request("POST", path, payload, {}, customHeaders)
}
@@ -24,7 +28,10 @@ class AdminStoresResource extends BaseResource {
* @param customHeaders
* @returns updated store.
*/
addCurrency(currency_code: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminStoresRes> {
addCurrency(
currency_code: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminStoresRes> {
const path = `/admin/store/${currency_code}`
return this.client.request("POST", path, {}, {}, customHeaders)
}
@@ -35,7 +42,10 @@ class AdminStoresResource extends BaseResource {
* @param customHeaders
* @returns updated store
*/
deleteCurrency(currency_code: string, customHeaders: Record<string, any> = {}): ResponsePromise<AdminStoresRes> {
deleteCurrency(
currency_code: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminStoresRes> {
const path = `/admin/store/currencies/${currency_code}`
return this.client.request("DELETE", path, {}, {}, customHeaders)
}
@@ -44,7 +54,9 @@ class AdminStoresResource extends BaseResource {
* @description gets a medusa store
* @returns a medusa store
*/
retrieve(customHeaders: Record<string, any> = {}): ResponsePromise<AdminStoresRes> {
retrieve(
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminStoresRes> {
const path = `/admin/store/`
return this.client.request("GET", path, {}, {}, customHeaders)
}
@@ -53,10 +65,23 @@ class AdminStoresResource extends BaseResource {
* @description Lists the store's payment providers
* @returns a list of payment providers configured on the store
*/
listPaymentProviders(customHeaders: Record<string, any> = {}): ResponsePromise<AdminPaymentProvidersList> {
listPaymentProviders(
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminPaymentProvidersList> {
const path = `/admin/store/payment-providers`
return this.client.request("GET", path, {}, {}, customHeaders)
}
/**
* @description Lists the store's payment providers
* @returns a list of payment providers configured on the store
*/
listTaxProviders(
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxProvidersList> {
const path = `/admin/store/tax-providers`
return this.client.request("GET", path, {}, {}, customHeaders)
}
}
export default AdminStoresResource
@@ -0,0 +1,189 @@
import {
AdminTaxRatesRes,
AdminTaxRatesListRes,
AdminTaxRatesDeleteRes,
AdminGetTaxRatesParams,
AdminGetTaxRatesTaxRateParams,
AdminDeleteTaxRatesTaxRateProductsReq,
AdminDeleteTaxRatesTaxRateProductsParams,
AdminDeleteTaxRatesTaxRateProductTypesReq,
AdminDeleteTaxRatesTaxRateProductTypesParams,
AdminDeleteTaxRatesTaxRateShippingOptionsReq,
AdminDeleteTaxRatesTaxRateShippingOptionsParams,
AdminPostTaxRatesReq,
AdminPostTaxRatesTaxRateReq,
AdminPostTaxRatesTaxRateProductsReq,
AdminPostTaxRatesTaxRateProductTypesReq,
AdminPostTaxRatesTaxRateShippingOptionsReq,
} from "@medusajs/medusa"
import qs from "qs"
import { ResponsePromise } from "../../typings"
import BaseResource from "../base"
class AdminTaxRatesResource extends BaseResource {
retrieve(
id: string,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}?${queryString}`
}
return this.client.request("GET", path, {}, {}, customHeaders)
}
list(
query?: AdminGetTaxRatesParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesListRes> {
let path = `/admin/tax-rates`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates?${queryString}`
}
return this.client.request("GET", path, {}, {}, customHeaders)
}
create(
payload: AdminPostTaxRatesReq,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates?${queryString}`
}
return this.client.request("POST", path, payload, {}, customHeaders)
}
update(
id: string,
payload: AdminPostTaxRatesTaxRateReq,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}?${queryString}`
}
return this.client.request("POST", path, payload, {}, customHeaders)
}
addProducts(
id: string,
payload: AdminPostTaxRatesTaxRateProductsReq,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/products/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/products/batch?${queryString}`
}
return this.client.request("POST", path, payload, {}, customHeaders)
}
addProductTypes(
id: string,
payload: AdminPostTaxRatesTaxRateProductTypesReq,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/product-types/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/product-types/batch?${queryString}`
}
return this.client.request("POST", path, payload, {}, customHeaders)
}
addShippingOptions(
id: string,
payload: AdminPostTaxRatesTaxRateShippingOptionsReq,
query?: AdminGetTaxRatesTaxRateParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/shipping-options/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/shipping-options/batch?${queryString}`
}
return this.client.request("POST", path, payload, {}, customHeaders)
}
removeProducts(
id: string,
payload: AdminDeleteTaxRatesTaxRateProductsReq,
query?: AdminDeleteTaxRatesTaxRateProductsParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/products/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/products/batch?${queryString}`
}
return this.client.request("DELETE", path, payload, {}, customHeaders)
}
removeProductTypes(
id: string,
payload: AdminDeleteTaxRatesTaxRateProductTypesReq,
query?: AdminDeleteTaxRatesTaxRateProductTypesParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/product-types/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/product-types/batch?${queryString}`
}
return this.client.request("DELETE", path, payload, {}, customHeaders)
}
removeShippingOptions(
id: string,
payload: AdminDeleteTaxRatesTaxRateShippingOptionsReq,
query?: AdminDeleteTaxRatesTaxRateShippingOptionsParams,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesRes> {
let path = `/admin/tax-rates/${id}/shipping-options/batch`
if (query) {
const queryString = qs.stringify(query)
path = `/admin/tax-rates/${id}/shipping-options/batch?${queryString}`
}
return this.client.request("DELETE", path, payload, {}, customHeaders)
}
delete(
id: string,
customHeaders: Record<string, any> = {}
): ResponsePromise<AdminTaxRatesDeleteRes> {
const path = `/admin/tax-rates/${id}`
return this.client.request("DELETE", path, {}, {}, customHeaders)
}
}
export default AdminTaxRatesResource
@@ -3,6 +3,18 @@ export const TotalsServiceMock = {
getTaxTotal: jest.fn(),
getAllocationItemDiscounts: jest.fn(),
getDiscountTotal: jest.fn(),
getLineItemTotals: jest.fn(() => {
return {
total: 10,
tax_lines: [],
}
}),
getShippingMethodTotals: jest.fn(() => {
return {
total: 10,
tax_lines: [],
}
}),
}
const mock = jest.fn().mockImplementation(() => {
@@ -5,7 +5,7 @@ import { PaymentService } from "medusa-interfaces"
class KlarnaProviderService extends PaymentService {
static identifier = "klarna"
constructor({ shippingProfileService }, options) {
constructor({ shippingProfileService, totalsService }, options) {
super()
/**
@@ -41,48 +41,66 @@ class KlarnaProviderService extends PaymentService {
/** @private @const {ShippingProfileService} */
this.shippingProfileService_ = shippingProfileService
/** @private @const {TotalsService} */
this.totalsService_ = totalsService
}
async lineItemsToOrderLines_(cart, taxRate) {
async lineItemsToOrderLines_(cart) {
let order_lines = []
const tax = taxRate / 100
cart.items.forEach((item) => {
for (const item of cart.items) {
// Withdraw discount from the total item amount
const quantity = item.quantity
const unit_price = item.unit_price * (tax + 1)
const total_amount = unit_price * quantity
const total_tax_amount = total_amount * (tax / (1 + tax))
const totals = await this.totalsService_.getLineItemTotals(item, cart, {
include_tax: true,
})
const tax =
totals.tax_lines.reduce((acc, next) => acc + next.rate, 0) / 100
order_lines.push({
name: item.title,
tax_rate: tax * 10000,
quantity,
unit_price,
total_amount,
total_tax_amount,
unit_price: Math.round(totals.original_total / item.quantity),
total_amount: totals.total - totals.gift_card_total,
total_tax_amount: totals.tax_total,
total_discount_amount:
totals.original_total - totals.total + totals.gift_card_total,
})
})
}
if (cart.shipping_methods.length) {
const { name, price } = cart.shipping_methods.reduce(
(acc, next) => {
acc.name = [...acc.name, next?.shipping_option.name]
acc.price += next.price
return acc
},
{ name: [], price: 0 }
)
const name = []
let total = 0
let tax = 0
for (const next of cart.shipping_methods) {
const totals = await this.totalsService_.getShippingMethodTotals(
next,
cart,
{
include_tax: true,
}
)
name.push(next?.shipping_option.name)
total += totals.total
tax += totals.tax_total
}
const taxRate = tax / (total - tax)
order_lines.push({
name: name?.join(" + ") || "Shipping fee",
quantity: 1,
type: "shipping_fee",
unit_price: price * (1 + tax),
tax_rate: tax * 10000,
total_amount: price * (1 + tax),
total_tax_amount: price * tax,
unit_price: total,
tax_rate: taxRate * 10000,
total_amount: total,
total_tax_amount: tax,
})
}
@@ -96,45 +114,20 @@ class KlarnaProviderService extends PaymentService {
locale: "en-US",
}
const { region, gift_card_total, discount_total, tax_total, total } = cart
const { region, gift_card_total, tax_total, total } = cart
const taxRate = region.tax_rate / 100
order.order_lines = await this.lineItemsToOrderLines_(cart)
order.order_lines = await this.lineItemsToOrderLines_(cart, region.tax_rate)
if (discount_total > 0) {
order.order_lines.push({
name: `Discount`,
quantity: 1,
type: "discount",
unit_price: 0,
total_discount_amount: discount_total * (1 + taxRate),
tax_rate: taxRate * 10000,
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) {
if (gift_card_total && !region.gift_cards_taxable) {
order.order_lines.push({
name: `Gift Card`,
quantity: 1,
type: "gift_card",
unit_price: 0,
total_discount_amount: gift_card_total * (1 + taxRate),
tax_rate: taxRate * 10000,
total_amount: -gift_card_total * (1 + taxRate),
total_tax_amount: -gift_card_total * taxRate,
total_discount_amount: gift_card_total,
tax_rate: 0,
total_amount: -gift_card_total,
total_tax_amount: 0,
})
}
@@ -185,11 +178,20 @@ class KlarnaProviderService extends PaymentService {
// shipping_options and set the selected shipping method
if (cart.shipping_methods.length) {
const shipping_method = cart.shipping_methods[0]
const totals = await this.totalsService_.getShippingMethodTotals(
shipping_method,
cart,
{
include_tax: true,
}
)
const taxRate = totals.tax_total / (totals.total - totals.tax_total)
order.selected_shipping_option = {
id: shipping_method.shipping_option.id,
name: shipping_method.shipping_option.name,
price: shipping_method.price * (1 + taxRate),
tax_amount: shipping_method.price * taxRate,
price: totals.total,
tax_amount: total.tax_total,
tax_rate: taxRate * 10000,
}
}
@@ -213,6 +215,8 @@ class KlarnaProviderService extends PaymentService {
const methods = Object.keys(partitioned).map((k) => partitioned[k])
const combinations = cartesian(...methods)
const taxRate = region.tax_rate / 100
// Use the cartesian product of shipping methods to generate correct
// format for the Klarna Widget
order.shipping_options = combinations.map((combination) => {
@@ -156,6 +156,20 @@ const TotalsService = {
getTotal: () => {
return Promise.resolve(123)
},
getShippingMethodTotals: () => {
return {
price: 0,
discount_total: 0,
tax_total: 0,
}
},
getLineItemTotals: () => {
return {
subtotal: 15800,
discount_total: 0,
tax_total: 3950,
}
},
getLineDiscounts: (o) => {
if (o.id === "rounding") {
return [
@@ -242,76 +256,6 @@ describe("BrightpearlService", () => {
})
})
describe("createSalesOrder", () => {
const bpService = new BrightpearlService(
{
orderService: OrderService,
totalsService: TotalsService,
oauthService: OAuthService,
regionService: RegionService,
},
{ account: "test" }
)
it("successfully builds sales order", async () => {
jest.clearAllMocks()
await bpService.createSalesOrder(order)
expect(mockCreateOrder).toHaveBeenCalledWith({
currency: { code: "DKK" },
ref: "1234",
externalRef: "12355",
channelId: "1",
installedIntegrationInstanceId: undefined,
statusId: "3",
customer: {
id: "12345",
address: {
addressFullName: "Test Testson",
addressLine1: "Test",
addressLine2: "TEst",
postalCode: "1234",
countryIsoCode: "DK",
telephone: "12345678",
email: "test@example.com",
},
},
delivery: {
shippingMethodId: 0,
address: {
addressFullName: "Test Testson",
addressLine1: "Test",
addressLine2: "TEst",
postalCode: "1234",
countryIsoCode: "DK",
telephone: "12345678",
email: "test@example.com",
},
},
rows: [
{
name: "Test",
net: 22,
tax: 5.082,
quantity: 2,
taxCode: "1234",
externalRef: undefined,
nominalCode: "4000",
},
{
name: "Shipping: standard",
quantity: 1,
net: 123.99,
tax: 28.6417,
taxCode: "1234",
nominalCode: "4040",
},
],
})
})
})
describe("rounding", () => {
const bpService = new BrightpearlService(
{
@@ -322,15 +322,8 @@ class BrightpearlService extends BaseService {
name: `${fromRefund.reason}: ${fromRefund.note}`,
quantity: 1,
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)),
fromOrder.currency_code
),
net: this.bpnum_(fromRefund.amount, fromOrder.currency_code),
tax: 0,
nominalCode: accountingCode,
},
],
@@ -410,6 +403,29 @@ class BrightpearlService extends BaseService {
}),
}
if (fromReturn.shipping_method) {
const totals = await this.totalsService_.getShippingMethodTotals(
fromReturn.shipping_method,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
order.rows.push({
net: this.bpnum_(
-1 * (totals.total - totals.tax_total),
fromOrder.currency_code
),
tax: this.bpnum_(-1 * totals.tax_total, fromOrder.currency_code),
name: "Return shipping",
taxCode: region.tax_code,
nominalCode: this.options.shipping_account_code || "4040",
quantity: 1,
})
}
const total = order.rows.reduce((acc, next) => {
return acc + next.net + next.tax
}, 0)
@@ -421,15 +437,8 @@ class BrightpearlService extends BaseService {
name: "Difference",
quantity: 1,
taxCode: region.tax_code,
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
),
net: this.bpround_(difference),
tax: 0,
nominalCode: this.options.sales_account_code || "4000",
})
}
@@ -811,14 +820,24 @@ class BrightpearlService extends BaseService {
fromSwap.return_order.shipping_method &&
fromSwap.return_order.shipping_method.price
) {
const shippingTotals =
await this.totalsService_.getShippingMethodTotals(
fromSwap.return_order.shipping_method,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
order.rows.push({
name: "Return Shipping",
quantity: 1,
taxCode: region.tax_code,
net: (-1 * fromSwap.return_order.shipping_method.price) / 100,
tax:
((-1 * fromSwap.return_order.shipping_method.price) / 100) *
(fromOrder.tax_rate / 100),
net: this.bpnum_(1 * shippingTotals.price, fromOrder.currency_code),
tax: this.bpnum_(
1 * shippingTotals.tax_total,
fromOrder.currency_code
),
nominalCode: this.options.shipping_account_code || "4040",
})
}
@@ -882,21 +901,19 @@ class BrightpearlService extends BaseService {
config = { include_price: true, is_claim: false }
) {
const { region } = fromOrder
const discount = fromOrder.discounts.find(
({ rule }) => rule.type !== "free_shipping"
)
let lineDiscounts = []
if (discount) {
lineDiscounts = this.totalsService_.getLineDiscounts(fromOrder, discount)
}
const lines = await Promise.all(
fromOrder.items.map(async (item) => {
const bpProduct = await this.retrieveProductBySKU(item.variant.sku)
const ld = lineDiscounts.find((l) => item.id === l.item.id) || {
amount: 0,
}
const lineTotals = await this.totalsService_.getLineItemTotals(
item,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
const row = {}
if (bpProduct) {
@@ -907,23 +924,20 @@ class BrightpearlService extends BaseService {
if (config.include_price) {
row.net = this.bpnum_(
item.unit_price * item.quantity - ld.amount,
lineTotals.subtotal - lineTotals.discount_total,
fromOrder.currency_code
)
row.tax = this.bpnum_(
item.unit_price * item.quantity - ld.amount,
fromOrder.currency_code,
fromOrder.tax_rate
)
row.tax = this.bpnum_(lineTotals.tax_total, fromOrder.currency_code)
} else if (config.is_claim) {
row.net = await this.retrieveProductPrice(
bpProduct.productId,
this.options.cost_price_list || `1`
)
row.tax = this.bpnum_(
row.net * 100,
fromOrder.currency_code,
fromOrder.tax_rate
lineTotals.tax_lines.reduce((acc, next) => acc + next.rate, 0)
)
}
@@ -948,34 +962,48 @@ class BrightpearlService extends BaseService {
// purchased.
const gcTotal = fromOrder.gift_card_total
if (gcTotal) {
let tax = 0
if (fromOrder.region.gift_cards_taxable) {
tax = this.bpnum_(
-1 * gcTotal,
fromOrder.currency_code,
fromOrder.region.tax_rate
)
}
lines.push({
name: `Gift Card`,
net: this.bpnum_(-1 * gcTotal, fromOrder.currency_code),
tax: this.bpnum_(
-1 * gcTotal,
fromOrder.currency_code,
fromOrder.tax_rate
),
tax,
quantity: 1,
taxCode: region.tax_code,
nominalCode: this.options.gift_card_account_code || "4000",
})
}
const shippingTotal =
fromOrder.shipping_total ||
this.totalsService_.getShippingTotal(fromOrder)
const shippingMethods = fromOrder.shipping_methods
if (shippingMethods.length > 0) {
const shippingTotal = await shippingMethods.reduce(async (acc, next) => {
const accum = await acc
const totals = await this.totalsService_.getShippingMethodTotals(
next,
fromOrder,
{
include_tax: true,
use_tax_lines: true,
}
)
return {
price: accum.price + totals.price,
tax: accum.tax + totals.tax_total,
}
}, Promise.resolve({ price: 0, tax: 0 }))
lines.push({
name: `Shipping: ${shippingMethods.map((m) => m.name).join(" + ")}`,
quantity: 1,
net: this.bpnum_(shippingTotal, fromOrder.currency_code),
tax: this.bpnum_(
shippingTotal,
fromOrder.currency_code,
fromOrder.tax_rate
),
net: this.bpnum_(shippingTotal.price, fromOrder.currency_code),
tax: this.bpnum_(shippingTotal.tax, fromOrder.currency_code),
taxCode: region.tax_code,
nominalCode: this.options.shipping_account_code || "4040",
})
@@ -72,21 +72,20 @@ class OrderSubscriber {
const fromSwap = await this.swapService_.retrieve(id, {
relations: [
"order",
"order.payments",
"order.region",
"order.swaps",
"order.discounts",
"order.discounts.rule",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
"additional_items",
"additional_items.tax_lines",
"shipping_address",
"shipping_methods",
"shipping_methods.tax_lines",
],
})
let fromOrder = fromSwap.order
const fromOrder = await this.orderService_.retrieve(fromSwap.order_id, {
relations: ["payments", "region", "swaps", "discounts", "discounts.rule"],
})
if (
!(
@@ -105,23 +104,27 @@ class OrderSubscriber {
const { id } = data
const fromClaim = await this.claimService_.retrieve(id, {
relations: [
"order",
"order.payments",
"order.region",
"order.claims",
"order.discounts",
"order.discounts.rule",
"claim_items",
"return_order",
"return_order.items",
"return_order.shipping_method",
"return_order.shipping_method.tax_lines",
"additional_items",
"additional_items.tax_lines",
"shipping_address",
"shipping_methods",
],
})
const fromOrder = fromClaim.order
const fromOrder = await this.orderService_.retrieve(fromClaim.order_id, {
relations: [
"payments",
"region",
"claims",
"discounts",
"discounts.rule",
],
})
if (fromClaim.type === "replace") {
await this.brightpearlService_.createClaim(fromOrder, fromClaim)
@@ -147,11 +150,11 @@ class OrderSubscriber {
const { id, return_id } = data
const order = await this.orderService_.retrieve(id, {
relations: ["region", "swaps", "payments"],
relations: ["discounts", "region", "swaps", "payments"],
})
const fromReturn = await this.returnService_.retrieve(return_id, {
relations: ["items"],
relations: ["items", "shipping_method", "shipping_method.tax_lines"],
})
return this.brightpearlService_
@@ -64,8 +64,11 @@ describe("SegmentService", () => {
}
const TotalsService = {
getLineItemRefund: (_, item) => {
return item.unit_price
getLineItemTotals: (item) => {
return {
total: item.unit_price,
tax_total: 0,
}
},
}
@@ -101,10 +104,10 @@ describe("SegmentService", () => {
{
category: "Collection",
name: "Test",
price: 4.47,
price: 5.5,
product_id: "prod_123",
quantity: 2,
reporting_revenue: 8.94,
reporting_revenue: 11,
sku: "",
subtitle: "Subtitle",
type: "Type",
@@ -160,10 +163,10 @@ describe("SegmentService", () => {
{
category: "Collection",
name: "Test",
price: 4.47,
price: 5.5,
product_id: "prod_123",
quantity: 2,
reporting_revenue: 8.94,
reporting_revenue: 11,
sku: "",
subtitle: "Subtitle",
type: "Type",
@@ -214,10 +217,10 @@ describe("SegmentService", () => {
{
category: "Collection",
name: "Test",
price: 446.79,
price: 550,
product_id: "prod_123",
quantity: 2,
reporting_revenue: 893.58,
reporting_revenue: 1100,
sku: "",
subtitle: "Subtitle",
type: "Type",
@@ -73,8 +73,6 @@ class SegmentService extends BaseService {
coupon = order.discounts[0] && order.discounts[0].code
}
const taxRate = order.tax_rate / 100
const orderData = {
checkout_id: order.cart_id,
order_id: order.id,
@@ -113,15 +111,18 @@ class SegmentService extends BaseService {
products: await Promise.all(
order.items.map(async (item) => {
let name = item.title
const lineTotalTax = this.totalsService_.getLineItemRefund(
const totals = await this.totalsService_.getLineItemTotals(
item,
order,
item
{
include_tax: true,
}
)
const lineTotal = lineTotalTax / (1 + taxRate)
const lineTotal = totals.total - totals.tax_total
const revenue = await this.getReportingValue(
order.currency_code,
curr,
humanizeAmount(lineTotal, curr)
)
@@ -349,7 +349,7 @@ class SendGridService extends NotificationService {
}
}
async orderPlacedData({ id }) {
async orderCanceledData({ id }) {
const order = await this.orderService_.retrieve(id, {
select: [
"shipping_total",
@@ -448,6 +448,131 @@ class SendGridService extends NotificationService {
}
}
async orderPlacedData({ id }) {
const order = await this.orderService_.retrieve(id, {
select: [
"shipping_total",
"discount_total",
"tax_total",
"refunded_total",
"gift_card_total",
"subtotal",
"total",
],
relations: [
"customer",
"billing_address",
"shipping_address",
"discounts",
"discounts.rule",
"discounts.rule.valid_for",
"shipping_methods",
"shipping_methods.shipping_option",
"payments",
"fulfillments",
"returns",
"gift_cards",
"gift_card_transactions",
],
})
const { tax_total, shipping_total, gift_card_total, total } = order
const currencyCode = order.currency_code.toUpperCase()
const items = await Promise.all(
order.items.map(async (i) => {
i.totals = await this.totalsService_.getLineItemTotals(i, order, {
include_tax: true,
use_tax_lines: true,
})
i.thumbnail = this.normalizeThumbUrl_(i.thumbnail)
i.discounted_price = `${this.humanPrice_(
i.totals.total / i.quantity,
currencyCode
)} ${currencyCode}`
i.price = `${this.humanPrice_(
i.totals.original_total / i.quantity,
currencyCode
)} ${currencyCode}`
return i
})
)
let discounts = []
if (order.discounts) {
discounts = order.discounts.map((discount) => {
return {
is_giftcard: false,
code: discount.code,
descriptor: `${discount.rule.value}${
discount.rule.type === "percentage" ? "%" : ` ${currencyCode}`
}`,
}
})
}
let giftCards = []
if (order.gift_cards) {
giftCards = order.gift_cards.map((gc) => {
return {
is_giftcard: true,
code: gc.code,
descriptor: `${gc.value} ${currencyCode}`,
}
})
discounts.concat(giftCards)
}
const locale = await this.extractLocale(order)
// Includes taxes in discount amount
const discountTotal = items.reduce((acc, i) => {
return acc + i.totals.original_total - i.totals.total
}, 0)
const discounted_subtotal = items.reduce((acc, i) => {
return acc + i.totals.total
}, 0)
const subtotal = items.reduce((acc, i) => {
return acc + i.totals.original_total
}, 0)
const subtotal_ex_tax = items.reduce((total, i) => {
return total + i.totals.subtotal
}, 0)
return {
...order,
locale,
has_discounts: order.discounts.length,
has_gift_cards: order.gift_cards.length,
date: order.created_at.toDateString(),
items,
discounts,
subtotal_ex_tax: `${this.humanPrice_(
subtotal_ex_tax,
currencyCode
)} ${currencyCode}`,
subtotal: `${this.humanPrice_(subtotal, currencyCode)} ${currencyCode}`,
gift_card_total: `${this.humanPrice_(
gift_card_total,
currencyCode
)} ${currencyCode}`,
tax_total: `${this.humanPrice_(tax_total, currencyCode)} ${currencyCode}`,
discount_total: `${this.humanPrice_(
discountTotal,
currencyCode
)} ${currencyCode}`,
shipping_total: `${this.humanPrice_(
shipping_total,
currencyCode
)} ${currencyCode}`,
total: `${this.humanPrice_(total, currencyCode)} ${currencyCode}`,
}
}
async gcCreatedData({ id }) {
const giftCard = await this.giftCardService_.retrieve(id, {
relations: ["region", "order"],
@@ -475,68 +600,76 @@ class SendGridService extends NotificationService {
relations: [
"items",
"items.item",
"items.item.tax_lines",
"items.item.variant",
"items.item.variant.product",
"shipping_method",
"shipping_method.tax_lines",
"shipping_method.shipping_option",
],
})
const items = await this.lineItemService_.list({
id: returnRequest.items.map(({ item_id }) => item_id),
})
returnRequest.items = returnRequest.items.map((item) => {
const found = items.find((i) => i.id === item.item_id)
return {
...item,
item: found,
}
})
const items = await this.lineItemService_.list(
{
id: returnRequest.items.map(({ item_id }) => item_id),
},
{ relations: ["tax_lines"] }
)
// Fetch the order
const order = await this.orderService_.retrieve(id, {
select: ["total"],
relations: [
"items",
"items.tax_lines",
"discounts",
"discounts.rule",
"discounts.rule.valid_for",
"shipping_address",
"returns",
"swaps",
"swaps.additional_items",
],
})
let merged = [...order.items]
// merge items from order with items from order swaps
if (order.swaps && order.swaps.length) {
for (const s of order.swaps) {
merged = [...merged, ...s.additional_items]
}
}
// Calculate which items are in the return
const returnItems = returnRequest.items.map((i) => {
const found = merged.find((oi) => oi.id === i.item_id)
return {
...found,
quantity: i.quantity,
}
})
const taxRate = order.tax_rate / 100
const currencyCode = order.currency_code.toUpperCase()
// Calculate which items are in the return
const returnItems = await Promise.all(
returnRequest.items.map(async (i) => {
const found = items.find((oi) => oi.id === i.item_id)
found.quantity = i.quantity
found.thumbnail = this.normalizeThumbUrl_(found.thumbnail)
found.totals = await this.totalsService_.getLineItemTotals(
found,
order,
{
include_tax: true,
use_tax_lines: true,
}
)
found.price = `${this.humanPrice_(
found.totals.total,
currencyCode
)} ${currencyCode}`
found.tax_lines = found.totals.tax_lines
return found
})
)
// Get total of the returned products
const item_subtotal = this.totalsService_.getRefundTotal(order, returnItems)
const item_subtotal = returnItems.reduce(
(acc, next) => acc + next.totals.total,
0
)
// If the return has a shipping method get the price and any attachments
let shippingTotal = 0
if (returnRequest.shipping_method) {
shippingTotal = returnRequest.shipping_method.price * (1 + taxRate)
const base = returnRequest.shipping_method.price
shippingTotal =
base +
returnRequest.shipping_method.tax_lines.reduce((acc, next) => {
return Math.round(acc + base * (next.rate / 100))
}, 0)
}
const locale = await this.extractLocale(order)
@@ -545,7 +678,7 @@ class SendGridService extends NotificationService {
locale,
has_shipping: !!returnRequest.shipping_method,
email: order.email,
items: this.processItems_(returnItems, taxRate, currencyCode),
items: returnItems,
subtotal: `${this.humanPrice_(
item_subtotal,
currencyCode
@@ -570,11 +703,12 @@ class SendGridService extends NotificationService {
}
}
async swapCreatedData({ id }) {
async swapReceivedData({ id }) {
const store = await this.storeService_.retrieve()
const swap = await this.swapService_.retrieve(id, {
relations: [
"additional_items",
"additional_items.tax_lines",
"return_order",
"return_order.items",
"return_order.items.item",
@@ -585,9 +719,14 @@ class SendGridService extends NotificationService {
const returnRequest = swap.return_order
const items = await this.lineItemService_.list({
id: returnRequest.items.map(({ item_id }) => item_id),
})
const items = await this.lineItemService_.list(
{
id: returnRequest.items.map(({ item_id }) => item_id),
},
{
relations: ["tax_lines"],
}
)
returnRequest.items = returnRequest.items.map((item) => {
const found = items.find((i) => i.id === item.item_id)
@@ -612,42 +751,51 @@ class SendGridService extends NotificationService {
"shipping_address",
"swaps",
"swaps.additional_items",
"swaps.additional_items.tax_lines",
],
})
const taxRate = order.tax_rate / 100
const cart = await this.cartService_.retrieve(swap.cart_id, {
select: [
"total",
"tax_total",
"discount_total",
"shipping_total",
"subtotal",
],
})
const currencyCode = order.currency_code.toUpperCase()
let merged = [...order.items]
const decoratedItems = await Promise.all(
cart.items.map(async (i) => {
const totals = await this.totalsService_.getLineItemTotals(i, cart, {
include_tax: true,
})
// merge items from order with items from order swaps
if (order.swaps && order.swaps.length) {
for (const s of order.swaps) {
merged = [...merged, ...s.additional_items]
}
}
const returnItems = this.processItems_(
swap.return_order.items.map((i) => {
const found = merged.find((oi) => oi.id === i.item_id)
return {
...found,
quantity: i.quantity,
...i,
totals,
price: this.humanPrice_(
totals.subtotal + totals.tax_total,
currencyCode
),
}
}),
taxRate,
currencyCode
})
)
const returnTotal = this.totalsService_.getRefundTotal(order, returnItems)
const returnTotal = decoratedItems.reduce((acc, next) => {
if (next.is_return) {
return acc + -1 * (next.totals.subtotal + next.totals.tax_total)
}
return acc
}, 0)
const constructedOrder = {
...order,
shipping_methods: [],
items: swap.additional_items,
}
const additionalTotal = this.totalsService_.getTotal(constructedOrder)
const additionalTotal = decoratedItems.reduce((acc, next) => {
if (!next.is_return) {
return acc + next.totals.subtotal + next.totals.tax_total
}
return acc
}, 0)
const refundAmount = swap.return_order.refund_amount
@@ -661,8 +809,143 @@ class SendGridService extends NotificationService {
date: swap.updated_at.toDateString(),
swap_link: swapLink,
email: order.email,
items: this.processItems_(swap.additional_items, taxRate, currencyCode),
return_items: returnItems,
items: decoratedItems.filter((di) => !di.is_return),
return_items: decoratedItems.filter((di) => di.is_return),
return_total: `${this.humanPrice_(
returnTotal,
currencyCode
)} ${currencyCode}`,
tax_total: `${this.humanPrice_(
cart.total,
currencyCode
)} ${currencyCode}`,
refund_amount: `${this.humanPrice_(
refundAmount,
currencyCode
)} ${currencyCode}`,
additional_total: `${this.humanPrice_(
additionalTotal,
currencyCode
)} ${currencyCode}`,
}
}
async swapCreatedData({ id }) {
const store = await this.storeService_.retrieve()
const swap = await this.swapService_.retrieve(id, {
relations: [
"additional_items",
"additional_items.tax_lines",
"return_order",
"return_order.items",
"return_order.items.item",
"return_order.shipping_method",
"return_order.shipping_method.shipping_option",
],
})
const returnRequest = swap.return_order
const items = await this.lineItemService_.list(
{
id: returnRequest.items.map(({ item_id }) => item_id),
},
{
relations: ["tax_lines"],
}
)
returnRequest.items = returnRequest.items.map((item) => {
const found = items.find((i) => i.id === item.item_id)
return {
...item,
item: found,
}
})
const swapLink = store.swap_link_template.replace(
/\{cart_id\}/,
swap.cart_id
)
const order = await this.orderService_.retrieve(swap.order_id, {
select: ["total"],
relations: [
"items",
"items.tax_lines",
"discounts",
"discounts.rule",
"discounts.rule.valid_for",
"shipping_address",
"swaps",
"swaps.additional_items",
"swaps.additional_items.tax_lines",
],
})
const cart = await this.cartService_.retrieve(swap.cart_id, {
select: [
"total",
"tax_total",
"discount_total",
"shipping_total",
"subtotal",
],
})
const currencyCode = order.currency_code.toUpperCase()
const decoratedItems = await Promise.all(
cart.items.map(async (i) => {
const totals = await this.totalsService_.getLineItemTotals(i, cart, {
include_tax: true,
})
return {
...i,
totals,
tax_lines: totals.tax_lines,
price: `${this.humanPrice_(
totals.original_total / i.quantity,
currencyCode
)} ${currencyCode}`,
discounted_price: `${this.humanPrice_(
totals.total / i.quantity,
currencyCode
)} ${currencyCode}`,
}
})
)
const returnTotal = decoratedItems.reduce((acc, next) => {
const { total } = next.totals
if (next.is_return && next.variant_id) {
return acc + -1 * total
}
return acc
}, 0)
const additionalTotal = decoratedItems.reduce((acc, next) => {
const { total } = next.totals
if (!next.is_return) {
return acc + total
}
return acc
}, 0)
const refundAmount = swap.return_order.refund_amount
const locale = await this.extractLocale(order)
return {
locale,
swap,
order,
return_request: returnRequest,
date: swap.updated_at.toDateString(),
swap_link: swapLink,
email: order.email,
items: decoratedItems.filter((di) => !di.is_return),
return_items: decoratedItems.filter((di) => di.is_return),
return_total: `${this.humanPrice_(
returnTotal,
currencyCode
@@ -687,7 +970,9 @@ class SendGridService extends NotificationService {
relations: [
"shipping_address",
"shipping_methods",
"shipping_methods.tax_lines",
"additional_items",
"additional_items.tax_lines",
"return_order",
"return_order.items",
],
@@ -695,40 +980,68 @@ class SendGridService extends NotificationService {
const order = await this.orderService_.retrieve(swap.order_id, {
relations: [
"region",
"items",
"items.tax_lines",
"discounts",
"discounts.rule",
"discounts.rule.valid_for",
"swaps",
"swaps.additional_items",
"swaps.additional_items.tax_lines",
],
})
let merged = [...order.items]
const cart = await this.cartService_.retrieve(swap.cart_id, {
select: [
"total",
"tax_total",
"discount_total",
"shipping_total",
"subtotal",
],
})
// merge items from order with items from order swaps
if (order.swaps && order.swaps.length) {
for (const s of order.swaps) {
merged = [...merged, ...s.additional_items]
const returnRequest = swap.return_order
const items = await this.lineItemService_.list(
{
id: returnRequest.items.map(({ item_id }) => item_id),
},
{
relations: ["tax_lines"],
}
}
)
const taxRate = order.tax_rate / 100
const currencyCode = order.currency_code.toUpperCase()
const returnItems = this.processItems_(
swap.return_order.items.map((i) => {
const found = merged.find((oi) => oi.id === i.item_id)
const returnItems = await Promise.all(
swap.return_order.items.map(async (i) => {
const found = items.find((oi) => oi.id === i.item_id)
const totals = await this.totalsService_.getLineItemTotals(i, cart, {
include_tax: true,
})
return {
...found,
thumbnail: this.normalizeThumbUrl_(found.thumbnail),
price: `${this.humanPrice_(
totals.original_total / i.quantity,
currencyCode
)} ${currencyCode}`,
discounted_price: `${this.humanPrice_(
totals.total / i.quantity,
currencyCode
)} ${currencyCode}`,
quantity: i.quantity,
}
}),
taxRate,
currencyCode
})
)
const returnTotal = this.totalsService_.getRefundTotal(order, returnItems)
const returnTotal = await this.totalsService_.getRefundTotal(
order,
returnItems
)
const constructedOrder = {
...order,
@@ -736,7 +1049,7 @@ class SendGridService extends NotificationService {
items: swap.additional_items,
}
const additionalTotal = this.totalsService_.getTotal(constructedOrder)
const additionalTotal = await this.totalsService_.getTotal(constructedOrder)
const refundAmount = swap.return_order.refund_amount
@@ -750,11 +1063,31 @@ class SendGridService extends NotificationService {
locale,
swap,
order,
items: this.processItems_(swap.additional_items, taxRate, currencyCode),
items: await Promise.all(
swap.additional_items.map(async (i) => {
const totals = await this.totalsService_.getLineItemTotals(i, cart, {
include_tax: true,
})
return {
...i,
thumbnail: this.normalizeThumbUrl_(i.thumbnail),
price: `${this.humanPrice_(
totals.original_total / i.quantity,
currencyCode
)} ${currencyCode}`,
discounted_price: `${this.humanPrice_(
totals.total / i.quantity,
currencyCode
)} ${currencyCode}`,
quantity: i.quantity,
}
})
),
date: swap.updated_at.toDateString(),
email: order.email,
tax_amount: `${this.humanPrice_(
swap.difference_due * taxRate,
cart.tax_total,
currencyCode
)} ${currencyCode}`,
paid_total: `${this.humanPrice_(
@@ -871,7 +1204,7 @@ class SendGridService extends NotificationService {
if (fromOrder.cart_id) {
try {
const cart = await this.cartService_.retrieve(fromOrder.cart_id, {
select: ["context"],
select: ["id", "context"],
})
if (cart.context && cart.context.locale) {
@@ -61,8 +61,6 @@ class SlackService extends BaseService {
const { subtotal, tax_total, discount_total, shipping_total, total } = order
const currencyCode = order.currency_code.toUpperCase()
const taxRate = order.tax_rate / 100
const getDisplayAmount = (amount) => {
const humanAmount = humanizeAmount(amount, currencyCode)
if (zeroDecimalCurrencies.includes(currencyCode.toLowerCase())) {
@@ -141,13 +139,20 @@ class SlackService extends BaseService {
type: "divider",
})
order.items.forEach((lineItem) => {
for (const lineItem of order.items) {
const totals = await this.totalsService_.getLineItemTotals(
lineItem,
order,
{
include_tax: true,
}
)
let line = {
type: "section",
text: {
type: "mrkdwn",
text: `*${lineItem.title}*\n${lineItem.quantity} x ${getDisplayAmount(
lineItem.unit_price * (1 + taxRate)
totals.original_total
)} ${currencyCode}`,
},
}
@@ -170,7 +175,7 @@ class SlackService extends BaseService {
blocks.push({
type: "divider",
})
})
}
return axios.post(this.options_.slack_url, {
text: `Order ${order.display_id} was processed`,
@@ -8,6 +8,7 @@ export * from "./gift-cards"
export * from "./orders"
export * from "./products"
export * from "./product-tags"
export * from "./product-types"
export * from "./return-reasons"
export * from "./regions"
export * from "./shipping-options"
@@ -20,3 +21,4 @@ export * from "./store"
export * from "./swaps"
export * from "./users"
export * from "./variants"
export * from "./tax-rates"
@@ -0,0 +1 @@
export * from "./queries"
@@ -0,0 +1,34 @@
import {
AdminProductTypesListRes,
AdminGetProductTypesParams,
} from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js"
import { useQuery } from "react-query"
import { useMedusa } from "../../../contexts"
import { UseQueryOptionsWrapper } from "../../../types"
import { queryKeysFactory } from "../../utils/index"
const ADMIN_PRODUCT_TYPES_QUERY_KEY = `admin_product_types` as const
export const adminProductTypeKeys = queryKeysFactory(
ADMIN_PRODUCT_TYPES_QUERY_KEY
)
type ProductTypesQueryKeys = typeof adminProductTypeKeys
export const useAdminProductTypes = (
query?: AdminGetProductTypesParams,
options?: UseQueryOptionsWrapper<
Response<AdminProductTypesListRes>,
Error,
ReturnType<ProductTypesQueryKeys["list"]>
>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminProductTypeKeys.list(query),
() => client.admin.productTypes.list(query),
options
)
return { ...data, ...rest } as const
}
@@ -2,7 +2,6 @@ import {
AdminProductsListRes,
AdminProductsRes,
AdminGetProductsParams,
AdminProductsListTypesRes,
AdminProductsListTagsRes,
} from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js"
@@ -51,22 +50,6 @@ export const useAdminProduct = (
return { ...data, ...rest } as const
}
export const useAdminProductTypes = (
options?: UseQueryOptionsWrapper<
Response<AdminProductsListTypesRes>,
Error,
ReturnType<ProductQueryKeys["detail"]>
>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminProductKeys.detail("types"),
() => client.admin.products.listTypes(),
options
)
return { ...data, ...rest } as const
}
export const useAdminProductTagUsage = (
options?: UseQueryOptionsWrapper<
Response<AdminProductsListTagsRes>,
@@ -1,4 +1,8 @@
import { AdminPaymentProvidersList, AdminStoresRes } from "@medusajs/medusa"
import {
AdminTaxProvidersList,
AdminPaymentProvidersList,
AdminStoresRes,
} from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js"
import { useQuery } from "react-query"
import { useMedusa } from "../../../contexts"
@@ -27,6 +31,22 @@ export const useAdminStorePaymentProviders = (
return { ...data, ...rest } as const
}
export const useAdminStoreTaxProviders = (
options?: UseQueryOptionsWrapper<
Response<AdminTaxProvidersList>,
Error,
ReturnType<StoreQueryKeys["detail"]>
>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminStoreKeys.detail("tax_providers"),
() => client.admin.store.listTaxProviders(),
options
)
return { ...data, ...rest } as const
}
export const useAdminStore = (
options?: UseQueryOptionsWrapper<
Response<AdminStoresRes>,
@@ -0,0 +1,2 @@
export * from "./queries"
export * from "./mutations"
@@ -0,0 +1,203 @@
import { adminTaxRateKeys } from "./queries"
import {
AdminTaxRatesRes,
AdminTaxRatesDeleteRes,
AdminDeleteTaxRatesTaxRateProductsReq,
AdminDeleteTaxRatesTaxRateProductTypesReq,
AdminDeleteTaxRatesTaxRateShippingOptionsReq,
AdminPostTaxRatesReq,
AdminPostTaxRatesTaxRateReq,
AdminPostTaxRatesTaxRateProductsReq,
AdminPostTaxRatesTaxRateProductTypesReq,
AdminPostTaxRatesTaxRateShippingOptionsReq,
} from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js"
import { useMutation, UseMutationOptions, useQueryClient } from "react-query"
import { useMedusa } from "../../../contexts/medusa"
import { buildOptions } from "../../utils/buildOptions"
export const useAdminCreateTaxRate = (
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminPostTaxRatesReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostTaxRatesReq) => client.admin.taxRates.create(payload),
buildOptions(queryClient, adminTaxRateKeys.lists(), options)
)
}
export const useAdminUpdateTaxRate = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminPostTaxRatesTaxRateReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostTaxRatesTaxRateReq) =>
client.admin.taxRates.update(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminDeleteTaxRate = (
id: string,
options?: UseMutationOptions<Response<AdminTaxRatesDeleteRes>, Error, void>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
() => client.admin.taxRates.delete(id),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminCreateProductTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminPostTaxRatesTaxRateProductsReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostTaxRatesTaxRateProductsReq) =>
client.admin.taxRates.addProducts(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminDeleteProductTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminDeleteTaxRatesTaxRateProductsReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminDeleteTaxRatesTaxRateProductsReq) =>
client.admin.taxRates.removeProducts(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminCreateProductTypeTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminPostTaxRatesTaxRateProductTypesReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostTaxRatesTaxRateProductTypesReq) =>
client.admin.taxRates.addProductTypes(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminDeleteProductTypeTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminDeleteTaxRatesTaxRateProductTypesReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminDeleteTaxRatesTaxRateProductTypesReq) =>
client.admin.taxRates.removeProductTypes(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminCreateShippingTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminPostTaxRatesTaxRateShippingOptionsReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminPostTaxRatesTaxRateShippingOptionsReq) =>
client.admin.taxRates.addShippingOptions(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
export const useAdminDeleteShippingTaxRates = (
id: string,
options?: UseMutationOptions<
Response<AdminTaxRatesRes>,
Error,
AdminDeleteTaxRatesTaxRateShippingOptionsReq
>
) => {
const { client } = useMedusa()
const queryClient = useQueryClient()
return useMutation(
(payload: AdminDeleteTaxRatesTaxRateShippingOptionsReq) =>
client.admin.taxRates.removeShippingOptions(id, payload),
buildOptions(
queryClient,
[adminTaxRateKeys.lists(), adminTaxRateKeys.detail(id)],
options
)
)
}
@@ -0,0 +1,51 @@
import {
AdminTaxRatesRes,
AdminTaxRatesListRes,
AdminGetTaxRatesParams,
} from "@medusajs/medusa"
import { Response } from "@medusajs/medusa-js"
import { useQuery } from "react-query"
import { useMedusa } from "../../../contexts"
import { UseQueryOptionsWrapper } from "../../../types"
import { queryKeysFactory } from "../../utils/index"
const ADMIN_TAX_RATES_QUERY_KEY = `admin_tax_rates` as const
export const adminTaxRateKeys = queryKeysFactory(ADMIN_TAX_RATES_QUERY_KEY)
type TaxRateQueryKeys = typeof adminTaxRateKeys
export const useAdminTaxRates = (
query?: AdminGetTaxRatesParams,
options?: UseQueryOptionsWrapper<
Response<AdminTaxRatesListRes>,
Error,
ReturnType<TaxRateQueryKeys["list"]>
>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminTaxRateKeys.list(query),
() => client.admin.taxRates.list(query),
options
)
return { ...data, ...rest } as const
}
export const useAdminTaxRate = (
id: string,
query?: AdminGetTaxRatesParams,
options?: UseQueryOptionsWrapper<
Response<AdminTaxRatesRes>,
Error,
ReturnType<TaxRateQueryKeys["detail"]>
>
) => {
const { client } = useMedusa()
const { data, ...rest } = useQuery(
adminTaxRateKeys.detail(id),
() => client.admin.taxRates.retrieve(id, query),
options
)
return { ...data, ...rest } as const
}
@@ -22,20 +22,6 @@ describe("useAdminProducts hook", () => {
})
})
describe("useAdminProductTypes hook", () => {
test("returns a list of product types", async () => {
const types = fixtures.list("product_type")
const { result, waitFor } = renderHook(() => useAdminProductTypes(), {
wrapper: createWrapper(),
})
await waitFor(() => result.current.isSuccess)
expect(result.current.response.status).toEqual(200)
expect(result.current.types).toEqual(types)
})
})
describe("useAdminProductTagUsage hook", () => {
test("returns a list of product tags", async () => {
const tags = fixtures.list("product_tag")
@@ -1,6 +1,8 @@
import { renderHook } from "@testing-library/react-hooks"
import { fixtures } from "../../../../mocks/data"
import {
useAdminCreateSwap,
useAdminFulfillSwap,
useAdminCancelSwap,
useAdminCancelSwapFulfillment,
useAdminCreateSwap,
+1
View File
@@ -21,6 +21,7 @@
"@babel/core": "^7.14.3",
"@babel/preset-typescript": "^7.13.0",
"@types/express": "^4.17.13",
"@types/jest": "^27.0.3",
"@types/jsonwebtoken": "^8.5.5",
"babel-preset-medusa-package": "^1.1.19",
"cross-env": "^5.2.1",
+2
View File
@@ -35,9 +35,11 @@ export * from "./routes/admin/return-reasons"
export * from "./routes/admin/swaps"
export * from "./routes/admin/uploads"
export * from "./routes/admin/returns"
export * from "./routes/admin/tax-rates"
export * from "./routes/admin/shipping-options"
export * from "./routes/admin/regions"
export * from "./routes/admin/product-tags"
export * from "./routes/admin/product-types"
// Store
export * from "./routes/store/auth"
@@ -25,6 +25,8 @@ import collectionRoutes from "./collections"
import productTagRoutes from "./product-tags"
import notificationRoutes from "./notifications"
import noteRoutes from "./notes"
import taxRateRoutes from "./tax-rates"
import productTypesRoutes from "./product-types"
import customerGroupRoutes from "./customer-groups"
const route = Router()
@@ -79,8 +81,10 @@ export default (app, container, config) => {
notificationRoutes(route)
returnReasonRoutes(route)
productTagRoutes(route)
productTypesRoutes(route)
noteRoutes(route)
inviteRoutes(route)
taxRateRoutes(route)
customerGroupRoutes(route)
return app
@@ -15,6 +15,8 @@ const defaultRelations = [
"fulfillments.tracking_links",
"fulfillments.items",
"returns",
"returns.shipping_method",
"returns.shipping_method.tax_lines",
"returns.items",
"returns.items.reason",
"gift_cards",
@@ -169,7 +169,15 @@ export default async (req, res) => {
const order = await orderService
.withTransaction(manager)
.retrieve(id, {
relations: ["items", "discounts", "discounts.rule"],
relations: [
"customer",
"shipping_address",
"region",
"items",
"items.tax_lines",
"discounts",
"discounts.rule",
],
})
await claimService.withTransaction(manager).create({
@@ -81,7 +81,7 @@ export class AdminPostOrdersOrderSwapsSwapShipmentsReq {
@IsArray()
@IsOptional()
@IsString({ each: true })
tracking_numbers?: string[]
tracking_numbers?: string[] = []
@IsBoolean()
@IsOptional()
@@ -150,7 +150,13 @@ export default async (req, res) => {
.withTransaction(manager)
.retrieve(id, {
select: ["refunded_total", "total"],
relations: ["items", "swaps", "swaps.additional_items"],
relations: [
"items",
"items.tax_lines",
"swaps",
"swaps.additional_items",
"swaps.additional_items.tax_lines",
],
})
const swap = await swapService
@@ -170,6 +176,7 @@ export default async (req, res) => {
await swapService
.withTransaction(manager)
.createCart(swap.id, validated.custom_shipping_options)
const returnOrder = await returnService
.withTransaction(manager)
.retrieveBySwap(swap.id)
@@ -143,14 +143,6 @@ export default (app) => {
middlewares.wrap(require("./cancel-swap").default)
)
/**
* Receives the inventory to return from a swap
*/
route.post(
"/:id/swaps/:swap_id/receive",
middlewares.wrap(require("./receive-swap").default)
)
/**
* Fulfills a swap.
*/
@@ -246,6 +238,8 @@ export const defaultAdminOrdersRelations = [
"fulfillments.tracking_links",
"fulfillments.items",
"returns",
"returns.shipping_method",
"returns.shipping_method.tax_lines",
"returns.items",
"returns.items.reason",
"gift_cards",
@@ -390,7 +384,6 @@ export * from "./fulfill-swap"
export * from "./get-order"
export * from "./list-orders"
export * from "./process-swap-payment"
export * from "./receive-swap"
export * from "./refund-payment"
export * from "./request-return"
export * from "./update-claim"
@@ -1,95 +0,0 @@
import { Type } from "class-transformer"
import {
IsArray,
IsInt,
IsNotEmpty,
IsString,
ValidateNested,
} from "class-validator"
import { EntityManager } from "typeorm"
import { defaultAdminOrdersFields, defaultAdminOrdersRelations } from "."
import { OrderService, SwapService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [post] /orders/{id}/swaps/{swap_id}/receive
* operationId: "PostOrdersOrderSwapsSwapReceive"
* summary: "Receive a Swap"
* description: "Registers a Swap as received."
* x-authenticated: true
* parameters:
* - (path) id=* {string} The id of the Order.
* - (path) swap_id=* {string} The id of the Swap.
* requestBody:
* content:
* application/json:
* schema:
* properties:
* items:
* description: The Line Items that have been received.
* type: array
* items:
* properties:
* item_id:
* description: The id of the Line Item.
* type: string
* quantity:
* description: The quantity of the Line Item.
* type: integer
* tags:
* - Order
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* order:
* $ref: "#/components/schemas/order"
*/
export default async (req, res) => {
const { id, swap_id } = req.params
const validated = await validator(
AdminPostOrdersOrderSwapsSwapReceiveReq,
req.body
)
const orderService: OrderService = req.scope.resolve("orderService")
const swapService: SwapService = req.scope.resolve("swapService")
const entityManager: EntityManager = req.scope.resolve("manager")
await entityManager.transaction(async (manager) => {
await swapService
.withTransaction(manager)
.receiveReturn(swap_id, validated.items)
await orderService
.withTransaction(manager)
.registerSwapReceived(id, swap_id)
})
const order = await orderService.retrieve(id, {
select: defaultAdminOrdersFields,
relations: defaultAdminOrdersRelations,
})
res.status(200).json({ order })
}
export class AdminPostOrdersOrderSwapsSwapReceiveReq {
@IsArray()
@ValidateNested({ each: true })
@Type(() => Item)
items: Item[]
}
class Item {
@IsString()
@IsNotEmpty()
item_id: string
@IsInt()
@IsNotEmpty()
quantity: number
}
@@ -0,0 +1,40 @@
import { Router } from "express"
import { ProductType } from "../../../.."
import { PaginatedResponse } from "../../../../types/common"
import middlewares from "../../../middlewares"
import "reflect-metadata"
const route = Router()
export default (app) => {
app.use("/product-types", route)
route.get("/", middlewares.wrap(require("./list-product-types").default))
return app
}
export const allowedAdminProductTypeFields = [
"id",
"value",
"created_at",
"updated_at",
]
export const defaultAdminProductTypeFields = [
"id",
"value",
"created_at",
"updated_at",
]
export const defaultAdminProductTypeRelations = []
export type AdminProductTypesListRes = PaginatedResponse & {
product_types: ProductType[]
}
export type AdminProductTypesRes = {
product_type: ProductType
}
export * from "./list-product-types"
@@ -0,0 +1,125 @@
import { Type } from "class-transformer"
import { MedusaError } from "medusa-core-utils"
import { IsNumber, IsString, IsOptional, ValidateNested } from "class-validator"
import { omit, pickBy, identity } from "lodash"
import {
allowedAdminProductTypeFields,
defaultAdminProductTypeFields,
defaultAdminProductTypeRelations,
} from "."
import { ProductType } from "../../../../models/product-type"
import ProductTypeService from "../../../../services/product-type"
import {
StringComparisonOperator,
DateComparisonOperator,
FindConfig,
} from "../../../../types/common"
import { validator } from "../../../../utils/validator"
import { IsType } from "../../../../utils/validators/is-type"
/**
* @oas [get] /product-types
* operationId: "GetProductTypes"
* summary: "List Product Types"
* description: "Retrieve a list of Product Types."
* x-authenticated: true
* parameters:
* - (query) limit {string} The number of types to return.
* - (query) offset {string} The offset of types to return.
* - (query) value {string} The value of types to return.
* - (query) id {string} The id of types to return.
* - (query) created_at {DateComparisonOperator} Date comparison for when resulting tas was created, i.e. less than, greater than etc.
* - (query) updated_at {DateComparisonOperator} Date comparison for when resulting tas was updated, i.e. less than, greater than etc.
* tags:
* - Product Tag
* responses:
* "200":
* description: OK
* content:
* application/json:
* schema:
* properties:
* types:
* $ref: "#/components/schemas/product_tag"
*/
export default async (req, res) => {
const validated = await validator(AdminGetProductTypesParams, req.query)
const typeService: ProductTypeService =
req.scope.resolve("productTypeService")
const listConfig: FindConfig<ProductType> = {
select: defaultAdminProductTypeFields as (keyof ProductType)[],
relations: defaultAdminProductTypeRelations,
skip: validated.offset,
take: validated.limit,
}
if (typeof validated.order !== "undefined") {
let orderField = validated.order
if (validated.order.startsWith("-")) {
const [, field] = validated.order.split("-")
orderField = field
listConfig.order = { [field]: "DESC" }
} else {
listConfig.order = { [validated.order]: "ASC" }
}
if (!allowedAdminProductTypeFields.includes(orderField)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Order field must be a valid product type field"
)
}
}
const filterableFields = omit(validated, ["limit", "offset"])
const [types, count] = await typeService.listAndCount(
pickBy(filterableFields, identity),
listConfig
)
res.status(200).json({
product_types: types,
count,
offset: validated.offset,
limit: validated.limit,
})
}
export class AdminGetProductTypesPaginationParams {
@IsNumber()
@IsOptional()
@Type(() => Number)
limit? = 10
@IsNumber()
@IsOptional()
@Type(() => Number)
offset? = 0
}
export class AdminGetProductTypesParams extends AdminGetProductTypesPaginationParams {
@ValidateNested()
@IsType([String, [String], StringComparisonOperator])
@IsOptional()
id?: string | string[] | StringComparisonOperator
@ValidateNested()
@IsType([String, [String], StringComparisonOperator])
@IsOptional()
value?: string | string[] | StringComparisonOperator
@IsType([DateComparisonOperator])
@IsOptional()
created_at?: DateComparisonOperator
@IsType([DateComparisonOperator])
@IsOptional()
updated_at?: DateComparisonOperator
@IsString()
@IsOptional()
order?: string
}
@@ -5,6 +5,9 @@ import { RegionServiceMock } from "../../../../../services/__mocks__/region"
const defaultFields = [
"id",
"name",
"automatic_taxes",
"gift_cards_taxable",
"tax_provider_id",
"currency_code",
"tax_rate",
"tax_code",
@@ -5,6 +5,9 @@ import { RegionServiceMock } from "../../../../../services/__mocks__/region"
const defaultFields = [
"id",
"name",
"automatic_taxes",
"gift_cards_taxable",
"tax_provider_id",
"currency_code",
"tax_rate",
"tax_code",
@@ -77,6 +77,9 @@ export default (app) => {
export const defaultAdminRegionFields = [
"id",
"name",
"automatic_taxes",
"gift_cards_taxable",
"tax_provider_id",
"currency_code",
"tax_rate",
"tax_code",
@@ -1,4 +1,10 @@
import { IsArray, IsNumber, IsOptional, IsString } from "class-validator"
import {
IsArray,
IsBoolean,
IsNumber,
IsOptional,
IsString,
} from "class-validator"
import { defaultAdminRegionRelations, defaultAdminRegionFields } from "."
import { validator } from "../../../../utils/validator"
import RegionService from "../../../../services/region"
@@ -22,6 +28,15 @@ import RegionService from "../../../../services/region"
* currency_code:
* description: "The 3 character ISO currency code to use for the Region."
* type: string
* automatic_taxes:
* description: "If true Medusa will automatically calculate taxes for carts in this region. If false you have to manually call POST /carts/:id/taxes."
* type: boolean
* gift_cards_taxable:
* description: "Whether gift cards in this region should be applied sales tax when purchasing a gift card"
* type: boolean
* tax_provider_id:
* description: "The id of the tax provider to use; if null the system tax provider is used"
* type: string
* tax_code:
* description: "An optional tax code the Region."
* type: string
@@ -86,6 +101,18 @@ export class AdminPostRegionsRegionReq {
@IsOptional()
tax_rate?: number
@IsBoolean()
@IsOptional()
gift_cards_taxable?: boolean
@IsBoolean()
@IsOptional()
automatic_taxes?: boolean
@IsString()
@IsOptional()
tax_provider_id?: string | null
@IsArray()
@IsString({ each: true })
@IsOptional()
@@ -40,8 +40,8 @@ describe("GET /admin/shipping-options", () => {
})
it("calls service retrieve", () => {
expect(ShippingOptionServiceMock.list).toHaveBeenCalledTimes(1)
expect(ShippingOptionServiceMock.list).toHaveBeenCalledWith(
expect(ShippingOptionServiceMock.listAndCount).toHaveBeenCalledTimes(1)
expect(ShippingOptionServiceMock.listAndCount).toHaveBeenCalledWith(
{},
{
select: defaultFields,
@@ -1,6 +1,6 @@
import { Router } from "express"
import { ShippingOption } from "../../../.."
import { DeleteResponse } from "../../../../types/common"
import { PaginatedResponse, DeleteResponse } from "../../../../types/common"
import middlewares from "../../../middlewares"
const route = Router()
@@ -46,7 +46,7 @@ export const defaultFields = [
export const defaultRelations = ["region", "profile", "requirements"]
export type AdminShippingOptionsListRes = {
export type AdminShippingOptionsListRes = PaginatedResponse & {
shipping_options: ShippingOption[]
}
@@ -50,12 +50,12 @@ export default async (req, res) => {
)
const optionService = req.scope.resolve("shippingOptionService")
const data = await optionService.list(validatedParams, {
const [data, count] = await optionService.listAndCount(validatedParams, {
select: defaultFields,
relations: defaultRelations,
})
res.status(200).json({ shipping_options: data })
res.status(200).json({ shipping_options: data, count })
}
export class AdminGetShippingOptionsParams {
@@ -1,5 +1,5 @@
import { Router } from "express"
import { Store, PaymentProvider } from "./../../../../"
import { Store, PaymentProvider, TaxProvider } from "./../../../../"
import middlewares from "../../../middlewares"
const route = Router()
@@ -12,6 +12,10 @@ export default (app) => {
"/payment-providers",
middlewares.wrap(require("./list-payment-providers").default)
)
route.get(
"/tax-providers",
middlewares.wrap(require("./list-tax-providers").default)
)
route.post("/", middlewares.wrap(require("./update-store").default))
route.post(
"/currencies/:currency_code",
@@ -29,6 +33,10 @@ export type AdminStoresRes = {
store: Store
}
export type AdminTaxProvidersList = {
tax_providers: TaxProvider[]
}
export type AdminPaymentProvidersList = {
payment_providers: PaymentProvider[]
}
@@ -0,0 +1,28 @@
import { TaxProviderService } from "../../../../services"
/**
* @oas [get] /store/tax-providers
* operationId: "GetStoreTaxProviders"
* summary: "Retrieve configured Tax Providers"
* description: "Retrieves the configured Tax Providers"
* x-authenticated: true
* tags:
* - Store
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_providers:
* type: array
* items:
* $ref: "#/components/schemas/store"
*/
export default async (req, res) => {
const taxProviderService: TaxProviderService =
req.scope.resolve("taxProviderService")
const taxProviders = await taxProviderService.list()
res.status(200).json({ tax_providers: taxProviders })
}
@@ -11,12 +11,6 @@ const defaultRelations = [
"shipping_address",
"shipping_methods",
"cart",
"cart.items",
"cart.region",
"cart.shipping_methods",
"cart.gift_cards",
"cart.discounts",
"cart.payment",
]
const defaultFields = [
@@ -30,12 +30,6 @@ export const defaultAdminSwapRelations = [
"shipping_address",
"shipping_methods",
"cart",
"cart.items",
"cart.region",
"cart.shipping_methods",
"cart.gift_cards",
"cart.discounts",
"cart.payment",
]
export const defaultAdminSwapFields = [
@@ -0,0 +1,66 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [post] /tax-rates/:id/product-types/batch
* operationId: "PostTaxRatesTaxRateProductTypes"
* summary: "Add Tax Rate to Product Types"
* description: "Associates a Tax Rate with a list of Product Types"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(
AdminPostTaxRatesTaxRateProductTypesReq,
req.body
)
const query = await validator(
AdminPostTaxRatesTaxRateProductTypesParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.addToProductType(req.params.id, value.product_types)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminPostTaxRatesTaxRateProductTypesReq {
@IsArray()
product_types: string[]
}
export class AdminPostTaxRatesTaxRateProductTypesParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,63 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [post] /tax-rates/:id/products/batch
* operationId: "PostTaxRatesTaxRateProducts"
* summary: "Add Tax Rate to Products"
* description: "Associates a Tax Rate with a list of Products"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(AdminPostTaxRatesTaxRateProductsReq, req.body)
const query = await validator(
AdminPostTaxRatesTaxRateProductsParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.addToProduct(req.params.id, value.products)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminPostTaxRatesTaxRateProductsReq {
@IsArray()
products: string[]
}
export class AdminPostTaxRatesTaxRateProductsParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,65 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [post] /tax-rates/:id/shipping-options/batch
* operationId: "PostTaxRatesTaxRateShippingOptions"
* summary: "Add Tax Rate to Product Types"
* description: "Associates a Tax Rate with a list of Product Types"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(
AdminPostTaxRatesTaxRateShippingOptionsReq,
req.body
)
const query = await validator(
AdminPostTaxRatesTaxRateShippingOptionsParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.addToShippingOption(req.params.id, value.shipping_options)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminPostTaxRatesTaxRateShippingOptionsReq {
@IsArray()
shipping_options: string[]
}
export class AdminPostTaxRatesTaxRateShippingOptionsParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,114 @@
import { EntityManager } from "typeorm"
import { IsString, IsArray, IsOptional } from "class-validator"
import { omit } from "lodash"
import { MedusaError } from "medusa-core-utils"
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
import { IsType } from "../../../../utils/validators/is-type"
/**
* @oas [post] /tax-rates
* operationId: "PostTaxRates"
* summary: "Create a Tax Rate"
* description: "Creates a Tax Rate"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(AdminPostTaxRatesReq, req.body)
const query = await validator(AdminPostTaxRatesParams, req.query)
const manager: EntityManager = req.scope.resolve("manager")
const rateService: TaxRateService = req.scope.resolve("taxRateService")
let id: string | undefined
await manager.transaction(async (tx) => {
const txRateService = rateService.withTransaction(tx)
const created = await txRateService.create(
omit(value, ["products", "product_types", "shipping_options"])
)
id = created.id
if (typeof value.products !== "undefined") {
await txRateService.addToProduct(id, value.products)
}
if (typeof value.product_types !== "undefined") {
await txRateService.addToProductType(id, value.product_types)
}
if (typeof value.shipping_options !== "undefined") {
await txRateService.addToShippingOption(id, value.shipping_options)
}
})
if (typeof id === "undefined") {
throw new MedusaError(
MedusaError.Types.UNEXPECTED_STATE,
"Tax Rate was not created"
)
}
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminPostTaxRatesReq {
@IsString()
code: string
@IsString()
name: string
@IsString()
region_id: string
@IsOptional()
@IsType([Number, null])
rate?: number | null
@IsOptional()
@IsArray()
products?: string[]
@IsOptional()
@IsArray()
shipping_options?: string[]
@IsOptional()
@IsArray()
product_types?: string[]
}
export class AdminPostTaxRatesParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,40 @@
import { TaxRateService } from "../../../../services"
/**
* @oas [delete] /tax-rates/{id}
* operationId: "DeleteTaxRatesTaxRate"
* summary: "Delete a Tax Rate"
* description: "Deletes a Tax Rate"
* x-authenticated: true
* parameters:
* - (path) id=* {string} The id of the Shipping Option.
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* id:
* type: string
* description: The id of the deleted Shipping Option.
* object:
* type: string
* description: The type of the object that was deleted.
* deleted:
* type: boolean
*/
export default async (req, res) => {
const { id } = req.params
const taxRateService: TaxRateService = req.scope.resolve("taxRateService")
await taxRateService.delete(id)
res.json({
id: id,
object: "tax-rate",
deleted: true,
})
}
@@ -0,0 +1,50 @@
import { getRetrieveConfig, pickByConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [get] /tax-rates/:id
* operationId: "GetTaxRatesTaxRate"
* summary: "Get Tax Rate"
* description: "Retrieves a TaxRate"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(AdminGetTaxRatesTaxRateParams, req.query)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
const config = getRetrieveConfig(
value.fields as (keyof TaxRate)[],
value.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig<TaxRate>(rate, config)
res.json({ tax_rate: data })
}
export class AdminGetTaxRatesTaxRateParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,119 @@
import { Router } from "express"
import { TaxRate } from "../../../.."
import { DeleteResponse, PaginatedResponse } from "../../../../types/common"
import middlewares from "../../../middlewares"
const route = Router()
export default (app) => {
app.use("/tax-rates", route)
/**
* List tax rates
*/
route.get("/", middlewares.wrap(require("./list-tax-rates").default))
/**
* Get a tax rate
*/
route.get("/:id", middlewares.wrap(require("./get-tax-rate").default))
/**
* Create a tax rate
*/
route.post("/", middlewares.wrap(require("./create-tax-rate").default))
/**
* Update a tax rate
*/
route.post("/:id", middlewares.wrap(require("./update-tax-rate").default))
/**
* Remove products from tax rate
*/
route.delete(
"/:id/products/batch",
middlewares.wrap(require("./remove-from-products").default)
)
/**
* Remove product types from tax rate
*/
route.delete(
"/:id/product-types/batch",
middlewares.wrap(require("./remove-from-product-types").default)
)
/**
* Remove shipping options from tax rate
*/
route.delete(
"/:id/shipping-options/batch",
middlewares.wrap(require("./remove-from-shipping-options").default)
)
/**
* Add products to tax rate
*/
route.post(
"/:id/products/batch",
middlewares.wrap(require("./add-to-products").default)
)
/**
* Add product types to tax rate
*/
route.post(
"/:id/product-types/batch",
middlewares.wrap(require("./add-to-product-types").default)
)
/**
* Add to shipping options
*/
route.post(
"/:id/shipping-options/batch",
middlewares.wrap(require("./add-to-shipping-options").default)
)
/**
* Delete a tax rate
*/
route.delete("/:id", middlewares.wrap(require("./delete-tax-rate").default))
return app
}
export const defaultAdminTaxRatesRelations = []
export const defaultAdminTaxRatesFields: (keyof TaxRate)[] = [
"id",
"rate",
"code",
"name",
"region_id",
"created_at",
"updated_at",
]
export type AdminTaxRatesDeleteRes = DeleteResponse
export type AdminTaxRatesListRes = PaginatedResponse & {
tax_rates: TaxRate[]
}
export type AdminTaxRatesRes = {
tax_rate: TaxRate
}
export * from "./list-tax-rates"
export * from "./get-tax-rate"
export * from "./remove-from-product-types"
export * from "./remove-from-products"
export * from "./remove-from-shipping-options"
export * from "./add-to-product-types"
export * from "./add-to-products"
export * from "./add-to-shipping-options"
export * from "./create-tax-rate"
export * from "./delete-tax-rate"
export * from "./update-tax-rate"
@@ -0,0 +1,111 @@
import { getListConfig, pickByConfig } from "./utils/get-query-config"
import {
IsArray,
ValidateNested,
IsNumber,
IsOptional,
IsString,
} from "class-validator"
import { Type } from "class-transformer"
import { omit, pickBy, pick, identity } from "lodash"
import { TaxRate } from "../../../.."
import {
NumericalComparisonOperator,
FindConfig,
} from "../../../../types/common"
import { TaxRateService } from "../../../../services"
import { IsType } from "../../../../utils/validators/is-type"
import { validator } from "../../../../utils/validator"
/**
* @oas [get] /tax-rates
* operationId: "GetTaxRates"
* summary: "List Tax Rates"
* description: "Retrieves a list of TaxRates"
* x-authenticated: true
* parameters:
* - (query) q {string} Query used for searching orders.
* - (query) id {string} Id of the order to search for.
* - (query) region_id {string} to search for.
* - (query) code {string} to search for.
* - (query) rate {string} to search for.
* - (query) created_at {DateComparisonOperator} Date comparison for when resulting orders was created, i.e. less than, greater than etc.
* - (query) updated_at {DateComparisonOperator} Date comparison for when resulting orders was updated, i.e. less than, greater than etc.
* - (query) offset {string} How many orders to skip in the result.
* - (query) limit {string} Limit the number of orders returned.
* - (query) fields {string} (Comma separated) Which fields should be included in each order of the result.
* tags:
* - Order
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* orders:
* type: array
* items:
* $ref: "#/components/schemas/order"
*/
export default async (req, res) => {
const value = await validator(AdminGetTaxRatesParams, req.query)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
const listConfig = getListConfig()
const filterableFields = omit(value, [
"limit",
"offset",
"expand",
"fields",
"order",
])
const [rates, count] = await rateService.listAndCount(
pickBy(filterableFields, identity),
listConfig
)
const data = pickByConfig<TaxRate>(rates, listConfig)
res.json({ tax_rates: data, count, offset: value.offset, limit: value.limit })
}
export class AdminGetTaxRatesParams {
@IsOptional()
@IsType([String, [String]])
region_id?: string | string[]
@IsString()
@IsOptional()
name?: string
@IsString()
@IsOptional()
code?: string
@IsType([NumericalComparisonOperator, Number])
@IsOptional()
rate?: number | NumericalComparisonOperator
@IsNumber()
@IsOptional()
@Type(() => Number)
offset? = 0
@IsNumber()
@IsOptional()
@Type(() => Number)
limit? = 50
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,66 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [delete] /tax-rates/:id/product-types/batch
* operationId: "DeleteTaxRatesTaxRateProductTypes"
* summary: "Remove Tax Rate from Product Types"
* description: "Removes a Tax Rate from a list of Product Types"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(
AdminDeleteTaxRatesTaxRateProductTypesReq,
req.body
)
const query = await validator(
AdminDeleteTaxRatesTaxRateProductTypesParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.removeFromProductType(req.params.id, value.product_types)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminDeleteTaxRatesTaxRateProductTypesReq {
@IsArray()
product_types: string[]
}
export class AdminDeleteTaxRatesTaxRateProductTypesParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,63 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [delete] /tax-rates/:id/products/batch
* operationId: "DeleteTaxRatesTaxRateProducts"
* summary: "Removes Tax Rate from Products"
* description: "Removes a Tax Rate from a list of Products"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(AdminDeleteTaxRatesTaxRateProductsReq, req.body)
const query = await validator(
AdminDeleteTaxRatesTaxRateProductsParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.removeFromProduct(req.params.id, value.products)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminDeleteTaxRatesTaxRateProductsReq {
@IsArray()
products: string[]
}
export class AdminDeleteTaxRatesTaxRateProductsParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,69 @@
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { IsArray, IsOptional } from "class-validator"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
/**
* @oas [delete] /tax-rates/:id/shipping-options/batch
* operationId: "DeleteTaxRatesTaxRateShippingOptions"
* summary: "Removes a Tax Rate from Product Types"
* description: "Removes a Tax Rate from a list of Product Types"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(
AdminDeleteTaxRatesTaxRateShippingOptionsReq,
req.body
)
const query = await validator(
AdminDeleteTaxRatesTaxRateShippingOptionsParams,
req.query
)
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await rateService.removeFromShippingOption(
req.params.id,
value.shipping_options
)
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminDeleteTaxRatesTaxRateShippingOptionsReq {
@IsArray()
shipping_options: string[]
}
export class AdminDeleteTaxRatesTaxRateShippingOptionsParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,116 @@
import { EntityManager } from "typeorm"
import { IsString, IsArray, IsOptional } from "class-validator"
import { omit } from "lodash"
import { pickByConfig, getRetrieveConfig } from "./utils/get-query-config"
import { TaxRate } from "../../../.."
import { TaxRateService } from "../../../../services"
import { validator } from "../../../../utils/validator"
import { IsType } from "../../../../utils/validators/is-type"
/**
* @oas [post] /tax-rates/:id
* operationId: "PostTaxRatesTaxRate"
* summary: "Update a Tax Rate"
* description: "Updates a Tax Rate"
* x-authenticated: true
* tags:
* - Tax Rates
* responses:
* 200:
* description: OK
* content:
* application/json:
* schema:
* properties:
* tax_rate:
* type: array
* items:
* $ref: "#/components/schemas/tax_rate"
*/
export default async (req, res) => {
const value = await validator(AdminPostTaxRatesTaxRateReq, req.body)
const query = await validator(AdminPostTaxRatesTaxRateParams, req.query)
const manager: EntityManager = req.scope.resolve("manager")
const rateService: TaxRateService = req.scope.resolve("taxRateService")
await manager.transaction(async (tx) => {
const txRateService = rateService.withTransaction(tx)
await txRateService.update(
req.params.id,
omit(value, ["products", "product_types", "shipping_options"])
)
if (typeof value.products !== "undefined") {
await txRateService.addToProduct(req.params.id, value.products, true)
}
if (typeof value.product_types !== "undefined") {
await txRateService.addToProductType(
req.params.id,
value.product_types,
true
)
}
if (typeof value.shipping_options !== "undefined") {
await txRateService.addToShippingOption(
req.params.id,
value.shipping_options,
true
)
}
})
const config = getRetrieveConfig(
query.fields as (keyof TaxRate)[],
query.expand
)
const rate = await rateService.retrieve(req.params.id, config)
const data = pickByConfig(rate, config)
res.json({ tax_rate: data })
}
export class AdminPostTaxRatesTaxRateReq {
@IsOptional()
@IsString()
code?: string
@IsOptional()
@IsString()
name?: string
@IsOptional()
@IsString()
region_id?: string
@IsOptional()
@IsType([Number, null])
rate?: number | null
@IsOptional()
@IsArray()
products?: string[]
@IsOptional()
@IsArray()
shipping_options?: string[]
@IsOptional()
@IsArray()
product_types?: string[]
}
export class AdminPostTaxRatesTaxRateParams {
@IsArray()
@IsOptional()
expand?: string[]
@IsArray()
@IsOptional()
fields?: string[]
}
@@ -0,0 +1,78 @@
import { defaultAdminTaxRatesFields, defaultAdminTaxRatesRelations } from "../"
import { pick } from "lodash"
import { FindConfig } from "../../../../../types/common"
import { TaxRate } from "../../../../.."
export function pickByConfig<T>(
obj: T | T[],
config: FindConfig<T>
): Partial<T> | Partial<T>[] {
const fields = [...(config.select ?? []), ...(config.relations ?? [])]
if (fields.length) {
if (Array.isArray(obj)) {
return obj.map((o) => pick(o, fields))
} else {
return pick(obj, fields)
}
}
return obj
}
export function getRetrieveConfig(
fields?: (keyof TaxRate)[],
expand?: string[]
): FindConfig<TaxRate> {
let includeFields: (keyof TaxRate)[] = []
if (typeof fields !== "undefined") {
const fieldSet = new Set(fields)
fieldSet.add("id")
includeFields = Array.from(fieldSet) as (keyof TaxRate)[]
}
let expandFields: string[] = []
if (typeof expand !== "undefined") {
expandFields = expand
}
return {
select: includeFields.length ? includeFields : defaultAdminTaxRatesFields,
relations: expandFields.length
? expandFields
: defaultAdminTaxRatesRelations,
}
}
export function getListConfig(
fields?: (keyof TaxRate)[],
expand?: string[],
limit = 50,
offset = 0,
order?: { [k: symbol]: "DESC" | "ASC" }
): FindConfig<TaxRate> {
let includeFields: (keyof TaxRate)[] = []
if (typeof fields !== "undefined") {
const fieldSet = new Set(fields)
// Ensure created_at is included, since we are sorting on this
fieldSet.add("created_at")
fieldSet.add("id")
includeFields = Array.from(fieldSet) as (keyof TaxRate)[]
}
let expandFields: string[] = []
if (typeof expand !== "undefined") {
expandFields = expand
}
const orderBy = order ?? { created_at: "DESC" }
return {
select: includeFields.length ? includeFields : defaultAdminTaxRatesFields,
relations: expandFields.length
? expandFields
: defaultAdminTaxRatesRelations,
skip: offset,
take: limit,
order: orderBy,
}
}
@@ -1,119 +1,56 @@
import { IdMap } from "medusa-test-utils"
import { request } from "../../../../../helpers/test-request"
import { CartServiceMock } from "../../../../../services/__mocks__/cart"
import { OrderServiceMock } from "../../../../../services/__mocks__/order"
import { SwapServiceMock } from "../../../../../services/__mocks__/swap"
import { CompletionStrategyMock } from "../../../../../strategies/__mocks__/cart-completion"
describe("POST /store/carts/:id", () => {
describe("successfully completes a normal cart", () => {
describe("POST /store/carts/:id/complete", () => {
describe("successfully calls completion strategy - Legacy Endpoint", () => {
let subject
beforeAll(async () => {
subject = await request(
"POST",
`/store/carts/${IdMap.getId("test-cart")}/complete-cart`
)
subject = await request("POST", `/store/carts/test-cart/complete-cart`)
})
afterAll(() => {
jest.clearAllMocks()
})
it("Call CartService authorizePayment", () => {
expect(CartServiceMock.authorizePayment).toHaveBeenCalledTimes(1)
expect(CartServiceMock.authorizePayment).toHaveBeenCalledWith(
IdMap.getId("test-cart"),
{ idempotency_key: "testkey" }
it("calls completion strat", () => {
expect(CompletionStrategyMock.complete).toHaveBeenCalledTimes(1)
expect(CompletionStrategyMock.complete).toHaveBeenCalledWith(
"test-cart",
{ idempotency_key: "testkey", recovery_point: "started" },
undefined
)
})
it("Call OrderService createFromCart", () => {
expect(OrderServiceMock.createFromCart).toHaveBeenCalledTimes(1)
expect(OrderServiceMock.createFromCart).toHaveBeenCalledWith(
IdMap.getId("test-cart")
)
})
it("returns 200", () => {
it("responds correctly", () => {
expect(subject.status).toEqual(200)
})
it("returns the created order", () => {
expect(subject.body.data.id).toEqual(IdMap.getId("test-order"))
expect(subject.body).toEqual({})
})
})
describe("successfully completes a swap cart", () => {
describe("successfully calls completion strategy", () => {
let subject
beforeAll(async () => {
subject = await request(
"POST",
`/store/carts/${IdMap.getId("swap-cart")}/complete-cart`
)
subject = await request("POST", `/store/carts/test-cart/complete`)
})
afterAll(() => {
jest.clearAllMocks()
})
it("Call CartService authorizePayment", () => {
expect(CartServiceMock.authorizePayment).toHaveBeenCalledTimes(1)
expect(CartServiceMock.authorizePayment).toHaveBeenCalledWith(
IdMap.getId("swap-cart"),
{ idempotency_key: "testkey" }
it("calls completion strat", () => {
expect(CompletionStrategyMock.complete).toHaveBeenCalledTimes(1)
expect(CompletionStrategyMock.complete).toHaveBeenCalledWith(
"test-cart",
{ idempotency_key: "testkey", recovery_point: "started" },
undefined
)
})
it("Call SwapService registerCartCompletion", () => {
expect(SwapServiceMock.registerCartCompletion).toHaveBeenCalledTimes(1)
expect(SwapServiceMock.registerCartCompletion).toHaveBeenCalledWith(
"test-swap"
)
})
it("returns 200", () => {
it("responds correctly", () => {
expect(subject.status).toEqual(200)
})
it("returns the created order", () => {
expect(subject.body.data.id).toEqual("test-swap")
})
})
describe("returns early if payment requires more work", () => {
let subject
beforeAll(async () => {
subject = await request(
"POST",
`/store/carts/${IdMap.getId("test-cart2")}/complete-cart`
)
})
afterAll(() => {
jest.clearAllMocks()
})
it("Call CartService authorizePayment", () => {
expect(CartServiceMock.authorizePayment).toHaveBeenCalledTimes(1)
expect(CartServiceMock.authorizePayment).toHaveBeenCalledWith(
IdMap.getId("test-cart2"),
{ idempotency_key: "testkey" }
)
})
it("Call CartService retrieve 1 time", () => {
expect(CartServiceMock.retrieve).toHaveBeenCalledTimes(1)
})
it("returns 200", () => {
expect(subject.status).toEqual(200)
})
it("returns the created order", () => {
expect(subject.body.data.id).toEqual(IdMap.getId("test-cart2"))
expect(subject.body.data.payment_session.status).toEqual("requires_more")
expect(subject.body).toEqual({})
})
})
})
@@ -0,0 +1,118 @@
import { EntityManager } from "typeorm"
import { IdempotencyKey } from "../../../../models/idempotency-key"
import { CartService, IdempotencyKeyService } from "../../../../services"
/**
* @oas [post] /carts/{id}/taxes
* summary: "Calculate Cart Taxes"
* operationId: "PostCartsCartTaxes"
* description: "Calculates taxes for a cart. Depending on the cart's region
* this may involve making 3rd party API calls to a Tax Provider service."
* parameters:
* - (path) id=* {String} The Cart id.
* tags:
* - Cart
* responses:
* 200:
* description: "A cart object with the tax_total field populated"
* content:
* application/json:
* schema:
* oneOf:
* - type: object
* properties:
* cart:
* $ref: "#/components/schemas/cart"
*/
export default async (req, res) => {
const { id } = req.params
const idempotencyKeyService: IdempotencyKeyService = req.scope.resolve(
"idempotencyKeyService"
)
const headerKey = req.get("Idempotency-Key") || ""
let idempotencyKey: IdempotencyKey
try {
idempotencyKey = await idempotencyKeyService.initializeRequest(
headerKey,
req.method,
req.params,
req.path
)
} catch (error) {
console.log(error)
res.status(409).send("Failed to create idempotency key")
return
}
res.setHeader("Access-Control-Expose-Headers", "Idempotency-Key")
res.setHeader("Idempotency-Key", idempotencyKey.idempotency_key)
const cartService: CartService = req.scope.resolve("cartService")
let inProgress = true
let err = false
while (inProgress) {
switch (idempotencyKey.recovery_point) {
case "started": {
const { key, error } = await idempotencyKeyService.workStage(
idempotencyKey.idempotency_key,
async (manager: EntityManager) => {
const cart = await cartService.withTransaction(manager).retrieve(
id,
{
select: [
"total",
"subtotal",
"tax_total",
"discount_total",
"shipping_total",
"gift_card_total",
],
},
{ force_taxes: true }
)
return {
response_code: 200,
response_body: { cart },
}
}
)
if (error) {
inProgress = false
err = error
} else {
idempotencyKey = key
}
break
}
case "finished": {
inProgress = false
break
}
default:
idempotencyKey = await idempotencyKeyService.update(
idempotencyKey.idempotency_key,
{
recovery_point: "finished",
response_code: 500,
response_body: { message: "Unknown recovery point" },
}
)
break
}
}
if (err) {
throw err
}
res.status(idempotencyKey.response_code).json(idempotencyKey.response_body)
}
@@ -1,12 +1,6 @@
import { MedusaError } from "medusa-core-utils"
import {
CartService,
IdempotencyKeyService,
OrderService,
SwapService,
} from "../../../../services"
import { Order } from "../../../../models/order"
import { ICartCompletionStrategy } from "../../../../interfaces"
import { IdempotencyKeyService } from "../../../../services"
import { IdempotencyKey } from "../../../../models/idempotency-key"
/**
* @oas [post] /carts/{id}/complete
@@ -54,7 +48,7 @@ export default async (req, res) => {
const headerKey = req.get("Idempotency-Key") || ""
let idempotencyKey
let idempotencyKey: IdempotencyKey
try {
idempotencyKey = await idempotencyKeyService.initializeRequest(
headerKey,
@@ -71,231 +65,15 @@ export default async (req, res) => {
res.setHeader("Access-Control-Expose-Headers", "Idempotency-Key")
res.setHeader("Idempotency-Key", idempotencyKey.idempotency_key)
const cartService: CartService = req.scope.resolve("cartService")
const orderService: OrderService = req.scope.resolve("orderService")
const swapService: SwapService = req.scope.resolve("swapService")
const completionStrat: ICartCompletionStrategy = req.scope.resolve(
"cartCompletionStrategy"
)
let inProgress = true
let err = false
const { response_code, response_body } = await completionStrat.complete(
id,
idempotencyKey,
req.request_context
)
while (inProgress) {
switch (idempotencyKey.recovery_point) {
case "started": {
const { key, error } = await idempotencyKeyService.workStage(
idempotencyKey.idempotency_key,
async (manager) => {
let cart = await cartService.withTransaction(manager).retrieve(id)
if (cart.completed_at) {
return {
response_code: 409,
response_body: {
code: MedusaError.Codes.CART_INCOMPATIBLE_STATE,
message: "Cart has already been completed",
type: MedusaError.Types.NOT_ALLOWED,
},
}
}
cart = await cartService
.withTransaction(manager)
.authorizePayment(id, {
...req.request_context,
idempotency_key: idempotencyKey.idempotency_key,
})
if (cart.payment_session) {
if (
cart.payment_session.status === "requires_more" ||
cart.payment_session.status === "pending"
) {
return {
response_code: 200,
response_body: {
data: cart,
payment_status: cart.payment_session.status,
type: "cart",
},
}
}
}
return {
recovery_point: "payment_authorized",
}
}
)
if (error) {
inProgress = false
err = error
} else {
idempotencyKey = key
}
break
}
case "payment_authorized": {
const { key, error } = await idempotencyKeyService.workStage(
idempotencyKey.idempotency_key,
async (manager) => {
const cart = await cartService
.withTransaction(manager)
.retrieve(id, {
select: ["total"],
relations: ["payment", "payment_sessions"],
})
let order: Order
// If cart is part of swap, we register swap as complete
switch (cart.type) {
case "swap": {
try {
const swapId = cart.metadata?.swap_id
let swap = await swapService
.withTransaction(manager)
.registerCartCompletion(swapId)
swap = await swapService
.withTransaction(manager)
.retrieve(swap.id, { relations: ["shipping_address"] })
return {
response_code: 200,
response_body: { data: swap, type: "swap" },
}
} catch (error) {
if (
error &&
error.code === MedusaError.Codes.INSUFFICIENT_INVENTORY
) {
return {
response_code: 409,
response_body: {
message: error.message,
type: error.type,
code: error.code,
},
}
} else {
throw error
}
}
}
// case "payment_link":
default: {
if (typeof cart.total === "undefined") {
return {
response_code: 500,
response_body: {
message: "Unexpected state",
},
}
}
if (!cart.payment && cart.total > 0) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Cart payment not authorized`
)
}
try {
order = await orderService
.withTransaction(manager)
.createFromCart(cart.id)
} catch (error) {
if (
error &&
error.message === "Order from cart already exists"
) {
order = await orderService
.withTransaction(manager)
.retrieveByCartId(id, {
select: [
"subtotal",
"tax_total",
"shipping_total",
"discount_total",
"total",
],
relations: ["shipping_address", "items", "payments"],
})
return {
response_code: 200,
response_body: { data: order, type: "order" },
}
} else if (
error &&
error.code === MedusaError.Codes.INSUFFICIENT_INVENTORY
) {
return {
response_code: 409,
response_body: {
message: error.message,
type: error.type,
code: error.code,
},
}
} else {
throw error
}
}
}
}
order = await orderService
.withTransaction(manager)
.retrieve(order.id, {
select: [
"subtotal",
"tax_total",
"shipping_total",
"discount_total",
"total",
],
relations: ["shipping_address", "items", "payments"],
})
return {
response_code: 200,
response_body: { data: order, type: "order" },
}
}
)
if (error) {
inProgress = false
err = error
} else {
idempotencyKey = key
}
break
}
case "finished": {
inProgress = false
break
}
default:
idempotencyKey = await idempotencyKeyService.update(
idempotencyKey.idempotency_key,
{
recovery_point: "finished",
response_code: 500,
response_body: { message: "Unknown recovery point" },
}
)
break
}
}
if (err) {
throw err
}
res.status(idempotencyKey.response_code).json(idempotencyKey.response_body)
res.status(response_code).json(response_body)
}
@@ -93,6 +93,12 @@ export default (app, container) => {
middlewares.wrap(require("./add-shipping-method").default)
)
// Taxes
route.post(
"/:id/taxes",
middlewares.wrap(require("./calculate-taxes").default)
)
return app
}
@@ -128,7 +128,13 @@ export default async (req, res) => {
.withTransaction(manager)
.retrieve(swapDto.order_id, {
select: ["refunded_total", "total"],
relations: ["items", "swaps", "swaps.additional_items"],
relations: [
"items",
"items.tax_lines",
"swaps",
"swaps.additional_items",
"swaps.additional_items.tax_lines",
],
})
let returnShipping
@@ -8,6 +8,7 @@ import config from "../config"
import apiLoader from "../loaders/api"
import passportLoader from "../loaders/passport"
import servicesLoader from "../loaders/services"
import strategiesLoader from "../loaders/strategies"
const adminSessionOpts = {
cookieName: "session",
@@ -45,6 +46,7 @@ testApp.use((req, res, next) => {
})
servicesLoader({ container })
strategiesLoader({ container })
passportLoader({ app: testApp, container })
testApp.use((req, res, next) => {
+61 -51
View File
@@ -1,55 +1,65 @@
// API payloads
export * from "./api"
// Interfaces
export * from "./interfaces"
// Models
export { Address } from "./models/address"
export { Cart } from "./models/cart"
export { ClaimImage } from "./models/claim-image"
export { ClaimItem } from "./models/claim-item"
export { ClaimOrder } from "./models/claim-order"
export { ClaimTag } from "./models/claim-tag"
export { Country } from "./models/country"
export { Currency } from "./models/currency"
export { CustomShippingOption } from "./models/custom-shipping-option"
export { Customer } from "./models/customer"
export { CustomerGroup } from "./models/customer-group"
export { Discount } from "./models/discount"
export { DiscountRule } from "./models/discount-rule"
export { DraftOrder } from "./models/draft-order"
export { Fulfillment } from "./models/fulfillment"
export { FulfillmentItem } from "./models/fulfillment-item"
export { FulfillmentProvider } from "./models/fulfillment-provider"
export { GiftCard } from "./models/gift-card"
export { GiftCardTransaction } from "./models/gift-card-transaction"
export { IdempotencyKey } from "./models/idempotency-key"
export { Image } from "./models/image"
export { Invite } from "./models/invite"
export { LineItem } from "./models/line-item"
export { MoneyAmount } from "./models/money-amount"
export { Note } from "./models/note"
export { Notification } from "./models/notification"
export { Oauth } from "./models/oauth"
export { Order } from "./models/order"
export { Payment } from "./models/payment"
export { PaymentProvider } from "./models/payment-provider"
export { PaymentSession } from "./models/payment-session"
export { Product } from "./models/product"
export { ProductCollection } from "./models/product-collection"
export { ProductOption } from "./models/product-option"
export { ProductOptionValue } from "./models/product-option-value"
export { ProductTag } from "./models/product-tag"
export { ProductType } from "./models/product-type"
export { ProductVariant } from "./models/product-variant"
export { Refund } from "./models/refund"
export { Region } from "./models/region"
export { Return } from "./models/return"
export { ReturnItem } from "./models/return-item"
export { ReturnReason } from "./models/return-reason"
export { ShippingMethod } from "./models/shipping-method"
export { ShippingOption } from "./models/shipping-option"
export { ShippingOptionRequirement } from "./models/shipping-option-requirement"
export { ShippingProfile } from "./models/shipping-profile"
export { StagedJob } from "./models/staged-job"
export { Store } from "./models/store"
export { Swap } from "./models/swap"
export { User } from "./models/user"
export * from "./models/shipping-tax-rate"
export * from "./models/product-tax-rate"
export * from "./models/product-type-tax-rate"
export * from "./models/tax-rate"
export * from "./models/shipping-method-tax-line"
export * from "./models/line-item-tax-line"
export * from "./models/address"
export * from "./models/cart"
export * from "./models/claim-image"
export * from "./models/claim-item"
export * from "./models/claim-order"
export * from "./models/claim-tag"
export * from "./models/country"
export * from "./models/currency"
export * from "./models/custom-shipping-option"
export * from "./models/customer"
export * from "./models/customer-group"
export * from "./models/discount"
export * from "./models/discount-rule"
export * from "./models/draft-order"
export * from "./models/fulfillment"
export * from "./models/fulfillment-item"
export * from "./models/fulfillment-provider"
export * from "./models/gift-card"
export * from "./models/gift-card-transaction"
export * from "./models/idempotency-key"
export * from "./models/image"
export * from "./models/invite"
export * from "./models/line-item"
export * from "./models/money-amount"
export * from "./models/note"
export * from "./models/notification"
export * from "./models/oauth"
export * from "./models/order"
export * from "./models/payment"
export * from "./models/payment-provider"
export * from "./models/payment-session"
export * from "./models/product"
export * from "./models/product-collection"
export * from "./models/product-option"
export * from "./models/product-option-value"
export * from "./models/product-tag"
export * from "./models/product-type"
export * from "./models/product-variant"
export * from "./models/refund"
export * from "./models/region"
export * from "./models/return"
export * from "./models/return-item"
export * from "./models/return-reason"
export * from "./models/shipping-method"
export * from "./models/shipping-option"
export * from "./models/shipping-option-requirement"
export * from "./models/shipping-profile"
export * from "./models/staged-job"
export * from "./models/store"
export * from "./models/swap"
export * from "./models/user"
export * from "./models/tax-provider"
@@ -0,0 +1,33 @@
import { IdempotencyKey } from "../models/idempotency-key"
import { RequestContext } from "../types/request"
export type CartCompletionResponse = {
/** The response code for the completion request */
response_code: number
/** The response body for the completion request */
response_body: object
}
export interface ICartCompletionStrategy {
/**
* Takes a cart id and completes the cart. This for example takes place when
* creating an order or confirming a swap.
* @param cartId - the id of the Cart to complete.
* @param idempotencyKey - the idempotency key for the request
* @param context - the request context for the completion request
* @return the response for the completion request
*/
complete(
cartId: string,
idempotencyKey: IdempotencyKey,
context: RequestContext
): Promise<CartCompletionResponse>
}
export function isCartCompletionStrategy(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
object: any
): object is ICartCompletionStrategy {
return typeof object.complete === "function"
}
+3
View File
@@ -0,0 +1,3 @@
export * from "./tax-calculation-strategy"
export * from "./cart-completion-strategy"
export * from "./tax-service"
@@ -0,0 +1,27 @@
import { LineItem } from "../models/line-item"
import { TaxCalculationContext } from "./tax-service"
import { LineItemTaxLine } from "../models/line-item-tax-line"
import { ShippingMethodTaxLine } from "../models/shipping-method-tax-line"
export interface ITaxCalculationStrategy {
/**
* Calculates the tax amount for a given set of line items under applicable
* tax conditions and calculation contexts.
* @param items - the line items to calculate the tax total for
* @param taxLines - the tax lines that applies to the calculation
* @param calculationContext - other details relevant for the calculation
* @return the tax total
*/
calculate(
items: LineItem[],
taxLines: (ShippingMethodTaxLine | LineItemTaxLine)[],
calculationContext: TaxCalculationContext
): Promise<number>
}
export function isTaxCalculationStrategy(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
object: any
): object is ITaxCalculationStrategy {
return typeof object.calculate === "function"
}
@@ -0,0 +1,59 @@
import { LineItem } from "../models/line-item"
import { Region } from "../models/region"
import { Address } from "../models/address"
import { ShippingMethod } from "../models/shipping-method"
import { Customer } from "../models/customer"
import { ProviderTaxLine, TaxServiceRate } from "../types/tax-service"
import { LineAllocationsMap } from "../types/totals"
/**
* A shipping method and the tax rates that have been configured to apply to the
* shipping method.
*/
export type ShippingTaxCalculationLine = {
shipping_method: ShippingMethod
rates: TaxServiceRate[]
}
/**
* A line item and the tax rates that have been configured to apply to the
* product contained in the line item.
*/
export type ItemTaxCalculationLine = {
item: LineItem
rates: TaxServiceRate[]
}
/**
* Information relevant to a tax calculation, such as the shipping address where
* the items are going.
*/
export type TaxCalculationContext = {
shipping_address: Address | null
customer: Customer
region: Region
is_return: boolean
shipping_methods: ShippingMethod[]
allocation_map: LineAllocationsMap
}
/**
* Interface to be implemented by tax provider plugins. The interface defines a
* single method `getTaxLines` that returns numerical rates to apply to line
* items and shipping methods.
*/
export interface ITaxService {
/**
* Retrieves the numerical tax lines for a calculation context.
* @param itemLines - the line item calculation lines
* @param itemLines - the shipping calculation lines
* @param context - other details relevant to the tax determination
* @return numerical tax rates that should apply to the provided calculation
* lines
*/
getTaxLines(
itemLines: ItemTaxCalculationLine[],
shippingLines: ShippingTaxCalculationLine[],
context: TaxCalculationContext
): Promise<ProviderTaxLine[]>
}
+17 -3
View File
@@ -16,9 +16,10 @@ import redisLoader from "./redis"
import repositoriesLoader from "./repositories"
import searchIndexLoader from "./search-index"
import servicesLoader from "./services"
import strategiesLoader from "./strategies"
import subscribersLoader from "./subscribers"
export default async ({ directory: rootDirectory, expressApp }) => {
export default async ({ directory: rootDirectory, expressApp, isTest }) => {
const { configModule } = getConfigFile(rootDirectory, `medusa-config`)
const container = createContainer()
@@ -58,7 +59,7 @@ export default async ({ directory: rootDirectory, expressApp }) => {
const modelsActivity = Logger.activity("Initializing models")
track("MODELS_INIT_STARTED")
modelsLoader({ container, activityId: modelsActivity })
modelsLoader({ container, activityId: modelsActivity, isTest })
const mAct = Logger.success(modelsActivity, "Models initialized") || {}
track("MODELS_INIT_COMPLETED", { duration: mAct.duration })
@@ -74,7 +75,7 @@ export default async ({ directory: rootDirectory, expressApp }) => {
const repoActivity = Logger.activity("Initializing repositories")
track("REPOSITORIES_INIT_STARTED")
repositoriesLoader({ container, activityId: repoActivity }) || {}
repositoriesLoader({ container, activityId: repoActivity, isTest }) || {}
const rAct = Logger.success(repoActivity, "Repositories initialized") || {}
track("REPOSITORIES_INIT_COMPLETED", { duration: rAct.duration })
@@ -84,6 +85,7 @@ export default async ({ directory: rootDirectory, expressApp }) => {
container,
configModule,
activityId: dbActivity,
isTest,
})
const dbAct = Logger.success(dbActivity, "Database initialized") || {}
track("DATABASE_INIT_COMPLETED", { duration: dbAct.duration })
@@ -92,12 +94,24 @@ export default async ({ directory: rootDirectory, expressApp }) => {
manager: asValue(dbConnection.manager),
})
const stratActivity = Logger.activity("Initializing strategies")
track("STRATEGIES_INIT_STARTED")
strategiesLoader({
container,
configModule,
activityId: stratActivity,
isTest,
})
const stratAct = Logger.success(stratActivity, "Strategies initialized") || {}
track("STRATEGIES_INIT_COMPLETED", { duration: stratAct.duration })
const servicesActivity = Logger.activity("Initializing services")
track("SERVICES_INIT_STARTED")
servicesLoader({
container,
configModule,
activityId: servicesActivity,
isTest,
})
const servAct = Logger.success(servicesActivity, "Services initialized") || {}
track("SERVICES_INIT_COMPLETED", { duration: servAct.duration })
+2 -2
View File
@@ -9,13 +9,13 @@ import formatRegistrationName from "../utils/format-registration-name"
* Registers all models in the model directory
*/
export default ({ container }, config = { register: true }) => {
let corePath = "../models/*.js"
const corePath = "../models/*.js"
const coreFull = path.join(__dirname, corePath)
const toReturn = []
const core = glob.sync(coreFull, { cwd: __dirname })
core.forEach(fn => {
core.forEach((fn) => {
const loaded = require(fn)
Object.entries(loaded).map(([key, val]) => {
+1 -1
View File
@@ -35,7 +35,7 @@ export default async ({ app, container }) => {
passport.use(
new JWTStrategy(
{
jwtFromRequest: req => req.session.jwt,
jwtFromRequest: (req) => req.session.jwt,
secretOrKey: config.jwtSecret,
},
async (jwtPayload, done) => {
+51 -23
View File
@@ -1,7 +1,6 @@
import glob from "glob"
import { EntitySchema } from "typeorm"
import {
BaseModel,
BaseService,
PaymentService,
FulfillmentService,
@@ -17,6 +16,7 @@ import fs from "fs"
import { asValue, asClass, asFunction, aliasTo } from "awilix"
import { sync as existsSync } from "fs-exists-cached"
import { isTaxCalculationStrategy } from "../interfaces/tax-calculation-strategy"
import formatRegistrationName from "../utils/format-registration-name"
/**
@@ -26,7 +26,7 @@ export default async ({ rootDirectory, container, app, activityId }) => {
const resolved = getResolvedPlugins(rootDirectory)
await Promise.all(
resolved.map(async pluginDetails => {
resolved.map(async (pluginDetails) => {
registerRepositories(pluginDetails, container)
await registerServices(pluginDetails, container)
registerMedusaApi(pluginDetails, container)
@@ -37,7 +37,7 @@ export default async ({ rootDirectory, container, app, activityId }) => {
)
await Promise.all(
resolved.map(async pluginDetails => runLoaders(pluginDetails, container))
resolved.map(async (pluginDetails) => runLoaders(pluginDetails, container))
)
}
@@ -50,7 +50,7 @@ function getResolvedPlugins(rootDirectory) {
const { plugins } = configModule
const resolved = plugins.map(plugin => {
const resolved = plugins.map((plugin) => {
if (_.isString(plugin)) {
return resolvePlugin(plugin)
}
@@ -75,7 +75,7 @@ function getResolvedPlugins(rootDirectory) {
export async function registerPluginModels({ rootDirectory, container }) {
const resolved = getResolvedPlugins(rootDirectory)
await Promise.all(
resolved.map(async pluginDetails => {
resolved.map(async (pluginDetails) => {
registerModels(pluginDetails, container)
})
)
@@ -87,7 +87,7 @@ async function runLoaders(pluginDetails, container) {
{}
)
await Promise.all(
loaderFiles.map(async loader => {
loaderFiles.map(async (loader) => {
try {
const module = require(loader).default
if (typeof module === "function") {
@@ -104,6 +104,34 @@ async function runLoaders(pluginDetails, container) {
function registerMedusaApi(pluginDetails, container) {
registerMedusaMiddleware(pluginDetails, container)
registerStrategies(pluginDetails, container)
}
function registerStrategies(pluginDetails, container) {
let module
try {
const path = `${pluginDetails.resolve}/strategies/tax-calculation`
if (existsSync(path)) {
module = require(path).default
} else {
return
}
} catch (err) {
return
}
if (isTaxCalculationStrategy(module.prototype)) {
container.register({
taxCalculationStrategy: asFunction(
(cradle) => new module(cradle, pluginDetails.options)
).singleton(),
})
} else {
const logger = container.resolve("logger")
logger.warn(
`${pluginDetails.resolve}/strategies/tax-calculation did not export a class that implements ITaxCalculationStrategy. Your Medusa server will still work, but if you have written custom tax calculation logic it will not be used. Make sure to implement the ITaxCalculationStrategy interface.`
)
}
}
function registerMedusaMiddleware(pluginDetails, container) {
@@ -140,7 +168,7 @@ function registerCoreRouters(pluginDetails, container) {
const adminFiles = glob.sync(`${resolve}/api/admin/[!__]*.js`, {})
const storeFiles = glob.sync(`${resolve}/api/store/[!__]*.js`, {})
adminFiles.forEach(fn => {
adminFiles.forEach((fn) => {
const descriptor = fn.split(".")[0]
const splat = descriptor.split("/")
const path = `${splat[splat.length - 2]}/${splat[splat.length - 1]}`
@@ -148,7 +176,7 @@ function registerCoreRouters(pluginDetails, container) {
middlewareService.addRouter(path, loaded())
})
storeFiles.forEach(fn => {
storeFiles.forEach((fn) => {
const descriptor = fn.split(".")[0]
const splat = descriptor.split("/")
const path = `${splat[splat.length - 2]}/${splat[splat.length - 1]}`
@@ -204,7 +232,7 @@ function registerApi(
async function registerServices(pluginDetails, container) {
const files = glob.sync(`${pluginDetails.resolve}/services/[!__]*`, {})
await Promise.all(
files.map(async fn => {
files.map(async (fn) => {
const loaded = require(fn).default
const name = formatRegistrationName(fn)
@@ -219,14 +247,14 @@ async function registerServices(pluginDetails, container) {
// Register our payment providers to paymentProviders
container.registerAdd(
"paymentProviders",
asFunction(cradle => new loaded(cradle, pluginDetails.options))
asFunction((cradle) => new loaded(cradle, pluginDetails.options))
)
// Add the service directly to the container in order to make simple
// resolution if we already know which payment provider we need to use
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
),
[`pp_${loaded.identifier}`]: aliasTo(name),
})
@@ -239,35 +267,35 @@ async function registerServices(pluginDetails, container) {
const name = appDetails.application_name
container.register({
[`${name}Oauth`]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
),
})
} else if (loaded.prototype instanceof FulfillmentService) {
// Register our payment providers to paymentProviders
container.registerAdd(
"fulfillmentProviders",
asFunction(cradle => new loaded(cradle, pluginDetails.options))
asFunction((cradle) => new loaded(cradle, pluginDetails.options))
)
// Add the service directly to the container in order to make simple
// resolution if we already know which fulfillment provider we need to use
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
).singleton(),
[`fp_${loaded.identifier}`]: aliasTo(name),
})
} else if (loaded.prototype instanceof NotificationService) {
container.registerAdd(
"notificationProviders",
asFunction(cradle => new loaded(cradle, pluginDetails.options))
asFunction((cradle) => new loaded(cradle, pluginDetails.options))
)
// Add the service directly to the container in order to make simple
// resolution if we already know which notification provider we need to use
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
).singleton(),
[`noti_${loaded.identifier}`]: aliasTo(name),
})
@@ -276,7 +304,7 @@ async function registerServices(pluginDetails, container) {
// resolution if we already know which file storage provider we need to use
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
),
[`fileService`]: aliasTo(name),
})
@@ -285,14 +313,14 @@ async function registerServices(pluginDetails, container) {
// resolution if we already know which search provider we need to use
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
),
[`searchService`]: aliasTo(name),
})
} else {
container.register({
[name]: asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
),
})
}
@@ -311,13 +339,13 @@ async function registerServices(pluginDetails, container) {
*/
function registerSubscribers(pluginDetails, container) {
const files = glob.sync(`${pluginDetails.resolve}/subscribers/*.js`, {})
files.forEach(fn => {
files.forEach((fn) => {
const loaded = require(fn).default
const name = formatRegistrationName(fn)
container.build(
asFunction(
cradle => new loaded(cradle, pluginDetails.options)
(cradle) => new loaded(cradle, pluginDetails.options)
).singleton()
)
})
@@ -334,7 +362,7 @@ function registerSubscribers(pluginDetails, container) {
*/
function registerRepositories(pluginDetails, container) {
const files = glob.sync(`${pluginDetails.resolve}/repositories/*.js`, {})
files.forEach(fn => {
files.forEach((fn) => {
const loaded = require(fn)
Object.entries(loaded).map(([key, val]) => {
@@ -361,7 +389,7 @@ function registerRepositories(pluginDetails, container) {
*/
function registerModels(pluginDetails, container) {
const files = glob.sync(`${pluginDetails.resolve}/models/*.js`, {})
files.forEach(fn => {
files.forEach((fn) => {
const loaded = require(fn)
Object.entries(loaded).map(([key, val]) => {
+6 -5
View File
@@ -7,20 +7,21 @@ import formatRegistrationName from "../utils/format-registration-name"
/**
* Registers all services in the services directory
*/
export default ({ container, configModule }) => {
const isTest = process.env.NODE_ENV === "test"
export default ({ container, configModule, isTest }) => {
const useMock =
typeof isTest !== "undefined" ? isTest : process.env.NODE_ENV === "test"
const corePath = isTest ? "../services/__mocks__/*.js" : "../services/*.js"
const corePath = useMock ? "../services/__mocks__/*.js" : "../services/*.js"
const coreFull = path.join(__dirname, corePath)
const core = glob.sync(coreFull, { cwd: __dirname })
core.forEach(fn => {
core.forEach((fn) => {
const loaded = require(fn).default
if (loaded) {
const name = formatRegistrationName(fn)
container.register({
[name]: asFunction(
cradle => new loaded(cradle, configModule),
(cradle) => new loaded(cradle, configModule)
).singleton(),
})
}
+37
View File
@@ -0,0 +1,37 @@
import glob from "glob"
import path from "path"
import { AwilixContainer, asFunction } from "awilix"
import formatRegistrationName from "../utils/format-registration-name"
type LoaderOptions = {
container: AwilixContainer
configModule: object
isTest: boolean
}
/**
* Registers all strategies in the strategies directory
* @returns void
*/
export default ({ container, configModule, isTest }: LoaderOptions): void => {
const useMock =
typeof isTest !== "undefined" ? isTest : process.env.NODE_ENV === "test"
const corePath = useMock
? "../strategies/__mocks__/*.js"
: "../strategies/*.js"
const coreFull = path.join(__dirname, corePath)
const core = glob.sync(coreFull, { cwd: __dirname })
core.forEach((fn) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const loaded = require(fn).default
const name = formatRegistrationName(fn)
container.register({
[name]: asFunction(
(cradle) => new loaded(cradle, configModule)
).singleton(),
})
})
}
@@ -0,0 +1,178 @@
import { MigrationInterface, QueryRunner } from "typeorm"
export class newTaxSystem1641636508055 implements MigrationInterface {
name = "newTaxSystem1641636508055"
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "tax_rate" ("id" character varying NOT NULL, "rate" real, "code" character varying, "name" character varying NOT NULL, "region_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_23b71b53f650c0b39e99ccef4fd" PRIMARY KEY ("id"))`
)
await queryRunner.query(
`CREATE TABLE "tax_provider" ("id" character varying NOT NULL, "is_installed" boolean NOT NULL DEFAULT true, CONSTRAINT "PK_b198bf82ba6a317c11763d99b99" PRIMARY KEY ("id"))`
)
await queryRunner.query(
`CREATE TABLE "line_item_tax_line" ("id" character varying NOT NULL, "rate" real NOT NULL, "name" character varying NOT NULL, "code" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "item_id" character varying NOT NULL, CONSTRAINT "PK_4a0f4322fcd5ce4af85727f89a8" PRIMARY KEY ("id"))`
)
await queryRunner.query(
`CREATE INDEX "IDX_5077fa54b0d037e984385dfe8a" ON "line_item_tax_line" ("item_id") `
)
await queryRunner.query(
`CREATE TABLE "shipping_method_tax_line" ("id" character varying NOT NULL, "rate" real NOT NULL, "name" character varying NOT NULL, "code" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "shipping_method_id" character varying NOT NULL, CONSTRAINT "PK_54c94f5908aacbd51cf0a73edb1" PRIMARY KEY ("id"))`
)
await queryRunner.query(
`CREATE INDEX "IDX_926ca9f29014af8091722dede0" ON "shipping_method_tax_line" ("shipping_method_id") `
)
await queryRunner.query(
`CREATE TABLE "product_tax_rate" ("product_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_326257ce468df46cd5c8c5922e9" PRIMARY KEY ("product_id", "rate_id"))`
)
await queryRunner.query(
`CREATE TABLE "product_type_tax_rate" ("product_type_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_ddc9242de1d99bc7674969289f0" PRIMARY KEY ("product_type_id", "rate_id"))`
)
await queryRunner.query(
`CREATE TABLE "shipping_tax_rate" ("shipping_option_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_bcd93b14d7e2695365d383f5eae" PRIMARY KEY ("shipping_option_id", "rate_id"))`
)
await queryRunner.query(
`ALTER TABLE "region" ADD "gift_cards_taxable" boolean NOT NULL DEFAULT true`
)
await queryRunner.query(
`ALTER TABLE "region" ADD "automatic_taxes" boolean NOT NULL DEFAULT true`
)
await queryRunner.query(
`ALTER TABLE "region" ADD "tax_provider_id" character varying`
)
await queryRunner.query(
`ALTER TABLE "line_item" ADD "is_return" boolean NOT NULL DEFAULT false`
)
await queryRunner.query(
`UPDATE "line_item" SET "is_return" = true WHERE "id" IN (SELECT "id" from "line_item" WHERE "metadata"->>'is_return_line' = 'true')`
)
await queryRunner.query(
`ALTER TABLE "order" ALTER COLUMN "tax_rate" DROP NOT NULL`
)
await queryRunner.query(
`CREATE INDEX "IDX_2484cf14c437a04586b07e7ddd" ON "product_tax_rate" ("rate_id") `
)
await queryRunner.query(
`CREATE INDEX "IDX_1d04aebeabb6a89f87e536a124" ON "product_tax_rate" ("product_id") `
)
await queryRunner.query(
`CREATE INDEX "IDX_ece65a774192b34253abc4cd67" ON "product_type_tax_rate" ("rate_id") `
)
await queryRunner.query(
`CREATE INDEX "IDX_25a3138bb236f63d9bb6c8ff11" ON "product_type_tax_rate" ("product_type_id") `
)
await queryRunner.query(
`CREATE INDEX "IDX_346e0016cf045b998074774764" ON "shipping_tax_rate" ("rate_id") `
)
await queryRunner.query(
`CREATE INDEX "IDX_f672727ab020df6c50fb64c1a7" ON "shipping_tax_rate" ("shipping_option_id") `
)
await queryRunner.query(
`ALTER TABLE "tax_rate" ADD CONSTRAINT "FK_b95a1e03b051993d208366cb960" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "region" ADD CONSTRAINT "FK_91f88052197680f9790272aaf5b" FOREIGN KEY ("tax_provider_id") REFERENCES "tax_provider"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "line_item_tax_line" ADD CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "shipping_method_tax_line" ADD CONSTRAINT "FK_926ca9f29014af8091722dede08" FOREIGN KEY ("shipping_method_id") REFERENCES "shipping_method"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "product_tax_rate" ADD CONSTRAINT "FK_1d04aebeabb6a89f87e536a124d" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "product_tax_rate" ADD CONSTRAINT "FK_2484cf14c437a04586b07e7dddb" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "product_type_tax_rate" ADD CONSTRAINT "FK_25a3138bb236f63d9bb6c8ff111" FOREIGN KEY ("product_type_id") REFERENCES "product_type"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "product_type_tax_rate" ADD CONSTRAINT "FK_ece65a774192b34253abc4cd672" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "shipping_tax_rate" ADD CONSTRAINT "FK_f672727ab020df6c50fb64c1a70" FOREIGN KEY ("shipping_option_id") REFERENCES "shipping_option"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
await queryRunner.query(
`ALTER TABLE "shipping_tax_rate" ADD CONSTRAINT "FK_346e0016cf045b9980747747645" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "shipping_tax_rate" DROP CONSTRAINT "FK_346e0016cf045b9980747747645"`
)
await queryRunner.query(
`ALTER TABLE "shipping_tax_rate" DROP CONSTRAINT "FK_f672727ab020df6c50fb64c1a70"`
)
await queryRunner.query(
`ALTER TABLE "product_type_tax_rate" DROP CONSTRAINT "FK_ece65a774192b34253abc4cd672"`
)
await queryRunner.query(
`ALTER TABLE "product_type_tax_rate" DROP CONSTRAINT "FK_25a3138bb236f63d9bb6c8ff111"`
)
await queryRunner.query(
`ALTER TABLE "product_tax_rate" DROP CONSTRAINT "FK_2484cf14c437a04586b07e7dddb"`
)
await queryRunner.query(
`ALTER TABLE "product_tax_rate" DROP CONSTRAINT "FK_1d04aebeabb6a89f87e536a124d"`
)
await queryRunner.query(
`ALTER TABLE "shipping_method_tax_line" DROP CONSTRAINT "FK_926ca9f29014af8091722dede08"`
)
await queryRunner.query(
`ALTER TABLE "line_item_tax_line" DROP CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad"`
)
await queryRunner.query(
`ALTER TABLE "region" DROP CONSTRAINT "FK_91f88052197680f9790272aaf5b"`
)
await queryRunner.query(
`ALTER TABLE "tax_rate" DROP CONSTRAINT "FK_b95a1e03b051993d208366cb960"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_f672727ab020df6c50fb64c1a7"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_346e0016cf045b998074774764"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_25a3138bb236f63d9bb6c8ff11"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_ece65a774192b34253abc4cd67"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_1d04aebeabb6a89f87e536a124"`
)
await queryRunner.query(
`DROP INDEX "public"."IDX_2484cf14c437a04586b07e7ddd"`
)
await queryRunner.query(
`ALTER TABLE "order" ALTER COLUMN "tax_rate" SET NOT NULL`
)
await queryRunner.query(`ALTER TABLE "line_item" DROP COLUMN "is_return"`)
await queryRunner.query(
`ALTER TABLE "region" DROP COLUMN "tax_provider_id"`
)
await queryRunner.query(
`ALTER TABLE "region" DROP COLUMN "automatic_taxes"`
)
await queryRunner.query(
`ALTER TABLE "region" DROP COLUMN "gift_cards_taxable"`
)
await queryRunner.query(`DROP TABLE "shipping_tax_rate"`)
await queryRunner.query(`DROP TABLE "product_type_tax_rate"`)
await queryRunner.query(`DROP TABLE "product_tax_rate"`)
await queryRunner.query(
`DROP INDEX "public"."IDX_926ca9f29014af8091722dede0"`
)
await queryRunner.query(`DROP TABLE "shipping_method_tax_line"`)
await queryRunner.query(
`DROP INDEX "public"."IDX_5077fa54b0d037e984385dfe8a"`
)
await queryRunner.query(`DROP TABLE "line_item_tax_line"`)
await queryRunner.query(`DROP TABLE "tax_provider"`)
await queryRunner.query(`DROP TABLE "tax_rate"`)
}
}
+3 -1
View File
@@ -124,6 +124,8 @@ export class Cart {
@PrimaryColumn()
id: string
readonly object = "cart"
@Column({ nullable: true })
email: string
@@ -245,7 +247,7 @@ export class Cart {
shipping_total?: number
discount_total?: number
tax_total?: number
tax_total?: number | null
refunded_total?: number
total?: number
subtotal?: number
@@ -0,0 +1,30 @@
import {
Entity,
BeforeInsert,
Index,
Column,
ManyToOne,
JoinColumn,
} from "typeorm"
import { ulid } from "ulid"
import { TaxLine } from "./tax-line"
import { LineItem } from "./line-item"
@Entity()
export class LineItemTaxLine extends TaxLine {
@Index()
@Column()
item_id: string
@ManyToOne(() => LineItem, (li) => li.tax_lines)
@JoinColumn({ name: "item_id" })
item: LineItem
@BeforeInsert()
private beforeInsert() {
if (this.id) return
const id = ulid()
this.id = `litl_${id}`
}
}
+12 -16
View File
@@ -1,5 +1,6 @@
import {
Entity,
OneToMany,
BeforeInsert,
CreateDateColumn,
UpdateDateColumn,
@@ -13,6 +14,7 @@ import {
import { ulid } from "ulid"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { LineItemTaxLine } from "./line-item-tax-line"
import { Swap } from "./swap"
import { Cart } from "./cart"
import { Order } from "./order"
@@ -32,10 +34,7 @@ export class LineItem {
@Column({ nullable: true })
cart_id: string
@ManyToOne(
() => Cart,
cart => cart.items
)
@ManyToOne(() => Cart, (cart) => cart.items)
@JoinColumn({ name: "cart_id" })
cart: Cart
@@ -43,10 +42,7 @@ export class LineItem {
@Column({ nullable: true })
order_id: string
@ManyToOne(
() => Order,
order => order.items
)
@ManyToOne(() => Order, (order) => order.items)
@JoinColumn({ name: "order_id" })
order: Order
@@ -54,10 +50,7 @@ export class LineItem {
@Column({ nullable: true })
swap_id: string
@ManyToOne(
() => Swap,
swap => swap.additional_items
)
@ManyToOne(() => Swap, (swap) => swap.additional_items)
@JoinColumn({ name: "swap_id" })
swap: Swap
@@ -65,13 +58,13 @@ export class LineItem {
@Column({ nullable: true })
claim_order_id: string
@ManyToOne(
() => ClaimOrder,
co => co.additional_items
)
@ManyToOne(() => ClaimOrder, (co) => co.additional_items)
@JoinColumn({ name: "claim_order_id" })
claim_order: ClaimOrder
@OneToMany(() => LineItemTaxLine, (tl) => tl.item, { cascade: ["insert"] })
tax_lines: LineItemTaxLine[]
@Column()
title: string
@@ -81,6 +74,9 @@ export class LineItem {
@Column({ nullable: true })
thumbnail: string
@Column({ default: false })
is_return: boolean
@Column({ default: false })
is_giftcard: boolean
+19 -52
View File
@@ -74,6 +74,8 @@ export class Order {
@PrimaryColumn()
id: string
readonly object = "order"
@DbAwareColumn({ type: "enum", enum: OrderStatus, default: "pending" })
status: OrderStatus
@@ -142,8 +144,8 @@ export class Order {
@JoinColumn({ name: "currency_code", referencedColumnName: "code" })
currency: Currency
@Column({ type: "real" })
tax_rate: number
@Column({ type: "real", nullable: true })
tax_rate: number | null
@ManyToMany(() => Discount, { cascade: ["insert"] })
@JoinTable({
@@ -173,57 +175,29 @@ export class Order {
})
gift_cards: GiftCard[]
@OneToMany(
() => ShippingMethod,
(method) => method.order,
{
cascade: ["insert"],
}
)
@OneToMany(() => ShippingMethod, (method) => method.order, {
cascade: ["insert"],
})
shipping_methods: ShippingMethod[]
@OneToMany(
() => Payment,
(payment) => payment.order,
{ cascade: ["insert"] }
)
@OneToMany(() => Payment, (payment) => payment.order, { cascade: ["insert"] })
payments: Payment[]
@OneToMany(
() => Fulfillment,
(fulfillment) => fulfillment.order,
{
cascade: ["insert"],
}
)
@OneToMany(() => Fulfillment, (fulfillment) => fulfillment.order, {
cascade: ["insert"],
})
fulfillments: Fulfillment[]
@OneToMany(
() => Return,
(ret) => ret.order,
{ cascade: ["insert"] }
)
@OneToMany(() => Return, (ret) => ret.order, { cascade: ["insert"] })
returns: Return[]
@OneToMany(
() => ClaimOrder,
(co) => co.order,
{ cascade: ["insert"] }
)
@OneToMany(() => ClaimOrder, (co) => co.order, { cascade: ["insert"] })
claims: ClaimOrder[]
@OneToMany(
() => Refund,
(ref) => ref.order,
{ cascade: ["insert"] }
)
@OneToMany(() => Refund, (ref) => ref.order, { cascade: ["insert"] })
refunds: Refund[]
@OneToMany(
() => Swap,
(swap) => swap.order,
{ cascade: ["insert"] }
)
@OneToMany(() => Swap, (swap) => swap.order, { cascade: ["insert"] })
swaps: Swap[]
@Column({ nullable: true })
@@ -233,19 +207,12 @@ export class Order {
@JoinColumn({ name: "draft_order_id" })
draft_order: DraftOrder
@OneToMany(
() => LineItem,
(lineItem) => lineItem.order,
{
cascade: ["insert"],
}
)
@OneToMany(() => LineItem, (lineItem) => lineItem.order, {
cascade: ["insert"],
})
items: LineItem[]
@OneToMany(
() => GiftCardTransaction,
(gc) => gc.order
)
@OneToMany(() => GiftCardTransaction, (gc) => gc.order)
gift_card_transactions: GiftCardTransaction[]
@Column({ nullable: true, type: resolveDbType("timestamptz") })
@@ -0,0 +1,69 @@
import {
Entity,
DeleteDateColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
PrimaryColumn,
} from "typeorm"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { Product } from "./product"
import { TaxRate } from "./tax-rate"
@Entity()
export class ProductTaxRate {
@PrimaryColumn()
product_id: string
@PrimaryColumn()
rate_id: string
@ManyToOne(() => Product, { onDelete: "CASCADE" })
@JoinColumn({ name: "product_id" })
product?: Product
// Note the onDelete config here
@ManyToOne(() => TaxRate, { onDelete: "CASCADE" })
@JoinColumn({ name: "rate_id" })
tax_rate?: TaxRate
@CreateDateColumn({ type: resolveDbType("timestamptz") })
created_at: Date
@UpdateDateColumn({ type: resolveDbType("timestamptz") })
updated_at: Date
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: any
}
/**
* @schema product_tax_rate
* title: "Product Tax Rate"
* description: "Associates a tax rate with a product to indicate that the product is taxed in a certain way"
* x-resourceId: product_tax_rate
* properties:
* product_id:
* description: "The id of the Product"
* type: string
* rate_id:
* description: "The id of the Tax Rate"
* type: string
* created_at:
* description: "The date with timezone at which the resource was created."
* type: string
* format: date-time
* updated_at:
* description: "The date with timezone at which the resource was last updated."
* type: string
* format: date-time
* deleted_at:
* description: "The date with timezone at which the resource was deleted."
* type: string
* format: date-time
* metadata:
* description: "An optional key-value map with additional information."
* type: object
*/
@@ -0,0 +1,68 @@
import {
Entity,
DeleteDateColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
PrimaryColumn,
} from "typeorm"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { ProductType } from "./product-type"
import { TaxRate } from "./tax-rate"
@Entity()
export class ProductTypeTaxRate {
@PrimaryColumn()
product_type_id: string
@PrimaryColumn()
rate_id: string
@ManyToOne(() => ProductType, { onDelete: "CASCADE" })
@JoinColumn({ name: "product_type_id" })
product_type?: ProductType
@ManyToOne(() => TaxRate, { onDelete: "CASCADE" })
@JoinColumn({ name: "rate_id" })
tax_rate?: TaxRate
@CreateDateColumn({ type: resolveDbType("timestamptz") })
created_at: Date
@UpdateDateColumn({ type: resolveDbType("timestamptz") })
updated_at: Date
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: any
}
/**
* @schema product_type_tax_rate
* title: "Product Type Tax Rate"
* description: "Associates a tax rate with a product type to indicate that the product type is taxed in a certain way"
* x-resourceId: product_type_tax_rate
* properties:
* product_type_id:
* description: "The id of the Product type"
* type: string
* rate_id:
* description: "The id of the Tax Rate"
* type: string
* created_at:
* description: "The date with timezone at which the resource was created."
* type: string
* format: date-time
* updated_at:
* description: "The date with timezone at which the resource was last updated."
* type: string
* format: date-time
* deleted_at:
* description: "The date with timezone at which the resource was deleted."
* type: string
* format: date-time
* metadata:
* description: "An optional key-value map with additional information."
* type: object
*/
+27 -6
View File
@@ -16,9 +16,11 @@ import { ulid } from "ulid"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { Currency } from "./currency"
import { TaxRate } from "./tax-rate"
import { Country } from "./country"
import { PaymentProvider } from "./payment-provider"
import { FulfillmentProvider } from "./fulfillment-provider"
import { TaxProvider } from "./tax-provider"
@Entity()
export class Region {
@@ -38,16 +40,32 @@ export class Region {
@Column({ type: "real" })
tax_rate: number
@OneToMany(() => TaxRate, (tr) => tr.region)
tax_rates: TaxRate[] | null
@Column({ nullable: true })
tax_code: string
@OneToMany(
() => Country,
c => c.region
)
@Column({ default: true })
gift_cards_taxable: boolean
@Column({ default: true })
automatic_taxes: boolean
@OneToMany(() => Country, (c) => c.region)
countries: Country[]
@ManyToMany(() => PaymentProvider, { eager: true, cascade: ['insert', 'update'] })
@Column({ type: "text", nullable: true })
tax_provider_id: string | null
@ManyToOne(() => TaxProvider)
@JoinColumn({ name: "tax_provider_id" })
tax_provider: TaxProvider
@ManyToMany(() => PaymentProvider, {
eager: true,
cascade: ["insert", "update"],
})
@JoinTable({
name: "region_payment_providers",
joinColumn: {
@@ -61,7 +79,10 @@ export class Region {
})
payment_providers: PaymentProvider[]
@ManyToMany(() => FulfillmentProvider, { eager: true, cascade: ['insert', 'update'] })
@ManyToMany(() => FulfillmentProvider, {
eager: true,
cascade: ["insert", "update"],
})
@JoinTable({
name: "region_fulfillment_providers",
joinColumn: {
@@ -0,0 +1,30 @@
import {
Entity,
BeforeInsert,
Index,
Column,
ManyToOne,
JoinColumn,
} from "typeorm"
import { ulid } from "ulid"
import { TaxLine } from "./tax-line"
import { ShippingMethod } from "./shipping-method"
@Entity()
export class ShippingMethodTaxLine extends TaxLine {
@Index()
@Column()
shipping_method_id: string
@ManyToOne(() => ShippingMethod, (sm) => sm.tax_lines)
@JoinColumn({ name: "shipping_method_id" })
shipping_method: ShippingMethod
@BeforeInsert()
private beforeInsert() {
if (this.id) return
const id = ulid()
this.id = `smtl_${id}`
}
}
@@ -6,6 +6,7 @@ import {
PrimaryColumn,
ManyToOne,
OneToOne,
OneToMany,
JoinColumn,
Index,
} from "typeorm"
@@ -18,6 +19,7 @@ import { Cart } from "./cart"
import { Swap } from "./swap"
import { Return } from "./return"
import { ShippingOption } from "./shipping-option"
import { ShippingMethodTaxLine } from "./shipping-method-tax-line"
@Check(
`"claim_order_id" IS NOT NULL OR "order_id" IS NOT NULL OR "cart_id" IS NOT NULL OR "swap_id" IS NOT NULL OR "return_id" IS NOT NULL`
@@ -68,10 +70,7 @@ export class ShippingMethod {
@Column({ nullable: true })
return_id: string
@OneToOne(
() => Return,
ret => ret.shipping_method
)
@OneToOne(() => Return, (ret) => ret.shipping_method)
@JoinColumn({ name: "return_id" })
return_order: Return
@@ -79,6 +78,11 @@ export class ShippingMethod {
@JoinColumn({ name: "shipping_option_id" })
shipping_option: ShippingOption
@OneToMany(() => ShippingMethodTaxLine, (tl) => tl.shipping_method, {
cascade: ["insert"],
})
tax_lines: ShippingMethodTaxLine[]
@Column({ type: "int" })
price: number
@@ -0,0 +1,68 @@
import {
Entity,
DeleteDateColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
PrimaryColumn,
} from "typeorm"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { ShippingOption } from "./shipping-option"
import { TaxRate } from "./tax-rate"
@Entity()
export class ShippingTaxRate {
@PrimaryColumn()
shipping_option_id: string
@PrimaryColumn()
rate_id: string
@ManyToOne(() => ShippingOption, { onDelete: "CASCADE" })
@JoinColumn({ name: "shipping_option_id" })
shipping_option?: ShippingOption
@ManyToOne(() => TaxRate, { onDelete: "CASCADE" })
@JoinColumn({ name: "rate_id" })
tax_rate?: TaxRate
@CreateDateColumn({ type: resolveDbType("timestamptz") })
created_at: Date
@UpdateDateColumn({ type: resolveDbType("timestamptz") })
updated_at: Date
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: any
}
/**
* @schema shipping_tax_rate
* title: "Shipping Tax Rate"
* description: "Associates a tax rate with a shipping option to indicate that the shipping option is taxed in a certain way"
* x-resourceId: shipping_tax_rate
* properties:
* shipping_option_id:
* description: "The id of the Shipping Option"
* type: string
* rate_id:
* description: "The id of the Tax Rate"
* type: string
* created_at:
* description: "The date with timezone at which the resource was created."
* type: string
* format: date-time
* updated_at:
* description: "The date with timezone at which the resource was last updated."
* type: string
* format: date-time
* deleted_at:
* description: "The date with timezone at which the resource was deleted."
* type: string
* format: date-time
* metadata:
* description: "An optional key-value map with additional information."
* type: object
*/
+7 -7
View File
@@ -63,35 +63,35 @@ export class Swap {
@ManyToOne(
() => Order,
o => o.swaps
(o) => o.swaps
)
@JoinColumn({ name: "order_id" })
order: Order
@OneToMany(
() => LineItem,
item => item.swap,
(item) => item.swap,
{ cascade: ["insert"] }
)
additional_items: LineItem
additional_items: LineItem[]
@OneToOne(
() => Return,
ret => ret.swap,
(ret) => ret.swap,
{ cascade: ["insert"] }
)
return_order: Return
@OneToMany(
() => Fulfillment,
fulfillment => fulfillment.swap,
(fulfillment) => fulfillment.swap,
{ cascade: ["insert"] }
)
fulfillments: Fulfillment[]
@OneToOne(
() => Payment,
p => p.swap,
(p) => p.swap,
{ cascade: ["insert"] }
)
payment: Payment
@@ -108,7 +108,7 @@ export class Swap {
@OneToMany(
() => ShippingMethod,
method => method.swap,
(method) => method.swap,
{ cascade: ["insert"] }
)
shipping_methods: ShippingMethod[]
+61
View File
@@ -0,0 +1,61 @@
import {
CreateDateColumn,
UpdateDateColumn,
Column,
PrimaryColumn,
} from "typeorm"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
export class TaxLine {
@PrimaryColumn()
id: string
@Column({ type: "real" })
rate: number
@Column()
name: string
@Column({ type: "varchar", nullable: true })
code: string | null
@CreateDateColumn({ type: resolveDbType("timestamptz") })
created_at: Date
@UpdateDateColumn({ type: resolveDbType("timestamptz") })
updated_at: Date
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: any
}
/**
* @schema tax_line
* title: "Tax Line"
* description: "Line item that specifies an amount of tax to add to a line item."
* x-resourceId: tax_line
* properties:
* id:
* description: "The id of the Tax Line. This value will be prefixed by `tl_`."
* type: string
* code:
* description: "A code to identify the tax type by"
* type: string
* name:
* description: "A human friendly name for the tax"
* type: string
* rate:
* description: "The numeric rate to charge tax by"
* type: number
* created_at:
* description: "The date with timezone at which the resource was created."
* type: string
* format: date-time
* updated_at:
* description: "The date with timezone at which the resource was last updated."
* type: string
* format: date-time
* metadata:
* description: "An optional key-value map with additional information."
* type: object
*/
@@ -0,0 +1,24 @@
import { Entity, Column, PrimaryColumn } from "typeorm"
@Entity()
export class TaxProvider {
@PrimaryColumn()
id: string
@Column({ default: true })
is_installed: boolean
}
/**
* @schema tax_provider
* title: "Tax Provider"
* description: "The tax service used to calculate taxes"
* x-resourceId: tax_provider
* properties:
* id:
* description: "The id of the tax provider as given by the plugin."
* type: string
* is_installed:
* description: "Whether the plugin is installed in the current version. Plugins that are no longer installed are not deleted by will have this field set to `false`."
* type: boolean
*/
+141
View File
@@ -0,0 +1,141 @@
import {
Entity,
BeforeInsert,
CreateDateColumn,
UpdateDateColumn,
Column,
PrimaryColumn,
ManyToOne,
ManyToMany,
JoinColumn,
JoinTable,
} from "typeorm"
import { ulid } from "ulid"
import { resolveDbType, DbAwareColumn } from "../utils/db-aware-column"
import { Region } from "./region"
import { Product } from "./product"
import { ProductType } from "./product-type"
import { ShippingOption } from "./shipping-option"
@Entity()
export class TaxRate {
@PrimaryColumn()
id: string
@Column({ type: "real", nullable: true })
rate: number | null
@Column({ type: "varchar", nullable: true })
code: string | null
@Column()
name: string
@Column()
region_id: string
@ManyToOne(() => Region)
@JoinColumn({ name: "region_id" })
region: Region
@CreateDateColumn({ type: resolveDbType("timestamptz") })
created_at: Date
@UpdateDateColumn({ type: resolveDbType("timestamptz") })
updated_at: Date
@DbAwareColumn({ type: "jsonb", nullable: true })
metadata: any
@ManyToMany(() => Product)
@JoinTable({
name: "product_tax_rate",
joinColumn: {
name: "rate_id",
referencedColumnName: "id",
},
inverseJoinColumn: {
name: "product_id",
referencedColumnName: "id",
},
})
products: Product[]
@ManyToMany(() => ProductType)
@JoinTable({
name: "product_type_tax_rate",
joinColumn: {
name: "rate_id",
referencedColumnName: "id",
},
inverseJoinColumn: {
name: "product_type_id",
referencedColumnName: "id",
},
})
product_types: ProductType[]
@ManyToMany(() => ShippingOption)
@JoinTable({
name: "shipping_tax_rate",
joinColumn: {
name: "rate_id",
referencedColumnName: "id",
},
inverseJoinColumn: {
name: "shipping_option_id",
referencedColumnName: "id",
},
})
shipping_options: ShippingOption[]
// TODO: consider custom DTO instead
product_count?: number
product_type_count?: number
shipping_option_count?: number
@BeforeInsert()
private beforeInsert() {
if (this.id) return
const id = ulid()
this.id = `txr_${id}`
}
}
/**
* @schema tax_rate
* title: "Tax Rate"
* description: "A Tax Rate can be used to associate a certain rate to charge on products within a given Region"
* x-resourceId: line_item
* properties:
* id:
* description: "The id of the Tax Rate. This value will be prefixed by `txr_`."
* type: string
* rate:
* description: "The numeric rate to charge"
* type: number
* code:
* description: "A code to identify the tax type by"
* type: string
* name:
* description: "A human friendly name for the tax"
* type: string
* region_id:
* description: "The id of the Region that the rate belongs to"
* type: string
* created_at:
* description: "The date with timezone at which the resource was created."
* type: string
* format: date-time
* updated_at:
* description: "The date with timezone at which the resource was last updated."
* type: string
* format: date-time
* metadata:
* description: "An optional key-value map with additional information."
* type: object
* refundable:
* description: "The amount that can be refunded from the given Line Item. Takes taxes and discounts into consideration."
* type: integer
*/
@@ -0,0 +1,5 @@
import { EntityRepository, Repository } from "typeorm"
import { LineItemTaxLine } from "../models/line-item-tax-line"
@EntityRepository(LineItemTaxLine)
export class LineItemTaxLineRepository extends Repository<LineItemTaxLine> {}
+26 -1
View File
@@ -1,5 +1,30 @@
import { EntityRepository, Repository } from "typeorm"
import { LineItem } from "../models/line-item"
import { ReturnItem } from "../models/return-item"
@EntityRepository(LineItem)
export class LineItemRepository extends Repository<LineItem> {}
export class LineItemRepository extends Repository<LineItem> {
/**
* Finds line items that are to be returned as part of the Return represented
* by `returnId`. The function joins the associated ReturnItem and the
* LineItem's TaxLines.
* @param returnId - the id of the Return to get LineItems by
* @return the LineItems associated with the Return with its ReturnItem joined
* and mapped to `return_item`.
*/
async findByReturn(
returnId: string
): Promise<(LineItem & { return_item: ReturnItem })[]> {
const qb = this.createQueryBuilder("li")
.leftJoinAndSelect(`li.tax_lines`, "tax_lines")
.leftJoinAndMapOne(
`li.return_item`,
ReturnItem,
`ri`,
`ri.item_id = li.id`
)
.where(`ri.return_id = :returnId`, { returnId })
return (await qb.getMany()) as (LineItem & { return_item: ReturnItem })[]
}
}
@@ -0,0 +1,5 @@
import { EntityRepository, Repository } from "typeorm"
import { ProductTaxRate } from "../models/product-tax-rate"
@EntityRepository(ProductTaxRate)
export class ProductTaxRateRepository extends Repository<ProductTaxRate> {}
@@ -0,0 +1,5 @@
import { EntityRepository, Repository } from "typeorm"
import { ShippingMethodTaxLine } from "../models/shipping-method-tax-line"
@EntityRepository(ShippingMethodTaxLine)
export class ShippingMethodTaxLineRepository extends Repository<ShippingMethodTaxLine> {}
@@ -0,0 +1,5 @@
import { EntityRepository, Repository } from "typeorm"
import { ShippingTaxRate } from "../models/shipping-tax-rate"
@EntityRepository(ShippingTaxRate)
export class ShippingTaxRateRepository extends Repository<ShippingTaxRate> {}
Loaded 100 of 223 files, more files were not shown because too many files have changed in this diff. Show more