Merge branch 'master' into docs/segment-integration

This commit is contained in:
Shahed Nasser authored and GitHub committed 2022-06-10 17:20:07 +03:00
commit 98e61b8b20
346 files changed
+32743 -8411

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
name: Generate References
on:
push:
branches:
- 'master'
paths:
- packages/medusa/src/services/**
jobs:
services:
runs-on: ubuntu-latest
steps:
- name: Cancel Previous Runs
uses: styfle/cancel-workflow-action@0.9.1
with:
access_token: ${{ github.token }}
- name: Checkout
uses: actions/checkout@v2.3.5
with:
fetch-depth: 0
- name: Setup Node.js environment
uses: actions/setup-node@v2.4.1
with:
node-version: "14"
cache: "yarn"
- name: Bootstrap packages
uses: ./.github/actions/cache-bootstrap
with:
extension: unit-tests
- name: Build Packages
run: yarn build
- name: Generate Services Reference
run: yarn generate:services
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Automatically Generated Services Reference
file_pattern: docs/content/*
skip_dirty_check: false
+5
View File
@@ -0,0 +1,5 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
yarn-path ".yarn/releases/yarn-1.19.0.cjs"
+3819 -585
View File
File diff suppressed because it is too large. Load diff
+1126 -1047
View File
File diff suppressed because it is too large. Load diff
+677 -667
View File
File diff suppressed because it is too large. Load diff
+707 -699
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -7,7 +7,7 @@ routes:
path: /products/:id
route: /products
description: >
A product represents the object, that is to be sold on the website. A product can have variants, that differ by e.g. size and color.
A product represents the object, that are to be sold on the website. A product can have variants, that differ by e.g. size and color.
endpoints:
- path: /:id
method: GET
+1 -1
View File
@@ -57,7 +57,7 @@ And that's all! You've now enabled Algolia for your Medusa store engine. The plu
**Usage**
This article will not go too much into depth about how the search functionality works under the hood when querying the API. We refer to the [previous article on MeiliSearch](https://www.medusajs.com/post/meilisearch-and-medusa) if this is of your interest. In there, you will find a quick showcase using Postman as well as a thorough walkthrough of how you can display the results in your storefront using ReactJS (GatsbyJS).
This article will not go too much into depth about how the search functionality works under the hood when querying the API. We refer to the [previous article on MeiliSearch](https://medusajs.com/blog/meilisearch-medusa) if this is of your interest. In there, you will find a quick showcase using Postman as well as a thorough walkthrough of how you can display the results in your storefront using ReactJS (GatsbyJS).
Instead, to illustrate the power of our Search API and search engine plugins, we'll switch out a MeiliSearch plugin with our new Algolia plugin in a store with existing products. Upon restarting the server with the new configuration, your products will automatically be fed into Algolia and the search functionality in your frontend will remain unchanged.
+108 -27
View File
@@ -1,57 +1,138 @@
# MinIO
In order to work with images in Medusa, you need a file service plugin responsible for hosting. Following this guide will allow you to upload images to MinIO bucket.
This document will guide you through installing the MinIO file service plugin on your Medusa server.
### Before you start
## Overview
At this point, you should have an instance of our store engine running. If not, we have a [full guide](https://docs.medusajs.com/tutorial/set-up-your-development-environment) for setting up your local environment.
To manage images in Medusa, you need a file service plugin responsible for hosting. Without a file service plugin, you will face issues while working with Medusa, such as when uploading images for products.
### Set up MinIO
Medusa provides three different options to handle your file storage. This document will focus on setting up [MinIO](https://min.io) on your local machine and connecting Medusa to it.
#### Create an MinIO bucket
## Prerequisites
In the MinIO console create a new bucket, then click into that bucket and change the `Access Policy` to `public`.
A Medusa server is required to be set up before following along with this document. You can follow the [quickstart guide](../quickstart/quick-start.md) to get started in minutes.
Be aware, that this will allow for anyone to acces your bucket. Avoid storing sensitive data.
## Set up MinIO
#### Generate access keys
You can follow [MinIO’s guide to install it](https://docs.min.io/minio/baremetal/quickstart/quickstart.html) on your machine based on your operating system.
Navigate to users and perform the following steps:
After installing it, make sure MinIO is always running when your Medusa server is running. It’s recommended that you set up an alias to quickly start the MinIO server as instructed at the end of the installation guides in MinIO.
- Enter new `Access Key` and `Secret Key`
- Select readwrite policy
- Submit the details
:::warning
### Installation
In MinIO’s documentation, port `9000` is used for the address of the MinIO server. However, this collides with the port for the Medusa server. You must change the port for MinIO to another one (for example, port `9001`).
First, install the plugin using your preferred package manager:
:::
```bash npm2yarn
### Create a MinIO bucket
After installing MinIO and logging into the Console, click on “Create Bucket” to create a new bucket that will store the files of your Medusa server.
![Create Bucket](https://i.imgur.com/PwLldKt.png)
Then, in the form, enter a name for the bucket and click on Create Bucket. By MinIO’s requirement, the name can only consist of lower case characters, numbers, dots (`.`), and hyphens (`-`).
![Bucket Info](https://i.imgur.com/UB477rl.png)
After creating the bucket, click on the cog icon at the top right to configure the bucket.
![Configure Bucket](https://i.imgur.com/0pB8RIM.png)
Then, click on the edit icon next to Access Policy. This will open a pop-up.
![Access Policy](https://i.imgur.com/qo3QQz4.png)
In the pop-up, change the selected value to “public” and click Set.
:::warning
Changing the Access Policy to public will allow anyone to access your bucket. Avoid storing sensitive data in the bucket.
:::
### Generate Access Keys
From the sidebar of your MinIO console, click on Identity then Service Accounts.
![Service Accounts Sidebar](https://i.imgur.com/CkTbrEc.png)
Then, click on Create Service Account.
![Create Service Account](https://i.imgur.com/a000HQf.png)
This will generate a random Access Key and Secret Key for you.
![Generated Keys](https://i.imgur.com/my4c7zU.png)
Click on Create. A pop-up will then show the value for your Access Key and Secret Key. Copy them to use in the next section.
:::caution
You will not be able to access the Secret Key after closing the pop-up. So, make sure to store it somewhere to use later when configuring the plugin.
:::
## Plugin Installation
In the directory of your Medusa server, run the following command to install the MinIO plugin:
```bash
npm install medusa-file-minio
```
Then configure your `medusa-config.js` to include the plugin alongside the required options:
Then, add the following environment variables in `.env`:
```=javascript
```bash
MINIO_ENDPOINT=<ENDPOINT>
MINIO_BUCKET=<BUCKET>
MINIO_ACCESS_KEY=<ACCESS_KEY>
MINIO_SECRET_KEY=<SECRET_KEY>
```
Where `<ENDPOINT>` is the URL of your MinIO server, `<BUCKET>` is the name of the bucket you created earlier, and `<ACCESS_KEY>` and `<SECRET_KEY>` are the keys you generated in the previous section.
Finally, configure your `medusa-config.js` to include the plugin with the required options:
```bash
{
resolve: `medusa-file-minio`,
options: {
endpoint: "minio.server.com",
bucket: "test",
access_key_id: "YOUR-ACCESS-KEY",
secret_access_key: "YOUR-SECRET-KEY",
endpoint: process.env.MINIO_ENDPOINT,
bucket: process.env.MINIO_BUCKET,
access_key_id: process.env.MINIO_ACCESS_KEY,
secret_access_key: process.env.MINIO_SECRET_KEY,
},
},
```
The two access keys in the options are the ones created in the previous section.
## Test it Out
:::tip
Run your Medusa server alongside the [Medusa Admin](../admin/quickstart.md) to try out your new file service. Upon editing or creating products, you can now upload thumbnails and images, that are stored in a MinIO server.
Make sure to use an environment variable for the secret key in a live environment.
![Image Uploaded on Admin](https://i.imgur.com/alabX2i.png)
:::
## Next.js Storefront Configuration
### Try it out
If you’re using a [Next.js](../starters/nextjs-medusa-starter.md) storefront, you need to add an additional configuration that adds the MinIO domain name into the configured images domain names. This is because all URLs of product images will be from the MinIO server.
Finally, run your Medusa server alongside our admin system to try out your new file service. Upon editing or creating products, you can now upload thumbnails and images, that are stored in an MinIO server.
If this configuration is not added, you’ll receive the error ["next/image Un-configured Host”](https://nextjs.org/docs/messages/next-image-unconfigured-host).
In `next.config.js` add the following option in the exported object:
```jsx
module.exports = {
//other options
images: {
domains: [
"127.0.0.1",
//any other domains...
],
},
}
```
Where `127.0.0.1` is the domain of your local MinIO server.
## What’s Next 🚀
- Check out [more plugins](https://github.com/medusajs/medusa/tree/master/packages) you can add to your store.
+1 -1
View File
@@ -24,7 +24,7 @@ By integrating SendGrid with Medusa, you’ll be sending email notifications to
Before going further with this guide make sure you have a Medusa server set up. You can follow our [Quickstart guide](../quickstart/quick-start.md).
You also must have [Redis configured on your Medusa server](../tutorial/0-set-up-your-development-environment.md). Sending emails is done through Subscribers, which uses Redis as the event queue. If you don’t set up Redis, the plugin will not send emails.
You also must have [Redis configured on your Medusa server](/tutorial/set-up-your-development-environment#redis). Sending emails is done through Subscribers, which uses Redis as the event queue. If you don’t set up Redis, the plugin will not send emails.
## Create a SendGrid Account
+4 -4
View File
@@ -48,8 +48,8 @@ const plugins = [
{
resolve: `medusa-payment-stripe`,
options: {
api_key: STRIPE_API_KEY,
webhook_secret: STRIPE_WEBHOOK_SECRET,
api_key: process.env.STRIPE_API_KEY,
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
},
},
];
@@ -57,7 +57,7 @@ const plugins = [
:::note
You might find that this code is already available but commented out. You can proceed with removing the comments instead of adding the code again.
You might find that this code is already available but commented out. You can proceed with removing the comments instead of adding the code again, but make sure to replace `STRIPE_API_KEY` and `STRIPE_WEBHOOK_SECRET` with `process.env.STRIPE_API_KEY` and `process.env.STRIPE_WEBHOOK_SECRET` respectively.
:::
@@ -131,7 +131,7 @@ All storefronts require that you obtain your Stripe’s Publishable Key. You can
Medusa has a Next.js storefront that you can easily use with your Medusa server. If you don’t have the storefront installed, you can follow [this quickstart guide](../starters/nextjs-medusa-starter).
In your `.env` file, add the following variable with its value set to the Publishable Key:
In your `.env.local` file (or the file you’re using for your environment variables), add the following variable with its value set to the Publishable Key:
```jsx
NEXT_PUBLIC_STRIPE_KEY=pk_...
+1 -1
View File
@@ -66,7 +66,7 @@ In this example, you’ll create a subscriber that listens to the `order.placed`
:::tip
For this example to work, you’ll need to install and configure Redis on your server. You can refer to the [development guide](../tutorial/0-set-up-your-development-environment.md#redis) to learn how to do that.
For this example to work, you’ll need to install and configure Redis on your server. You can refer to the [development guide](/tutorial/set-up-your-development-environment#redis) to learn how to do that.
:::
@@ -66,11 +66,11 @@ const corsOptions = {
}
```
Finally, for each route you add, create an `OPTIONS` request:
Finally, for each route you add, create an `OPTIONS` request and add `cors` as a middleware for the route:
```js
router.options("/admin/hello", cors(corsOptions))
router.get("/admin/hello", (req, res) => {
router.get("/admin/hello", cors(corsOptions), (req, res) => {
//...
})
```
@@ -46,6 +46,34 @@ npm run build
:::
## Accessing Endpoints from Storefront
If you’re customizing one of our storefronts or creating your own, you need to use the `cors` library.
First, you need to import your Medusa’s configurations along with the `cors` library:
```js
import cors from "cors"
import { projectConfig } from "../../medusa-config"
```
Then, create an object that will hold the CORS configurations:
```js
const corsOptions = {
origin: projectConfig.store_cors.split(","),
credentials: true,
}
```
Finally, for each route add `cors` as a middleware for the route passing it `corsOptions`:
```js
router.get("/store/hello", cors(corsOptions), (req, res) => {
//...
})
```
## Multiple Endpoints
### Same File
@@ -0,0 +1,97 @@
# Migrations
In this document, you’ll learn about what Migrations are, their purpose, how you can run them, and how you can create your own Migrations.
:::note
Medusa’s Migrations do not work with SQLite databases. They are intended to be used with PostgreSQL databases, which is the recommended Database for your Medusa production server.
:::
## Overview
Migrations are scripts that are used to make additions or changes to your database schema. In Medusa, they are essential for both when you first install your server and for subsequent server upgrades later on.
When you first create your Medusa server, the database schema used must have all the tables necessary for the server to run.
When a new Medusa version introduces changes to the database schema, you'll have to run migrations to apply them to your own database.
:::tip
Migrations are used to apply changes to the database schema. However, there are some version updates of Medusa that require updating the data in your database to fit the new schema. Those are specific to each version and you should check out the version under Upgrade Guides for details on the steps.
:::
## How to Run Migrations
Migrations in Medusa can be done in one of two ways:
### Migrate Command
Using the Medusa CLI tool, you can run migrations with the following command:
```bash
medusa migrations run
```
This will check for any migrations that contain changes to your database schema that aren't applied yet and run them on your server.
### Seed Command
Seeding is the process of filling your database with data that is either essential or for testing and demo purposes. In Medusa, the `seed` command will run the migrations to your database if necessary before it seeds your database with dummy data.
You can use the following command to seed your database:
```bash npm2yarn
npm run seed
```
This will use the underlying `seed` command provided by Medusa's CLI to seed your database with data from the file `data/seed.json` on your Medusa server.
## How to Create Migrations
In this section, you’ll learn how to create your own migrations using [Typeorm](https://typeorm.io). This will allow you to modify Medusa’s predefined tables or create your own tables.
### Create Migration
To create a migration that makes changes to your Medusa schema, run the following command:
```bash
npx typeorm migration:create -n UserChanged --dir src/path
```
:::tip
The migration file should be inside the src directory to make sure it is built when the build command is run next.
:::
This will create the migration file in the path you specify. You can use this without the need to install Typeorm's CLI tool. You can then go ahead and make changes to it as necessary.
:::tip
You can learn more about writing migrations in [Typeorm’s Documentation](https://typeorm.io/migrations).
:::
### Build Files
Before you can run the migrations you need to run the build command to transpile the TypeScript files to JavaScript files:
```bash npm2yarn
npm run build
```
### Run Migration
The last step is to run the migration with the command detailed earlier
```bash
medusa migrations run
```
If you check your database now you should see that the change defined by the migration has been applied successfully.
## What’s Next 🚀
- Learn more about [setting up your development server](/tutorial/set-up-your-development-environment).
@@ -6,7 +6,7 @@ In this document, you’ll learn how to add a Payment Provider to your Medusa se
A Payment Provider is the payment method used to authorize, capture, and refund payment, among other actions. An example of a Payment Provider is Stripe.
By default, Medusa has a [manual payment provider](https://github.com/medusajs/medusa/tree/2e6622ec5d0ae19d1782e583e099000f0a93b051/packages/medusa-fulfillment-manual) that has minimal implementation. It can be synonymous with a Cash on Delivery payment method. It allows store operators to manage the payment themselves but still keep track of its different stages on Medusa.
By default, Medusa has a [manual payment provider](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-manual) that has minimal implementation. It can be synonymous with a Cash on Delivery payment method. It allows store operators to manage the payment themselves but still keep track of its different stages on Medusa.
Adding a Payment Provider is as simple as creating a [service](../services/create-service.md) file in `src/services`. A Payment Provider is essentially a service that extends `PaymentService` from `medusa-interfaces`.
@@ -42,9 +42,9 @@ These methods are used at different points in the Checkout flow as well as when
![Payment Flows.jpg](https://i.imgur.com/WeDr0ph.jpg)
## Create a Fulfillment Provider
## Create a Payment Provider
The first step to create a fulfillment provider is to create a file in `src/services` with the following content:
The first step to create a payment provider is to create a file in `src/services` with the following content:
```jsx
import { PaymentService } from "medusa-interfaces"
@@ -127,4 +127,4 @@ This prevents any payment issues from occurring with the customers and allows fo
## What’s Next 🚀
- [Check out how the checkout flow is implemented on the frontend.](./frontend-payment-flow-in-checkout.md)
- Check out payment plugins like [Stripe](../../../add-plugins/stripe.md), [Paypal](../../../add-plugins/paypal.md), and [Klarna](../../../add-plugins/klarna.md).
- Check out payment plugins like [Stripe](../../../add-plugins/stripe.md), [Paypal](/add-plugins/paypal), and [Klarna](../../../add-plugins/klarna.md).
@@ -102,4 +102,5 @@ constructor({ helloService, eventBusService }) {
## What’s Next 🚀
- Check out the [Services Reference](/references/services/classes/AuthService) to see a list of all services in Medusa.
- [Learn How to Create an Endpoint.](/advanced/backend/endpoints/add-storefront)
@@ -93,4 +93,5 @@ You can then use `this.productService` anywhere in your subscriber’s methods.
## What’s Next 🚀
- [View the list of all events](events-list.md)
- [Learn how to create a service.](/advanced/backend/services/create-service)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
# v1.3.0
Version 1.3.0 of Medusa introduces new features including the addition of Line Item Adjustments and a more advanced Promotions API, as well as a change in loading environment variables into your Medusa server. The changes do not affect the public APIs and require only running necessary data migrations.
## Prerequisites
Both the actions required for this update need you to set the following environment variables:
```bash
TYPEORM_CONNECTION=postgres
TYPEORM_URL=<DATABASE_URL>
TYPEORM_LOGGING=true
TYPEORM_ENTITIES=./node_modules/@medusajs/medusa/dist/models/*.js
TYPEORM_MIGRATIONS=./node_modules/@medusajs/medusa/dist/migrations/*.js
```
These environment variables are used in the data migration scripts in this upgrade. Make sure to replace `<DATABASE_URL>` with your PostgreSQL database URL.
## Environment Variables
In previous versions of Medusa, The server automatically loads all environment variables in the `.env` file at the root of the Medusa server.
This new update removes loading it automatically and gives developers the freedom in how to load their environment variables. All environment variables will be loaded by default from the system’s environment variables.
### Actions Required
If you use a `.env` file to load environment variables on your server, you need to load the variables manually in `medusa-config.js`.
You can add the following code snippet at the top of the file which uses the [dotenv](https://www.npmjs.com/package/dotenv) package to load the environment variables based on the current Node environment:
```jsx
const dotenv = require('dotenv')
let ENV_FILE_NAME = '';
switch (process.env.NODE_ENV) {
case 'production':
ENV_FILE_NAME = '.env.production';
break;
case 'staging':
ENV_FILE_NAME = '.env.staging';
break;
case 'test':
ENV_FILE_NAME = '.env.test';
break;
case 'development':
default:
ENV_FILE_NAME = '.env';
break;
}
try {
dotenv.config({ path: process.cwd() + '/' + ENV_FILE_NAME });
} catch (e) {
}
```
## Line Item Adjustments
This new version of Medusa allows store operators to adjust line items in an order or a swap which provides more customization capabilities.
It introduces a new model `LineItemAdjustment` which gives more flexibility to adjust the pricing of line items in a cart, order, or swap. A discount can be added, removed, or modified and the price will reflect on the total calculation of the cart, order, or swap.
This also introduces an optimization to the calculation of totals, as it is no longer necessary to calculate the discounts every time the totals are retrieved.
### Actions Required
This new version adds a new data migration script that will go through your list of existing orders and add line item adjustments for each of the line items in the order.
For that reason, it’s essential to run the data migration script after upgrading your server and before starting your Medusa server:
```bash
node ./node_modules/@medusajs/medusa/dist/scripts/line-item-adjustment-migration.js
```
## Advanced Discount Conditions
This new version of Medusa holds advanced promotions functionalities to provide store operators with even more customization capabilities when creating discounts. You can now add even more conditions to your discounts to make them specific for a set of products, collections, customer groups, and more.
This change required creating a new model `DiscountCondition` which belongs to `DiscountRule` and includes a few relationships with other models to make the aforementioned feature possible.
### Actions Required
To ensure your old discount rules play well with the new Promotions API and schema, this version includes a migration script that will go through your existing discount rules, create discount conditions for these rules, and move the former direct relationship between discount rules and products to become between discount conditions and products.
For that reason, it’s essential to run the data migration script after upgrading your server and before starting your Medusa server:
```bash
node ./node_modules/@medusajs/medusa/dist/scripts/discount-rule-migration.js
```
+5 -5
View File
@@ -55,7 +55,7 @@ For the walkthrough purposes, we assume that the selected starter is `medusa-sta
### Selecting a Storefront
After selecting your Medusa starter you will be given the option to install one of our storefront starters. At the moment we have starters for Gatsby and Next.js:
After selecting your Medusa starter, you will be given the option to install one of our storefront starters. At the moment, we have starters for Gatsby and Next.js:
```bash
Which storefront starter would you like to install? …
@@ -74,7 +74,7 @@ Creating new project from git: https://github.com/medusajs/medusa-starter-defaul
Installing packages...
```
Once the installation has been completed you will have a Medusa backend, a demo storefront, and an admin dashboard.
Once the installation has been completed, you will have a Medusa backend, a Demo storefront, and an Admin dashboard.
## What's inside
@@ -87,7 +87,7 @@ Inside the root folder which was specified at the beginning of the installation
/admin // Medusa admin panel
```
`create-medusa-app` prints out the commands that are available to you after installation. When each project is started you can visit your storefront, complete the order, and view the order in Medusa admin.
`create-medusa-app` prints out the commands that are available to you after installation. When each project is started, you can visit your storefront, complete the order, and view the order in Medusa admin.
```bash
⠴ Installing packages...
@@ -112,10 +112,10 @@ Create initial git commit in my-medusa-store/admin
## **What's next?**
To learn more about Medusa to go through our docs to get some inspiration and guidance for the next steps and further development:
To learn more about Medusa, go through our docs to get some inspiration and guidance for the next steps and further development:
- [Find out how to set up a Medusa project with Gatsby and Contentful](https://docs.medusajs.com/how-to/headless-ecommerce-store-with-gatsby-contentful-medusa)
- [Move your Medusa setup to the next level with some custom functionality](https://docs.medusajs.com/tutorial/adding-custom-functionality)
- [Create your own Medusa plugin](https://docs.medusajs.com/guides/plugins)
If you have any follow-up questions or want to chat directly with our engineering team we are always happy to meet you at our [Discord](https://discord.gg/DSHySyMu).
If you have any follow-up questions or want to chat directly with our engineering team, we are always happy to meet you at our [Discord](https://discord.gg/DSHySyMu).
+6 -6
View File
@@ -4,7 +4,7 @@ title: "Deploying on Heroku"
# Deploying on Heroku
This is a guide for deploying a Medusa project on Heroku. Heroku is at PaaS that allows you to easily deploy your applications in the cloud.
This is a guide for deploying a Medusa project on Heroku. Heroku is a PaaS (Platform as a Service) that allows you to easily deploy your applications in the cloud.
<div>
<video width="100%" height="100%" playsinline autoplay muted controls>
@@ -57,7 +57,7 @@ Follow the instructions on your terminal
### 3. Create an app on Heroku
In your **Medusa project directory** run the following commands to create an app on Heroku and add it as a remote origin.
In your **Medusa project directory**, run the following commands to create an app on Heroku and add it as a remote origin.
```bash
heroku create medusa-test-app
@@ -70,13 +70,13 @@ Medusa requires a Postgres database and a Redis instance to work. These are adde
:::tip
In this below example, we initialize the resources on free plans. This is not a valid configuration for a production environment.
In this example below, we initialize the resources on free plans. This is not a valid configuration for a production environment.
:::
#### Postgresql
Add a Postgres addon to your Heroku app
Add a Postgres add-on to your Heroku app
```bash
heroku addons:create heroku-postgresql:hobby-dev
@@ -90,7 +90,7 @@ Add a Redis instance to your Heroku app
:::note
The addon `redistogo:nano` is free, but Heroku requires you to add a payment method to proceed.
The add-on `redistogo:nano` is free, but Heroku requires you to add a payment method to proceed.
:::
@@ -102,7 +102,7 @@ You can find more informations, plans and pricing about Redis To Go [here](https
### 5. Configure environment variables on Heroku
Medusa requires a set of environment variables. From you project repository run the following commands:.
Medusa requires a set of environment variables. From you project repository, run the following commands:.
```bash
heroku config:set NODE_ENV=production
@@ -15,7 +15,7 @@ This article assumes you already have the Medusa project created and ready to be
## Getting started
In order to get started let's open the terminal and use the following command to create an instance of your storefront:
In order to get started, let's open the terminal and use the following command to create an instance of your storefront:
```zsh
npx create-next-app -e https://github.com/medusajs/nextjs-starter-medusa my-medusa-storefront
@@ -31,7 +31,7 @@ Let's jump to these two.
For this part, we should navigate to a `client.js` file which you can find in the utils folder.
We don't need to do much in here, but to make sure that our storefront is pointing to the port, where the server is running
We don't need to do much in here, but to make sure that our storefront is pointing to the port where the server is running
```js
import Medusa from "@medusajs/medusa-js"
@@ -39,13 +39,13 @@ const BACKEND_URL = process.env.GATSBY_STORE_URL || "http://localhost:9000" // <
export const createClient = () => new Medusa({ baseUrl: BACKEND_URL })
```
By default the Medusa server is running at port 9000, so if you didn't change that we are good to go to our next step.
By default, the Medusa server is running at port 9000. So if you didn't change that, we are good to go to our next step.
## Update the `STORE_CORS` variable
Here let's navigate to your Medusa server and open `medusa-config.js`
Let's locate the `STORE_CORS` variable and make sure it's the right port (which is 3000 by default for Next.js projects)
Let's locate the `STORE_CORS` variable and make sure it's the right port (which is 3000 by default for Next.js projects).
```js
/*
+1 -1
View File
@@ -18,7 +18,7 @@ Your Medusa server will include all functionalities related to your store’s ch
The admin dashboard is accessible by store operators. Store operators can use the admin dashboard to view, create, and modify data such as orders and products.
Medusa provides a beautiful [admin dashboard](https://demo.medusajs.com) that you can use right off the bat. Our admin dashboard provides a lot of functionalities to manage your store including Order management, product management, user management and more.
Medusa provides a beautiful [admin dashboard](https://demo.medusajs.com) that you can use right off the bat. Our admin dashboard provides a lot of functionalities to manage your store including Order management, Product management, User management and more.
You can also create your own admin dashboard by utilizing the [Admin REST APIs](https://docs.medusajs.com/api/admin/auth).
+22 -20
View File
@@ -1,6 +1,12 @@
# Quickstart
This quickstart is intended for experienced developers, that are accustomed with concepts like JavaScript, Node.js, SQL and the command line. For a more gentle introduction, see our tutorial on [how to set up your development environment](../tutorial/0-set-up-your-development-environment.md).
This document will guide you through setting up your Medusa server in a few minutes.
:::tip
For a more detailed guide on how to set up your local environment to work with Medusa, check out the documentation on [how to set up your development environment](/tutorial/set-up-your-development-environment).
:::
## Prerequisites
@@ -29,33 +35,29 @@ You can install Node from the [official website](https://nodejs.org/en/).
3. **Start your Medusa engine**
```bash
cd my-medusa-store
medusa develop
```
4. **Use the API**
After these 3 steps and in only a couple of minutes, you now have a complete commerce engine running locally. You can test it out by sending a request using a tool like Postman or through the command line:
```bash
curl localhost:9000/store/products | python -m json.tool
```
```bash
curl localhost:9000/store/products | python -m json.tool
```
After these four steps and only a couple of minutes, you now have a complete commerce engine running locally. You may now explore [the documentation](https://docs.medusajs.com/api) to learn how to interact with the Medusa API. You may also add [plugins](https://github.com/medusajs/medusa/tree/master/packages) to your Medusa store by specifying them in your `medusa-config.js` file.
We have a prebuilt admin dashboard that you can use to configure and manage your store find it here: [Medusa Admin](https://github.com/medusajs/admin)
:::note
## What's next?
This command uses Python to format the result of the request better in your command line. If you don't want to use Python you can simply send a request without the formatting:
### Set up a storefront for your Medusa project
We have created two starters for you that can help you lay a foundation for your storefront. The starters work with your new server with minimal configuration simply clone the starters from here:
- [Nextjs Starter](https://github.com/medusajs/nextjs-starter-medusa)
- [Gatsby Starter](https://github.com/medusajs/gatsby-starter-medusa)
:::tip
Medusa runs on port 9000 by default and the storefront starters are both configured to run on port 8000. If you wish to run your storefront starter on another port you should update your CORS settings in your project's `medusa-config.js`.
```bash
curl localhost:9000/store/products
```
:::
<!-- ### Link you local development to Medusa Cloud (Coming soon!)
## What's next :rocket:
With your project in local development you can link your Medusa instance to Medusa Cloud - this will allow you to manage your store, view orders and test out the amazing functionalities that you are building. [Get started here](https://docs.medusajs.com/tutorial/linking-your-local-project-with-medusa-cloud). -->
- Install our [Next.js](http://localhost:3000/starters/nextjs-medusa-starter) or [Gatsby](http://localhost:3000/starters/gatsby-medusa-starter) storefronts to set up your ecommerce storefront quickly.
- Install the [Medusa Admin](../admin/quickstart.md) to supercharge your ecommerce experience with easy access to configurations and features.
- Check our the [API reference](https://docs.medusajs.com/api) to learn more about available endpoints available on your Medusa server.
- Install [plugins](https://github.com/medusajs/medusa/tree/master/packages) for features like Payment, CMS, Notifications, among other features.
@@ -0,0 +1 @@
TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false.
@@ -0,0 +1,136 @@
# Class: AuthService
Can authenticate a user based on email password combination
## Hierarchy
- `"medusa-interfaces"`
↳ **`AuthService`**
## Constructors
### constructor
• **new AuthService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/auth.ts:12](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/auth.ts#L12)
## Methods
### authenticate
▸ **authenticate**(`email`, `password`): `Promise`<`AuthenticateResult`\>
Authenticates a given user based on an email, password combination. Uses
scrypt to match password with hashed value.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `email` | `string` | the email of the user |
| `password` | `string` | the password of the user |
#### Returns
`Promise`<`AuthenticateResult`\>
success: whether authentication succeeded
user: the user document if authentication succeded
error: a string with the error message
#### Defined in
[services/auth.ts:78](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/auth.ts#L78)
___
### authenticateAPIToken
▸ **authenticateAPIToken**(`token`): `Promise`<`AuthenticateResult`\>
Authenticates a given user with an API token
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `token` | `string` | the api_token of the user to authenticate |
#### Returns
`Promise`<`AuthenticateResult`\>
success: whether authentication succeeded
user: the user document if authentication succeded
error: a string with the error message
#### Defined in
[services/auth.ts:41](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/auth.ts#L41)
___
### authenticateCustomer
▸ **authenticateCustomer**(`email`, `password`): `Promise`<`AuthenticateResult`\>
Authenticates a customer based on an email, password combination. Uses
scrypt to match password with hashed value.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `email` | `string` | the email of the user |
| `password` | `string` | the password of the user |
#### Returns
`Promise`<`AuthenticateResult`\>
success: whether authentication succeeded
user: the user document if authentication succeded
error: a string with the error message
#### Defined in
[services/auth.ts:123](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/auth.ts#L123)
___
### comparePassword\_
▸ **comparePassword_**(`password`, `hash`): `Promise`<`boolean`\>
Verifies if a password is valid given the provided password hash
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `password` | `string` | the raw password to check |
| `hash` | `string` | the hash to compare against |
#### Returns
`Promise`<`boolean`\>
the result of the comparison
#### Defined in
[services/auth.ts:28](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/auth.ts#L28)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,219 @@
# Class: ClaimItemService
## Hierarchy
- `"medusa-interfaces"`
↳ **`ClaimItemService`**
## Constructors
### constructor
• **new ClaimItemService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/claim-item.js:11](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L11)
## Properties
### claimImageRepository\_
• **claimImageRepository\_**: `any`
#### Defined in
[services/claim-item.js:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L27)
___
### claimTagRepository\_
• **claimTagRepository\_**: `any`
#### Defined in
[services/claim-item.js:26](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L26)
___
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CANCELED` | `string` |
| `CREATED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/claim-item.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L5)
## Methods
### cancel
▸ **cancel**(`id`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/claim-item.js:212](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L212)
___
### create
▸ **create**(`data`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `any` |
#### Returns
`any`
#### Defined in
[services/claim-item.js:55](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L55)
___
### deleteMetadata
▸ **deleteMetadata**(`orderId`, `key`): `Promise`<`any`\>
Dedicated method to delete metadata for an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the order to delete metadata from. |
| `key` | `string` | key for metadata field |
#### Returns
`Promise`<`any`\>
resolves to the updated result.
#### Defined in
[services/claim-item.js:259](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L259)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config object for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/claim-item.js:219](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L219)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`Order`\>
Gets a claim item by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of ClaimItem to retrieve |
| `config` | `any` | configuration for the find operation |
#### Returns
`Promise`<`Order`\>
the ClaimItem
#### Defined in
[services/claim-item.js:234](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L234)
___
### update
▸ **update**(`id`, `data`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
| `data` | `any` |
#### Returns
`any`
#### Defined in
[services/claim-item.js:135](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L135)
___
### withTransaction
▸ **withTransaction**(`manager`): [`ClaimItemService`](ClaimItemService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `manager` | `any` |
#### Returns
[`ClaimItemService`](ClaimItemService.md)
#### Defined in
[services/claim-item.js:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim-item.js#L36)
@@ -0,0 +1,438 @@
# Class: ClaimService
## Hierarchy
- `"medusa-interfaces"`
↳ **`ClaimService`**
## Constructors
### constructor
• **new ClaimService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/claim.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L14)
## Properties
### addressRepo\_
• **addressRepo\_**: `any`
#### Defined in
[services/claim.js:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L36)
___
### claimItemService\_
• **claimItemService\_**: `any`
#### Defined in
[services/claim.js:37](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L37)
___
### claimRepository\_
• **claimRepository\_**: `any`
#### Defined in
[services/claim.js:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L38)
___
### eventBus\_
• **eventBus\_**: `any`
#### Defined in
[services/claim.js:39](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L39)
___
### fulfillmentProviderService\_
• **fulfillmentProviderService\_**: `any`
#### Defined in
[services/claim.js:40](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L40)
___
### fulfillmentService\_
• **fulfillmentService\_**: `any`
#### Defined in
[services/claim.js:41](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L41)
___
### inventoryService\_
• **inventoryService\_**: `any`
#### Defined in
[services/claim.js:42](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L42)
___
### lineItemService\_
• **lineItemService\_**: `any`
#### Defined in
[services/claim.js:43](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L43)
___
### paymentProviderService\_
• **paymentProviderService\_**: `any`
#### Defined in
[services/claim.js:44](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L44)
___
### regionService\_
• **regionService\_**: `any`
#### Defined in
[services/claim.js:45](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L45)
___
### returnService\_
• **returnService\_**: `any`
#### Defined in
[services/claim.js:46](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L46)
___
### shippingOptionService\_
• **shippingOptionService\_**: `any`
#### Defined in
[services/claim.js:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L47)
___
### taxProviderService\_
• **taxProviderService\_**: `any`
#### Defined in
[services/claim.js:48](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L48)
___
### totalsService\_
• **totalsService\_**: `any`
#### Defined in
[services/claim.js:49](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L49)
___
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CANCELED` | `string` |
| `CREATED` | `string` |
| `FULFILLMENT_CREATED` | `string` |
| `REFUND_PROCESSED` | `string` |
| `SHIPMENT_CREATED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/claim.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L5)
## Methods
### cancel
▸ **cancel**(`id`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/claim.js:644](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L644)
___
### cancelFulfillment
▸ **cancelFulfillment**(`fulfillmentId`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `fulfillmentId` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/claim.js:512](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L512)
___
### create
▸ **create**(`data`): `any`
Creates a Claim on an Order. Claims consists of items that are claimed and
optionally items to be sent as replacement for the claimed items. The
shipping address that the new items will be shipped to
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `any` | the object containing all data required to create a claim |
#### Returns
`any`
created claim
#### Defined in
[services/claim.js:159](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L159)
___
### createFulfillment
▸ **createFulfillment**(`id`, `config?`): `Claim`
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the object containing all data required to create a claim |
| `config` | `Object` | config object |
| `config.metadata` | `any` | config metadata |
| `config.no_notification` | `undefined` \| `boolean` | config no notification |
#### Returns
`Claim`
created claim
#### Defined in
[services/claim.js:378](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L378)
___
### createShipment
▸ **createShipment**(`id`, `fulfillmentId`, `trackingLinks`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `any` | `undefined` |
| `fulfillmentId` | `any` | `undefined` |
| `trackingLinks` | `any` | `undefined` |
| `config` | `Object` | `undefined` |
| `config.metadata` | `Object` | `{}` |
| `config.no_notification` | `undefined` | `undefined` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/claim.js:577](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L577)
___
### deleteMetadata
▸ **deleteMetadata**(`orderId`, `key`): `Promise`<`any`\>
Dedicated method to delete metadata for an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the order to delete metadata from. |
| `key` | `string` | key for metadata field |
#### Returns
`Promise`<`any`\>
resolves to the updated result.
#### Defined in
[services/claim.js:734](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L734)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/claim.js:696](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L696)
___
### processRefund
▸ **processRefund**(`id`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/claim.js:535](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L535)
___
### retrieve
▸ **retrieve**(`claimId`, `config?`): `Promise`<`Order`\>
Gets an order by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `claimId` | `string` | id of order to retrieve |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/claim.js:711](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L711)
___
### update
▸ **update**(`id`, `data`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
| `data` | `any` |
#### Returns
`any`
#### Defined in
[services/claim.js:80](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L80)
___
### withTransaction
▸ **withTransaction**(`manager`): [`ClaimService`](ClaimService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `manager` | `any` |
#### Returns
[`ClaimService`](ClaimService.md)
#### Defined in
[services/claim.js:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/claim.js#L52)
@@ -0,0 +1,126 @@
# Class: CustomShippingOptionService
## Hierarchy
- `"medusa-interfaces"`
↳ **`CustomShippingOptionService`**
## Constructors
### constructor
• **new CustomShippingOptionService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/custom-shipping-option.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/custom-shipping-option.js#L5)
## Methods
### create
▸ **create**(`data`, `config?`): `Promise`<`CustomShippingOption`\>
Creates a custom shipping option associated with a given author
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `any` | the custom shipping option to create |
| `config` | `any` | any configurations if needed, including meta data |
#### Returns
`Promise`<`CustomShippingOption`\>
resolves to the creation result
#### Defined in
[services/custom-shipping-option.js:88](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/custom-shipping-option.js#L88)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`CustomShippingOption`[]\>
Fetches all custom shipping options related to the given selector
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the configuration used to find the objects. contains relations, skip, and take. |
#### Returns
`Promise`<`CustomShippingOption`[]\>
custom shipping options matching the query
#### Defined in
[services/custom-shipping-option.js:65](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/custom-shipping-option.js#L65)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`CustomShippingOption`\>
Retrieves a specific shipping option.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the custom shipping option to retrieve. |
| `config` | `any` | any options needed to query for the result. |
#### Returns
`Promise`<`CustomShippingOption`\>
which resolves to the requested custom shipping option.
#### Defined in
[services/custom-shipping-option.js:40](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/custom-shipping-option.js#L40)
___
### withTransaction
▸ **withTransaction**(`manager`): [`CustomShippingOptionService`](CustomShippingOptionService.md)
Sets the service's manager to a given transaction manager
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `manager` | `EntityManager` | the manager to use |
#### Returns
[`CustomShippingOptionService`](CustomShippingOptionService.md)
a cloned CustomShippingOption service
#### Defined in
[services/custom-shipping-option.js:20](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/custom-shipping-option.js#L20)
@@ -0,0 +1,275 @@
# Class: CustomerGroupService
Provides layer to manipulate discounts.
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`CustomerGroupService`**
## Constructors
### constructor
• **new CustomerGroupService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `CustomerGroupConstructorProps` |
#### Overrides
BaseService.constructor
#### Defined in
[services/customer-group.ts:31](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L31)
## Properties
### customerGroupRepository\_
• `Private` **customerGroupRepository\_**: typeof `CustomerGroupRepository`
#### Defined in
[services/customer-group.ts:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L27)
___
### customerService\_
• `Private` **customerService\_**: [`CustomerService`](CustomerService.md)
#### Defined in
[services/customer-group.ts:29](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L29)
___
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/customer-group.ts:25](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L25)
## Methods
### addCustomers
▸ **addCustomers**(`id`, `customerIds`): `Promise`<`CustomerGroup`\>
Add a batch of customers to a customer group at once
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of the customer group to add customers to |
| `customerIds` | `string` \| `string`[] | customer id's to add to the group |
#### Returns
`Promise`<`CustomerGroup`\>
the customer group after insertion
#### Defined in
[services/customer-group.ts:113](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L113)
___
### create
▸ **create**(`group`): `Promise`<`CustomerGroup`\>
Creates a customer group with the provided data.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `group` | `DeepPartial`<`CustomerGroup`\> | the customer group to create |
#### Returns
`Promise`<`CustomerGroup`\>
the result of the create operation
#### Defined in
[services/customer-group.ts:86](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L86)
___
### delete
▸ **delete**(`groupId`): `Promise`<`void`\>
Remove customer group
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `groupId` | `string` | id of the customer group to delete |
#### Returns
`Promise`<`void`\>
a promise
#### Defined in
[services/customer-group.ts:194](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L194)
___
### list
▸ **list**(`selector?`, `config`): `Promise`<`CustomerGroup`[]\>
List customer groups.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableCustomerGroupProps` | the query object for find |
| `config` | `FindConfig`<`CustomerGroup`\> | the config to be used for find |
#### Returns
`Promise`<`CustomerGroup`[]\>
the result of the find operation
#### Defined in
[services/customer-group.ts:217](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L217)
___
### listAndCount
▸ **listAndCount**(`selector?`, `config`): `Promise`<[`CustomerGroup`[], `number`]\>
Retrieve a list of customer groups and total count of records that match the query.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableCustomerGroupProps` | the query object for find |
| `config` | `FindConfig`<`CustomerGroup`\> | the config to be used for find |
#### Returns
`Promise`<[`CustomerGroup`[], `number`]\>
the result of the find operation
#### Defined in
[services/customer-group.ts:236](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L236)
___
### removeCustomer
▸ **removeCustomer**(`id`, `customerIds`): `Promise`<`CustomerGroup`\>
Remove list of customers from a customergroup
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of the customer group from which the customers are removed |
| `customerIds` | `string` \| `string`[] | id's of the customer to remove from group |
#### Returns
`Promise`<`CustomerGroup`\>
the customergroup with the provided id
#### Defined in
[services/customer-group.ts:271](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L271)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`CustomerGroup`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `config` | `Object` |
#### Returns
`Promise`<`CustomerGroup`\>
#### Defined in
[services/customer-group.ts:62](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L62)
___
### update
▸ **update**(`customerGroupId`, `update`): `Promise`<`CustomerGroup`[]\>
Update a customer group.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customerGroupId` | `string` | id of the customer group |
| `update` | `CustomerGroupUpdate` | customer group partial data |
#### Returns
`Promise`<`CustomerGroup`[]\>
resulting customer group
#### Defined in
[services/customer-group.ts:162](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L162)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`CustomerGroupService`](CustomerGroupService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`CustomerGroupService`](CustomerGroupService.md)
#### Defined in
[services/customer-group.ts:46](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer-group.ts#L46)
@@ -0,0 +1,452 @@
# Class: CustomerService
Provides layer to manipulate customers.
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`CustomerService`**
## Constructors
### constructor
• **new CustomerService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/customer.js:20](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L20)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `PASSWORD_RESET` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/customer.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L14)
## Methods
### addAddress
▸ **addAddress**(`customerId`, `address`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `customerId` | `any` |
| `address` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/customer.js:479](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L479)
___
### count
▸ **count**(): `Promise`<`any`\>
Return the total number of documents in database
#### Returns
`Promise`<`any`\>
the result of the count operation
#### Defined in
[services/customer.js:192](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L192)
___
### create
▸ **create**(`customer`): `Promise`<`any`\>
Creates a customer from an email - customers can have accounts associated,
e.g. to login and view order history, etc. If a password is provided the
customer will automatically get an account, otherwise the customer is just
used to hold details of customers.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customer` | `any` | the customer to create |
#### Returns
`Promise`<`any`\>
the result of create
#### Defined in
[services/customer.js:290](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L290)
___
### decorate
▸ **decorate**(`customer`, `fields?`, `expandFields?`): `Customer`
Decorates a customer.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `customer` | `Customer` | `undefined` | the cart to decorate. |
| `fields` | `string`[] | `[]` | the fields to include. |
| `expandFields` | `string`[] | `[]` | fields to expand. |
#### Returns
`Customer`
return the decorated customer.
#### Defined in
[services/customer.js:547](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L547)
___
### delete
▸ **delete**(`customerId`): `Promise`<`any`\>
Deletes a customer from a given customer id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customerId` | `string` | the id of the customer to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<`any`\>
the result of the delete operation.
#### Defined in
[services/customer.js:523](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L523)
___
### generateResetPasswordToken
▸ **generateResetPasswordToken**(`customerId`): `string`
Generate a JSON Web token, that will be sent to a customer, that wishes to
reset password.
The token will be signed with the customer's current password hash as a
secret a long side a payload with userId and the expiry time for the token,
which is always 15 minutes.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customerId` | `string` | the customer to reset the password for |
#### Returns
`string`
the generated JSON web token
#### Defined in
[services/customer.js:67](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L67)
___
### hashPassword\_
▸ **hashPassword_**(`password`): `Promise`<`string`\>
Hashes a password
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `password` | `string` | the value to hash |
#### Returns
`Promise`<`string`\>
hashed password
#### Defined in
[services/customer.js:277](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L277)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/customer.js:106](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L106)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `FindConfig`<`Customer`\> | the config object containing query settings |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/customer.js:147](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L147)
___
### removeAddress
▸ **removeAddress**(`customerId`, `addressId`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `customerId` | `any` |
| `addressId` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/customer.js:460](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L460)
___
### retrieve
▸ **retrieve**(`customerId`, `config?`): `Promise`<`Customer`\>
Gets a customer by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customerId` | `string` | the id of the customer to get. |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`Customer`\>
the customer document.
#### Defined in
[services/customer.js:205](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L205)
___
### retrieveByEmail
▸ **retrieveByEmail**(`email`, `config?`): `Promise`<`Customer`\>
Gets a customer by email.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `email` | `string` | the email of the customer to get. |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`Customer`\>
the customer document.
#### Defined in
[services/customer.js:230](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L230)
___
### retrieveByPhone
▸ **retrieveByPhone**(`phone`, `config?`): `Promise`<`Customer`\>
Gets a customer by phone.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `phone` | `string` | the phone of the customer to get. |
| `config` | `any` | the config object containing query settings |
#### Returns
`Promise`<`Customer`\>
the customer document.
#### Defined in
[services/customer.js:254](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L254)
___
### update
▸ **update**(`customerId`, `update`): `Promise`<`any`\>
Updates a customer.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customerId` | `string` | the id of the variant. Must be a string that can be casted to an ObjectId |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/customer.js:346](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L346)
___
### updateAddress
▸ **updateAddress**(`customerId`, `addressId`, `address`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `customerId` | `any` |
| `addressId` | `any` |
| `address` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/customer.js:441](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L441)
___
### updateBillingAddress\_
▸ **updateBillingAddress_**(`customer`, `addressOrId`, `addrRepo`): `Promise`<`any`\>
Updates the customers' billing address.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `customer` | `Customer` | the Customer to update |
| `addressOrId` | `any` | the value to set the billing address to |
| `addrRepo` | `any` | address repository |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/customer.js:408](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L408)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`CustomerService`](CustomerService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`CustomerService`](CustomerService.md)
#### Defined in
[services/customer.js:41](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/customer.js#L41)
@@ -0,0 +1,637 @@
# Class: DiscountService
Provides layer to manipulate discounts.
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`DiscountService`**
## Constructors
### constructor
• **new DiscountService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/discount.ts:59](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L59)
## Properties
### discountConditionRepository\_
• `Private` **discountConditionRepository\_**: typeof `DiscountConditionRepository`
#### Defined in
[services/discount.ts:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L52)
___
### discountConditionService\_
• `Private` **discountConditionService\_**: `DiscountConditionService`
#### Defined in
[services/discount.ts:53](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L53)
___
### discountRepository\_
• `Private` **discountRepository\_**: typeof `DiscountRepository`
#### Defined in
[services/discount.ts:49](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L49)
___
### discountRuleRepository\_
• `Private` **discountRuleRepository\_**: typeof `DiscountRuleRepository`
#### Defined in
[services/discount.ts:50](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L50)
___
### eventBus\_
• `Private` **eventBus\_**: [`EventBusService`](EventBusService.md)
#### Defined in
[services/discount.ts:57](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L57)
___
### giftCardRepository\_
• `Private` **giftCardRepository\_**: typeof `GiftCardRepository`
#### Defined in
[services/discount.ts:51](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L51)
___
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/discount.ts:48](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L48)
___
### productService\_
• `Private` **productService\_**: [`ProductService`](ProductService.md)
#### Defined in
[services/discount.ts:55](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L55)
___
### regionService\_
• `Private` **regionService\_**: [`RegionService`](RegionService.md)
#### Defined in
[services/discount.ts:56](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L56)
___
### totalsService\_
• `Private` **totalsService\_**: [`TotalsService`](TotalsService.md)
#### Defined in
[services/discount.ts:54](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L54)
## Methods
### addRegion
▸ **addRegion**(`discountId`, `regionId`): `Promise`<`Discount`\>
Adds a region to the discount regions array.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | id of discount |
| `regionId` | `string` | id of region to add |
#### Returns
`Promise`<`Discount`\>
the result of the update operation
#### Defined in
[services/discount.ts:521](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L521)
___
### calculateDiscountForLineItem
▸ **calculateDiscountForLineItem**(`discountId`, `lineItem`, `cart`): `Promise`<`number`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `discountId` | `string` |
| `lineItem` | `LineItem` |
| `cart` | `Cart` |
#### Returns
`Promise`<`number`\>
#### Defined in
[services/discount.ts:624](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L624)
___
### canApplyForCustomer
▸ **canApplyForCustomer**(`discountRuleId`, `customerId`): `Promise`<`boolean`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `discountRuleId` | `string` |
| `customerId` | `undefined` \| `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[services/discount.ts:762](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L762)
___
### create
▸ **create**(`discount`): `Promise`<`Discount`\>
Creates a discount with provided data given that the data is validated.
Normalizes discount code to uppercase.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discount` | `CreateDiscountInput` | the discount data to create |
#### Returns
`Promise`<`Discount`\>
the result of the create operation
#### Defined in
[services/discount.ts:220](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L220)
___
### createDynamicCode
▸ **createDynamicCode**(`discountId`, `data`): `Promise`<`Discount`\>
Creates a dynamic code for a discount id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | the id of the discount to create a code for |
| `data` | `CreateDynamicDiscountInput` | the object containing a code to identify the discount by |
#### Returns
`Promise`<`Discount`\>
the newly created dynamic code
#### Defined in
[services/discount.ts:446](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L446)
___
### delete
▸ **delete**(`discountId`): `Promise`<`void`\>
Deletes a discount idempotently
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | id of discount to delete |
#### Returns
`Promise`<`void`\>
the result of the delete operation
#### Defined in
[services/discount.ts:583](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L583)
___
### deleteDynamicCode
▸ **deleteDynamicCode**(`discountId`, `code`): `Promise`<`void`\>
Deletes a dynamic code for a discount id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | the id of the discount to create a code for |
| `code` | `string` | the code to identify the discount by |
#### Returns
`Promise`<`void`\>
the newly created dynamic code
#### Defined in
[services/discount.ts:498](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L498)
___
### hasExpired
▸ **hasExpired**(`discount`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `discount` | `Discount` |
#### Returns
`boolean`
#### Defined in
[services/discount.ts:733](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L733)
___
### hasNotStarted
▸ **hasNotStarted**(`discount`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `discount` | `Discount` |
#### Returns
`boolean`
#### Defined in
[services/discount.ts:729](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L729)
___
### hasReachedLimit
▸ **hasReachedLimit**(`discount`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `discount` | `Discount` |
#### Returns
`boolean`
#### Defined in
[services/discount.ts:723](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L723)
___
### isDisabled
▸ **isDisabled**(`discount`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `discount` | `Discount` |
#### Returns
`boolean`
#### Defined in
[services/discount.ts:741](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L741)
___
### isValidForRegion
▸ **isValidForRegion**(`discount`, `region_id`): `Promise`<`boolean`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `discount` | `Discount` |
| `region_id` | `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[services/discount.ts:745](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L745)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`Discount`[]\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableDiscountProps` | the query object for find |
| `config` | `FindConfig`<`Discount`\> | the config object containing query settings |
#### Returns
`Promise`<`Discount`[]\>
the result of the find operation
#### Defined in
[services/discount.ts:156](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L156)
___
### listAndCount
▸ **listAndCount**(`selector?`, `config?`): `Promise`<[`Discount`[], `number`]\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableDiscountProps` | the query object for find |
| `config` | `FindConfig`<`Discount`\> | the config object containing query settings |
#### Returns
`Promise`<[`Discount`[], `number`]\>
the result of the find operation
#### Defined in
[services/discount.ts:173](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L173)
___
### removeRegion
▸ **removeRegion**(`discountId`, `regionId`): `Promise`<`Discount`\>
Removes a region from the discount regions array.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | id of discount |
| `regionId` | `string` | id of region to remove |
#### Returns
`Promise`<`Discount`\>
the result of the update operation
#### Defined in
[services/discount.ts:557](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L557)
___
### retrieve
▸ **retrieve**(`discountId`, `config?`): `Promise`<`Discount`\>
Gets a discount by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | id of discount to retrieve |
| `config` | `FindConfig`<`Discount`\> | the config object containing query settings |
#### Returns
`Promise`<`Discount`\>
the discount
#### Defined in
[services/discount.ts:285](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L285)
___
### retrieveByCode
▸ **retrieveByCode**(`discountCode`, `config?`): `Promise`<`Discount`\>
Gets a discount by discount code.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountCode` | `string` | discount code of discount to retrieve |
| `config` | `FindConfig`<`Discount`\> | the config object containing query settings |
#### Returns
`Promise`<`Discount`\>
the discount document
#### Defined in
[services/discount.ts:313](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L313)
___
### update
▸ **update**(`discountId`, `update`): `Promise`<`Discount`\>
Updates a discount.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountId` | `string` | discount id of discount to update |
| `update` | `UpdateDiscountInput` | the data to update the discount with |
#### Returns
`Promise`<`Discount`\>
the result of the update operation
#### Defined in
[services/discount.ts:348](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L348)
___
### validateDiscountForCartOrThrow
▸ **validateDiscountForCartOrThrow**(`cart`, `discount`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `cart` | `Cart` |
| `discount` | `Discount` |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/discount.ts:665](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L665)
___
### validateDiscountForProduct
▸ **validateDiscountForProduct**(`discountRuleId`, `productId`): `Promise`<`boolean`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `discountRuleId` | `string` |
| `productId` | `undefined` \| `string` |
#### Returns
`Promise`<`boolean`\>
#### Defined in
[services/discount.ts:599](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L599)
___
### validateDiscountRule\_
▸ **validateDiscountRule_**<`T`\>(`discountRule`): `T`
Creates a discount rule with provided data given that the data is validated.
#### Type parameters
| Name | Type |
| :------ | :------ |
| `T` | extends `Object` |
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discountRule` | `T` | the discount rule to create |
#### Returns
`T`
the result of the create operation
#### Defined in
[services/discount.ts:138](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L138)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`DiscountService`](DiscountService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`DiscountService`](DiscountService.md)
#### Defined in
[services/discount.ts:108](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/discount.ts#L108)
@@ -0,0 +1,266 @@
# Class: DraftOrderService
Handles draft orders
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`DraftOrderService`**
## Constructors
### constructor
• **new DraftOrderService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/draft-order.js:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L15)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/draft-order.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L10)
## Methods
### create
▸ **create**(`data`): `Promise`<`DraftOrder`\>
Creates a draft order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `any` | data to create draft order from |
#### Returns
`Promise`<`DraftOrder`\>
the created draft order
#### Defined in
[services/draft-order.js:233](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L233)
___
### delete
▸ **delete**(`draftOrderId`): `Promise`<`any`\>
Deletes draft order idempotently.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `draftOrderId` | `string` | id of draft order to delete |
#### Returns
`Promise`<`any`\>
empty promise
#### Defined in
[services/draft-order.js:135](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L135)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`DraftOrder`\>
Lists draft orders
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | query object for find |
| `config` | `any` | configurable attributes for find |
#### Returns
`Promise`<`DraftOrder`\>
list of draft orders
#### Defined in
[services/draft-order.js:215](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L215)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<`DraftOrder`[]\>
Lists draft orders alongside the count
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | query selector to filter draft orders |
| `config` | `any` | query config |
#### Returns
`Promise`<`DraftOrder`[]\>
draft orders
#### Defined in
[services/draft-order.js:161](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L161)
___
### registerCartCompletion
▸ **registerCartCompletion**(`doId`, `orderId`): `Promise`<`any`\>
Registers a draft order as completed, when an order has been completed.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `doId` | `string` | id of draft order to complete |
| `orderId` | `string` | id of order completed from draft order cart |
#### Returns
`Promise`<`any`\>
the created order
#### Defined in
[services/draft-order.js:336](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L336)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`DraftOrder`\>
Retrieves a draft order with the given id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of the draft order to retrieve |
| `config` | `any` | query object for findOne |
#### Returns
`Promise`<`DraftOrder`\>
the draft order
#### Defined in
[services/draft-order.js:84](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L84)
___
### retrieveByCartId
▸ **retrieveByCartId**(`cartId`, `config?`): `Promise`<`DraftOrder`\>
Retrieves a draft order based on its associated cart id
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartId` | `string` | cart id that the draft orders's cart has |
| `config` | `any` | query object for findOne |
#### Returns
`Promise`<`DraftOrder`\>
the draft order
#### Defined in
[services/draft-order.js:111](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L111)
___
### update
▸ **update**(`doId`, `data`): `Promise`<`DraftOrder`\>
Updates a draft order with the given data
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `doId` | `string` | id of the draft order |
| `data` | `DraftOrder` | values to update the order with |
#### Returns
`Promise`<`DraftOrder`\>
the updated draft order
#### Defined in
[services/draft-order.js:357](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L357)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`DraftOrderService`](DraftOrderService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`DraftOrderService`](DraftOrderService.md)
#### Defined in
[services/draft-order.js:56](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/draft-order.js#L56)
@@ -0,0 +1,332 @@
# Class: EventBusService
Can keep track of multiple subscribers to different events and run the
subscribers when events happen. Events will run asynchronously.
## Constructors
### constructor
• **new EventBusService**(`__namedParameters`, `config`, `singleton?`)
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `__namedParameters` | `Object` | `undefined` |
| `config` | `any` | `undefined` |
| `singleton` | `boolean` | `true` |
#### Defined in
[services/event-bus.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L10)
## Properties
### config\_
• **config\_**: `any`
#### Defined in
[services/event-bus.js:31](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L31)
___
### enRun\_
• **enRun\_**: `undefined` \| `boolean`
#### Defined in
[services/event-bus.js:182](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L182)
___
### enqueue\_
• **enqueue\_**: `undefined` \| `Promise`<`void`\>
#### Defined in
[services/event-bus.js:183](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L183)
___
### redisClient\_
• **redisClient\_**: `any`
#### Defined in
[services/event-bus.js:51](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L51)
___
### redisSubscriber\_
• **redisSubscriber\_**: `any`
#### Defined in
[services/event-bus.js:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L52)
___
### stagedJobRepository\_
• **stagedJobRepository\_**: `any`
#### Defined in
[services/event-bus.js:39](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L39)
## Methods
### createCronJob
▸ **createCronJob**(`eventName`, `data`, `cron`, `handler`): `void`
Registers a cron job.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `eventName` | `string` | the name of the event |
| `data` | `any` | the data to be sent with the event |
| `cron` | `string` | the cron pattern |
| `handler` | `Function` | the handler to call on each cron job |
#### Returns
`void`
#### Defined in
[services/event-bus.js:280](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L280)
___
### cronWorker\_
▸ **cronWorker_**(`job`): `Promise`<`any`\>
Handles incoming jobs.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `job` | `any` | The job object |
#### Returns
`Promise`<`any`\>
resolves to the results of the subscriber calls.
#### Defined in
[services/event-bus.js:255](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L255)
___
### emit
▸ **emit**(`eventName`, `data`, `options?`): `BullJob`
Calls all subscribers when an event occurs.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `eventName` | `string` | the name of the event to be process. |
| `data` | `any` | the data to send to the subscriber. |
| `options` | `any` | options to add the job with |
#### Returns
`BullJob`
- the job from our queue
#### Defined in
[services/event-bus.js:154](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L154)
___
### enqueuer\_
▸ **enqueuer_**(): `Promise`<`void`\>
#### Returns
`Promise`<`void`\>
#### Defined in
[services/event-bus.js:191](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L191)
___
### registerCronHandler\_
▸ **registerCronHandler_**(`event`, `subscriber`): `void`
Adds a function to a list of event subscribers.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `event` | `string` | the event that the subscriber will listen for. |
| `subscriber` | `func` | the function to be called when a certain event happens. Subscribers must return a Promise. |
#### Returns
`void`
#### Defined in
[services/event-bus.js:135](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L135)
___
### sleep
▸ **sleep**(`ms`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `ms` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/event-bus.js:175](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L175)
___
### startEnqueuer
▸ **startEnqueuer**(): `Promise`<`void`\>
#### Returns
`Promise`<`void`\>
#### Defined in
[services/event-bus.js:181](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L181)
___
### stopEnqueuer
▸ **stopEnqueuer**(): `Promise`<`void`\>
#### Returns
`Promise`<`void`\>
#### Defined in
[services/event-bus.js:186](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L186)
___
### subscribe
▸ **subscribe**(`event`, `subscriber`): `void`
Adds a function to a list of event subscribers.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `event` | `string` | the event that the subscriber will listen for. |
| `subscriber` | `func` | the function to be called when a certain event happens. Subscribers must return a Promise. |
#### Returns
`void`
#### Defined in
[services/event-bus.js:98](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L98)
___
### unsubscribe
▸ **unsubscribe**(`event`, `subscriber`): `void`
Adds a function to a list of event subscribers.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `event` | `string` | the event that the subscriber will listen for. |
| `subscriber` | `func` | the function to be called when a certain event happens. Subscribers must return a Promise. |
#### Returns
`void`
#### Defined in
[services/event-bus.js:116](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L116)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`EventBusService`](EventBusService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`EventBusService`](EventBusService.md)
#### Defined in
[services/event-bus.js:69](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L69)
___
### worker\_
▸ **worker_**(`job`): `Promise`<`any`\>
Handles incoming jobs.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `job` | `any` | The job object |
#### Returns
`Promise`<`any`\>
resolves to the results of the subscriber calls.
#### Defined in
[services/event-bus.js:226](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/event-bus.js#L226)
@@ -0,0 +1,266 @@
# Class: FulfillmentProviderService
Helps retrive fulfillment providers
## Constructors
### constructor
• **new FulfillmentProviderService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `any` |
#### Defined in
[services/fulfillment-provider.js:7](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L7)
## Methods
### calculatePrice
▸ **calculatePrice**(`option`, `data`, `cart`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `option` | `any` |
| `data` | `any` |
| `cart` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:79](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L79)
___
### canCalculate
▸ **canCalculate**(`option`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `option` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:64](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L64)
___
### cancelFulfillment
▸ **cancelFulfillment**(`fulfillment`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `fulfillment` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:74](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L74)
___
### createFulfillment
▸ **createFulfillment**(`method`, `items`, `order`, `fulfillment`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `method` | `any` |
| `items` | `any` |
| `order` | `any` |
| `fulfillment` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:59](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L59)
___
### createReturn
▸ **createReturn**(`returnOrder`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `returnOrder` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:89](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L89)
___
### list
▸ **list**(): `Promise`<`any`\>
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:23](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L23)
___
### listFulfillmentOptions
▸ **listFulfillmentOptions**(`providers`): `Promise`<`any`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `providers` | `any` |
#### Returns
`Promise`<`any`[]\>
#### Defined in
[services/fulfillment-provider.js:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L30)
___
### registerInstalledProviders
▸ **registerInstalledProviders**(`providers`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `providers` | `any` |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/fulfillment-provider.js:12](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L12)
___
### retrieveDocuments
▸ **retrieveDocuments**(`providerId`, `fulfillmentData`, `documentType`): `Promise`<`any`\>
Fetches documents from the fulfillment provider
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `providerId` | `string` | the id of the provider |
| `fulfillmentData` | `any` | the data relating to the fulfillment |
| `documentType` | ``"invoice"`` \| ``"label"`` | the typ of document to fetch |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:102](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L102)
___
### retrieveProvider
▸ **retrieveProvider**(`provider_id`): `FulfillmentService`
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `provider_id` | `string` | the provider id |
#### Returns
`FulfillmentService`
the payment fulfillment provider
#### Defined in
[services/fulfillment-provider.js:48](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L48)
___
### validateFulfillmentData
▸ **validateFulfillmentData**(`option`, `data`, `cart`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `option` | `any` |
| `data` | `any` |
| `cart` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:69](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L69)
___
### validateOption
▸ **validateOption**(`option`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `option` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/fulfillment-provider.js:84](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment-provider.js#L84)
@@ -0,0 +1,234 @@
# Class: FulfillmentService
Handles Fulfillments
## Hierarchy
- `"medusa-interfaces"`
↳ **`FulfillmentService`**
## Constructors
### constructor
• **new FulfillmentService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/fulfillment.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L9)
## Methods
### cancelFulfillment
▸ **cancelFulfillment**(`fulfillmentOrId`): `Promise`<`any`\>
Cancels a fulfillment with the fulfillment provider. Will decrement the
fulfillment_quantity on the line items associated with the fulfillment.
Throws if the fulfillment has already been shipped.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `fulfillmentOrId` | `any` | the fulfillment object or id. |
#### Returns
`Promise`<`any`\>
the result of the save operation
#### Defined in
[services/fulfillment.js:223](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L223)
___
### createFulfillment
▸ **createFulfillment**(`order`, `itemsToFulfill`, `custom?`): `Fulfillment`[]
Creates an order fulfillment
If items needs to be fulfilled by different provider, we make
sure to partition those items, and create fulfillment for
those partitions.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | order to create fulfillment for |
| `itemsToFulfill` | { `item_id`: `string` ; `quantity`: `number` }[] | - |
| `custom` | `any` | potential custom values to add |
#### Returns
`Fulfillment`[]
the created fulfillments
#### Defined in
[services/fulfillment.js:171](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L171)
___
### createShipment
▸ **createShipment**(`fulfillmentId`, `trackingLinks`, `config?`): `Fulfillment`
Creates a shipment by marking a fulfillment as shipped. Adds
tracking links and potentially more metadata.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `fulfillmentId` | `Order` | the fulfillment to ship |
| `trackingLinks` | `TrackingLink`[] | tracking links for the shipment |
| `config` | `any` | potential configuration settings, such as no_notification and metadata |
#### Returns
`Fulfillment`
the shipped fulfillment
#### Defined in
[services/fulfillment.js:270](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L270)
___
### getFulfillmentItems\_
▸ **getFulfillmentItems_**(`order`, `items`, `transformer`): `Promise`<`LineItem`[]\>
Retrieves the order line items, given an array of items.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to get line items from |
| `items` | `Object` | the items to get |
| `items.item_id` | `string` | - |
| `items.quantity` | `number` | - |
| `transformer` | `Function` | a function to apply to each of the items retrieved from the order, should return a line item. If the transformer returns an undefined value the line item will be filtered from the returned array. |
#### Returns
`Promise`<`LineItem`[]\>
the line items generated by the transformer.
#### Defined in
[services/fulfillment.js:94](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L94)
___
### partitionItems\_
▸ **partitionItems_**(`shippingMethods`, `items`): { `shipping_method`: `any` = method }[]
#### Parameters
| Name | Type |
| :------ | :------ |
| `shippingMethods` | `any` |
| `items` | `any` |
#### Returns
{ `shipping_method`: `any` = method }[]
#### Defined in
[services/fulfillment.js:62](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L62)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Fulfillment`
Retrieves a fulfillment by its id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the fulfillment to retrieve |
| `config` | `any` | optional values to include with fulfillmentRepository query |
#### Returns
`Fulfillment`
the fulfillment
#### Defined in
[services/fulfillment.js:142](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L142)
___
### validateFulfillmentLineItem\_
▸ **validateFulfillmentLineItem_**(`item`, `quantity`): `LineItem`
Checks that a given quantity of a line item can be fulfilled. Fails if the
fulfillable quantity is lower than the requested fulfillment quantity.
Fulfillable quantity is calculated by subtracting the already fulfilled
quantity from the quantity that was originally purchased.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `item` | `LineItem` | the line item to check has sufficient fulfillable quantity. |
| `quantity` | `number` | the quantity that is requested to be fulfilled. |
#### Returns
`LineItem`
a line item that has the requested fulfillment quantity
set.
#### Defined in
[services/fulfillment.js:116](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L116)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`FulfillmentService`](FulfillmentService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`FulfillmentService`](FulfillmentService.md)
#### Defined in
[services/fulfillment.js:42](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/fulfillment.js#L42)
@@ -0,0 +1,245 @@
# Class: GiftCardService
Provides layer to manipulate gift cards.
## Hierarchy
- `"medusa-interfaces"`
↳ **`GiftCardService`**
## Constructors
### constructor
• **new GiftCardService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/gift-card.js:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L15)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
#### Defined in
[services/gift-card.js:11](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L11)
## Methods
### create
▸ **create**(`giftCard`): `Promise`<`GiftCard`\>
Creates a gift card with provided data given that the data is validated.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `giftCard` | `GiftCard` | the gift card data to create |
#### Returns
`Promise`<`GiftCard`\>
the result of the create operation
#### Defined in
[services/gift-card.js:134](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L134)
___
### createTransaction
▸ **createTransaction**(`data`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/gift-card.js:120](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L120)
___
### delete
▸ **delete**(`giftCardId`): `Promise`<`any`\>
Deletes a gift card idempotently
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `giftCardId` | `string` | id of gift card to delete |
#### Returns
`Promise`<`any`\>
the result of the delete operation
#### Defined in
[services/gift-card.js:288](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L288)
___
### generateCode\_
▸ **generateCode_**(): `string`
Generates a 16 character gift card code
#### Returns
`string`
the generated gift card code
#### Defined in
[services/gift-card.js:62](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L62)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the configuration used to find the objects. contains relations, skip, and take. |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/gift-card.js:78](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L78)
___
### retrieve
▸ **retrieve**(`giftCardId`, `config?`): `Promise`<`GiftCard`\>
Gets a gift card by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `giftCardId` | `string` | id of gift card to retrieve |
| `config` | `any` | optional values to include with gift card query |
#### Returns
`Promise`<`GiftCard`\>
the gift card
#### Defined in
[services/gift-card.js:175](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L175)
___
### retrieveByCode
▸ **retrieveByCode**(`code`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `code` | `any` |
| `config` | `Object` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/gift-card.js:209](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L209)
___
### update
▸ **update**(`giftCardId`, `update`): `Promise`<`any`\>
Updates a giftCard.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `giftCardId` | `string` | giftCard id of giftCard to update |
| `update` | `GiftCard` | the data to update the giftCard with |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/gift-card.js:247](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L247)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`GiftCardService`](GiftCardService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`GiftCardService`](GiftCardService.md)
#### Defined in
[services/gift-card.js:40](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/gift-card.js#L40)
@@ -0,0 +1,182 @@
# Class: IdempotencyKeyService
## Hierarchy
- `"medusa-interfaces"`
↳ **`IdempotencyKeyService`**
## Constructors
### constructor
• **new IdempotencyKeyService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/idempotency-key.js:8](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L8)
## Methods
### create
▸ **create**(`payload`): `Promise`<`IdempotencyKeyModel`\>
Creates an idempotency key for a request.
If no idempotency key is provided in request, we will create a unique
identifier.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `payload` | `any` | payload of request to create idempotency key for |
#### Returns
`Promise`<`IdempotencyKeyModel`\>
the created idempotency key
#### Defined in
[services/idempotency-key.js:55](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L55)
___
### initializeRequest
▸ **initializeRequest**(`headerKey`, `reqMethod`, `reqParams`, `reqPath`): `Promise`<`IdempotencyKeyModel`\>
Execute the initial steps in a idempotent request.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `headerKey` | `string` | potential idempotency key from header |
| `reqMethod` | `string` | method of request |
| `reqParams` | `string` | params of request |
| `reqPath` | `string` | path of request |
#### Returns
`Promise`<`IdempotencyKeyModel`\>
the existing or created idempotency key
#### Defined in
[services/idempotency-key.js:29](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L29)
___
### lock
▸ **lock**(`idempotencyKey`): `Promise`<`any`\>
Locks an idempotency.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `idempotencyKey` | `string` | key to lock |
#### Returns
`Promise`<`any`\>
result of the update operation
#### Defined in
[services/idempotency-key.js:94](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L94)
___
### retrieve
▸ **retrieve**(`idempotencyKey`): `Promise`<`IdempotencyKeyModel`\>
Retrieves an idempotency key
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `idempotencyKey` | `string` | key to retrieve |
#### Returns
`Promise`<`IdempotencyKeyModel`\>
idempotency key
#### Defined in
[services/idempotency-key.js:76](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L76)
___
### update
▸ **update**(`idempotencyKey`, `update`): `Promise`<`any`\>
Locks an idempotency.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `idempotencyKey` | `string` | key to update |
| `update` | `any` | update object |
#### Returns
`Promise`<`any`\>
result of the update operation
#### Defined in
[services/idempotency-key.js:121](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L121)
___
### workStage
▸ **workStage**(`idempotencyKey`, `func`): `IdempotencyKeyModel`
Performs an atomic work stage.
An atomic work stage contains some related functionality, that needs to be
transactionally executed in isolation. An idempotent request will
always consist of 2 or more of these phases. The required phases are
"started" and "finished".
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `idempotencyKey` | `string` | current idempotency key |
| `func` | `Function` | functionality to execute within the phase |
#### Returns
`IdempotencyKeyModel`
new updated idempotency key
#### Defined in
[services/idempotency-key.js:148](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/idempotency-key.js#L148)
@@ -0,0 +1,99 @@
# Class: InventoryService
## Hierarchy
- `"medusa-interfaces"`
↳ **`InventoryService`**
## Constructors
### constructor
• **new InventoryService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/inventory.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/inventory.js#L5)
## Methods
### adjustInventory
▸ **adjustInventory**(`variantId`, `adjustment`): `Promise`<`any`\>
Updates the inventory of a variant based on a given adjustment.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to update |
| `adjustment` | `number` | the number to adjust the inventory quantity by |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/inventory.js:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/inventory.js#L36)
___
### confirmInventory
▸ **confirmInventory**(`variantId`, `quantity`): `Promise`<`boolean`\>
Checks if the inventory of a variant can cover a given quantity. Will
return true if the variant doesn't have managed inventory or if the variant
allows backorders or if the inventory quantity is greater than `quantity`.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to check |
| `quantity` | `number` | the number of units to check availability for |
#### Returns
`Promise`<`boolean`\>
true if the inventory covers the quantity
#### Defined in
[services/inventory.js:62](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/inventory.js#L62)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`InventoryService`](InventoryService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`InventoryService`](InventoryService.md)
#### Defined in
[services/inventory.js:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/inventory.js#L15)
@@ -0,0 +1,305 @@
# Class: LineItemService
Provides layer to manipulate line items.
## Hierarchy
- `"medusa-interfaces"`
↳ **`LineItemService`**
## Constructors
### constructor
• **new LineItemService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `InjectedDependencies` |
#### Overrides
BaseService.constructor
#### Defined in
[services/line-item.ts:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L38)
## Properties
### cartRepository\_
• `Protected` `Readonly` **cartRepository\_**: typeof `CartRepository`
#### Defined in
[services/line-item.ts:32](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L32)
___
### itemTaxLineRepo\_
• `Protected` `Readonly` **itemTaxLineRepo\_**: typeof `LineItemTaxLineRepository`
#### Defined in
[services/line-item.ts:31](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L31)
___
### lineItemAdjustmentService\_
• `Protected` `Readonly` **lineItemAdjustmentService\_**: `LineItemAdjustmentService`
#### Defined in
[services/line-item.ts:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L36)
___
### lineItemRepository\_
• `Protected` `Readonly` **lineItemRepository\_**: typeof `LineItemRepository`
#### Defined in
[services/line-item.ts:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L30)
___
### manager\_
• `Protected` `Readonly` **manager\_**: `EntityManager`
#### Defined in
[services/line-item.ts:29](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L29)
___
### productService\_
• `Protected` `Readonly` **productService\_**: [`ProductService`](ProductService.md)
#### Defined in
[services/line-item.ts:34](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L34)
___
### productVariantService\_
• `Protected` `Readonly` **productVariantService\_**: [`ProductVariantService`](ProductVariantService.md)
#### Defined in
[services/line-item.ts:33](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L33)
___
### regionService\_
• `Protected` `Readonly` **regionService\_**: [`RegionService`](RegionService.md)
#### Defined in
[services/line-item.ts:35](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L35)
## Methods
### create
▸ **create**(`data`): `Promise`<`LineItem`\>
Create a line item
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `Partial`<`LineItem`\> | the line item object to create |
#### Returns
`Promise`<`LineItem`\>
the created line item
#### Defined in
[services/line-item.ts:261](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L261)
___
### createReturnLines
▸ **createReturnLines**(`returnId`, `cartId`): `Promise`<`LineItem`[]\>
Creates return line items for a given cart based on the return items in a
return.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `returnId` | `string` | the id to generate return items from. |
| `cartId` | `string` | the cart to assign the return line items to. |
#### Returns
`Promise`<`LineItem`[]\>
the created line items
#### Defined in
[services/line-item.ts:133](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L133)
___
### delete
▸ **delete**(`id`): `Promise`<`undefined` \| `LineItem`\>
Deletes a line item.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the line item to delete |
#### Returns
`Promise`<`undefined` \| `LineItem`\>
the result of the delete operation
#### Defined in
[services/line-item.ts:309](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L309)
___
### generate
▸ **generate**(`variantId`, `regionId`, `quantity`, `context?`): `Promise`<`LineItem`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `variantId` | `string` |
| `regionId` | `string` |
| `quantity` | `number` |
| `context` | `Object` |
| `context.cart?` | `Cart` |
| `context.customer_id?` | `string` |
| `context.metadata?` | `Record`<`string`, `unknown`\> |
| `context.unit_price?` | `number` |
#### Returns
`Promise`<`LineItem`\>
#### Defined in
[services/line-item.ts:186](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L186)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`LineItem`[]\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `selector` | `any` | `undefined` |
| `config` | `Object` | `undefined` |
| `config.order` | `Object` | `undefined` |
| `config.order.created_at` | `string` | `"DESC"` |
| `config.skip` | `number` | `0` |
| `config.take` | `number` | `50` |
#### Returns
`Promise`<`LineItem`[]\>
#### Defined in
[services/line-item.ts:81](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L81)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`LineItem`\>
Retrieves a line item by its id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the line item to retrieve |
| `config` | `Object` | the config to be used at query building |
#### Returns
`Promise`<`LineItem`\>
the line item
#### Defined in
[services/line-item.ts:102](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L102)
___
### update
▸ **update**(`id`, `data`): `Promise`<`LineItem`\>
Updates a line item
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the line item to update |
| `data` | `Partial`<`LineItem`\> | the properties to update on line item |
#### Returns
`Promise`<`LineItem`\>
the update line item
#### Defined in
[services/line-item.ts:280](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L280)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`LineItemService`](LineItemService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`LineItemService`](LineItemService.md)
#### Defined in
[services/line-item.ts:60](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/line-item.ts#L60)
@@ -0,0 +1,248 @@
# Class: MiddlewareService
Orchestrates dynamic middleware registered through the Medusa Middleware API
## Constructors
### constructor
• **new MiddlewareService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `any` |
#### Defined in
[services/middleware.js:7](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L7)
## Properties
### postAuthentication\_
• **postAuthentication\_**: `any`[]
#### Defined in
[services/middleware.js:8](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L8)
___
### preAuthentication\_
• **preAuthentication\_**: `any`[]
#### Defined in
[services/middleware.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L9)
___
### preCartCreation\_
• **preCartCreation\_**: `any`[]
#### Defined in
[services/middleware.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L10)
___
### routers
• **routers**: `Object`
#### Defined in
[services/middleware.js:11](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L11)
## Methods
### addPostAuthentication
▸ **addPostAuthentication**(`middleware`, `options`): `void`
Adds a middleware function to be called after authentication is completed.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `middleware` | `Function` | the middleware function. Should return a middleware function. |
| `options` | `any` | the arguments that will be passed to the middleware |
#### Returns
`void`
#### Defined in
[services/middleware.js:45](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L45)
___
### addPreAuthentication
▸ **addPreAuthentication**(`middleware`, `options`): `void`
Adds a middleware function to be called before authentication is completed.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `middleware` | `Function` | the middleware function. Should return a middleware function. |
| `options` | `any` | the arguments that will be passed to the middleware |
#### Returns
`void`
#### Defined in
[services/middleware.js:61](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L61)
___
### addPreCartCreation
▸ **addPreCartCreation**(`middleware`): `void`
Adds a middleware function to be called before cart creation
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `middleware` | `Function` | the middleware function. Should return a middleware function. |
#### Returns
`void`
#### Defined in
[services/middleware.js:75](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L75)
___
### addRouter
▸ **addRouter**(`path`, `router`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `path` | `any` |
| `router` | `any` |
#### Returns
`void`
#### Defined in
[services/middleware.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L14)
___
### getRouters
▸ **getRouters**(`path`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `path` | `any` |
#### Returns
`any`
#### Defined in
[services/middleware.js:19](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L19)
___
### usePostAuthentication
▸ **usePostAuthentication**(`app`): `void`
Adds post authentication middleware to an express app.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `app` | `ExpressApp` | the express app to add the middleware to |
#### Returns
`void`
#### Defined in
[services/middleware.js:85](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L85)
___
### usePreAuthentication
▸ **usePreAuthentication**(`app`): `void`
Adds pre authentication middleware to an express app.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `app` | `ExpressApp` | the express app to add the middleware to |
#### Returns
`void`
#### Defined in
[services/middleware.js:96](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L96)
___
### usePreCartCreation
▸ **usePreCartCreation**(): `any`[]
#### Returns
`any`[]
#### Defined in
[services/middleware.js:102](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L102)
___
### validateMiddleware\_
▸ **validateMiddleware_**(`fn`): `void`
Validates a middleware function, throws if fn is not of type function.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `fn` | `Function` | the middleware function to validate. |
#### Returns
`void`
#### Defined in
[services/middleware.js:28](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/middleware.js#L28)
@@ -0,0 +1,194 @@
# Class: NoteService
## Hierarchy
- `"medusa-interfaces"`
↳ **`NoteService`**
## Constructors
### constructor
• **new NoteService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/note.js:12](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L12)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `DELETED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/note.js:6](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L6)
## Methods
### create
▸ **create**(`data`, `config?`): `Promise`<`any`\>
Creates a note associated with a given author
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `CreateNoteInput` | the note to create |
| `config` | `any` | any configurations if needed, including meta data |
#### Returns
`Promise`<`any`\>
resolves to the creation result
#### Defined in
[services/note.js:98](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L98)
___
### delete
▸ **delete**(`noteId`): `Promise`<`any`\>
Deletes a given note
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `noteId` | `any` | id of the note to delete |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/note.js:154](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L154)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`Note`[]\>
Fetches all notes related to the given selector
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `Object` | the configuration used to find the objects. contains relations, skip, and take. |
| `config.relations` | `string`[] | Which relations to include in the resulting list of Notes. |
| `config.skip` | `number` | How many Notes to skip in the resulting list of Notes. |
| `config.take` | `number` | How many Notes to take in the resulting list of Notes. |
#### Returns
`Promise`<`Note`[]\>
notes related to the given search.
#### Defined in
[services/note.js:77](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L77)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`Note`\>
Retrieves a specific note.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the note to retrieve. |
| `config` | `any` | any options needed to query for the result. |
#### Returns
`Promise`<`Note`\>
which resolves to the requested note.
#### Defined in
[services/note.js:51](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L51)
___
### update
▸ **update**(`noteId`, `value`): `Promise`<`any`\>
Updates a given note with a new value
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `noteId` | `any` | the id of the note to update |
| `value` | `any` | the new value |
#### Returns
`Promise`<`any`\>
resolves to the updated element
#### Defined in
[services/note.js:131](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L131)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`NoteService`](NoteService.md)
Sets the service's manager to a given transaction manager
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `transactionManager` | `EntityManager` | the manager to use |
#### Returns
[`NoteService`](NoteService.md)
a cloned note service
#### Defined in
[services/note.js:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/note.js#L30)
@@ -0,0 +1,326 @@
# Class: NotificationService
Provides layer to manipulate orchestrate notifications.
## Hierarchy
- `"medusa-interfaces"`
↳ **`NotificationService`**
## Constructors
### constructor
• **new NotificationService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `any` |
#### Overrides
BaseService.constructor
#### Defined in
[services/notification.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L9)
## Properties
### attachmentGenerator\_
• **attachmentGenerator\_**: `any`
#### Defined in
[services/notification.js:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L30)
___
### container\_
• **container\_**: `any`
#### Defined in
[services/notification.js:19](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L19)
___
### logger\_
• **logger\_**: `any`
#### Defined in
[services/notification.js:23](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L23)
___
### notificationProviderRepository\_
• **notificationProviderRepository\_**: `any`
#### Defined in
[services/notification.js:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L27)
___
### subscribers\_
• **subscribers\_**: `Object`
#### Defined in
[services/notification.js:29](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L29)
## Methods
### handleEvent
▸ **handleEvent**(`eventName`, `data`): `Promise`<`any`\>
Handles an event by relaying the event data to the subscribing providers.
The result of the notification send will be persisted in the database in
order to allow for resends. Will log any errors that are encountered.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `eventName` | `string` | the event to handle |
| `data` | `any` | the data the event was sent with |
#### Returns
`Promise`<`any`\>
- the result of notification subscribed
#### Defined in
[services/notification.js:166](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L166)
___
### list
▸ **list**(`selector`, `config?`): `Notification`[]
Retrieves a list of notifications.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the params to select the notifications by. |
| `config` | `any` | the configuration to apply to the query |
#### Returns
`Notification`[]
the notifications that satisfy the query.
#### Defined in
[services/notification.js:84](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L84)
___
### registerAttachmentGenerator
▸ **registerAttachmentGenerator**(`service`): `void`
Registers an attachment generator to the service. The generator can be
used to generate on demand invoices or other documents.
#### Parameters
| Name | Type |
| :------ | :------ |
| `service` | `any` |
#### Returns
`void`
#### Defined in
[services/notification.js:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L38)
___
### registerInstalledProviders
▸ **registerInstalledProviders**(`providers`): `Promise`<`void`\>
Takes a list of notification provider ids and persists them in the database.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `providers` | `string`[] | a list of provider ids |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/notification.js:68](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L68)
___
### resend
▸ **resend**(`id`, `config?`): `Notification`
Resends a notification by retrieving a prior notification and calling the
underlying provider's resendNotification method.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the notification |
| `config` | `any` | any configuration that might override the previous send |
#### Returns
`Notification`
the newly created notification
#### Defined in
[services/notification.js:237](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L237)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Notification`
Retrieves a notification with a given id
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the notification |
| `config` | `any` | the configuration to apply to the query |
#### Returns
`Notification`
the notification
#### Defined in
[services/notification.js:101](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L101)
___
### retrieveProvider\_
▸ **retrieveProvider_**(`id`): `NotificationProvider`
Finds a provider with a given id. Will throw a NOT_FOUND error if the
resolution fails.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the provider |
#### Returns
`NotificationProvider`
the notification provider
#### Defined in
[services/notification.js:147](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L147)
___
### send
▸ **send**(`event`, `eventData`, `providerId`): `Notification`
Sends a notification, by calling the given provider's sendNotification
method. Persists the Notification in the database.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `event` | `string` | the name of the event |
| `eventData` | `any` | the data the event was sent with |
| `providerId` | `string` | the provider that should hande the event. |
#### Returns
`Notification`
the created notification
#### Defined in
[services/notification.js:195](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L195)
___
### subscribe
▸ **subscribe**(`eventName`, `providerId`): `void`
Subscribes a given provider to an event.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `eventName` | `string` | the event to subscribe to |
| `providerId` | `string` | the provider that the event will be sent to |
#### Returns
`void`
#### Defined in
[services/notification.js:126](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L126)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`NotificationService`](NotificationService.md)
Sets the service's manager to a given transaction manager.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `transactionManager` | `EntityManager` | the manager to use |
#### Returns
[`NotificationService`](NotificationService.md)
a cloned notification service
#### Defined in
[services/notification.js:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/notification.js#L47)
@@ -0,0 +1,227 @@
# Class: OauthService
## Hierarchy
- `"medusa-interfaces"`
↳ **`OauthService`**
## Constructors
### constructor
• **new OauthService**(`cradle`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `cradle` | `any` |
#### Overrides
OauthService.constructor
#### Defined in
[services/oauth.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L10)
## Properties
### container\_
• **container\_**: `any`
#### Defined in
[services/oauth.js:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L15)
___
### eventBus\_
• **eventBus\_**: `any`
#### Defined in
[services/oauth.js:17](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L17)
___
### manager
• **manager**: `any`
#### Defined in
[services/oauth.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L14)
___
### oauthRepository\_
• **oauthRepository\_**: `any`
#### Defined in
[services/oauth.js:16](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L16)
___
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `TOKEN_GENERATED` | `string` |
| `TOKEN_REFRESHED` | `string` |
#### Defined in
[services/oauth.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L5)
## Methods
### create
▸ **create**(`data`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/oauth.js:32](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L32)
___
### generateToken
▸ **generateToken**(`appName`, `code`, `state`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `appName` | `any` |
| `code` | `any` |
| `state` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/oauth.js:66](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L66)
___
### list
▸ **list**(`selector`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `selector` | `any` |
#### Returns
`any`
#### Defined in
[services/oauth.js:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L27)
___
### refreshToken
▸ **refreshToken**(`appName`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `appName` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/oauth.js:96](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L96)
___
### registerOauthApp
▸ **registerOauthApp**(`appDetails`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `appDetails` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/oauth.js:56](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L56)
___
### retrieveByName
▸ **retrieveByName**(`appName`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `appName` | `any` |
#### Returns
`any`
#### Defined in
[services/oauth.js:20](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L20)
___
### update
▸ **update**(`id`, `update`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
| `update` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/oauth.js:45](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/oauth.js#L45)
@@ -0,0 +1,759 @@
# Class: OrderService
## Hierarchy
- `"medusa-interfaces"`
↳ **`OrderService`**
## Constructors
### constructor
• **new OrderService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/order.js:25](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L25)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CANCELED` | `string` |
| `COMPLETED` | `string` |
| `FULFILLMENT_CANCELED` | `string` |
| `FULFILLMENT_CREATED` | `string` |
| `GIFT_CARD_CREATED` | `string` |
| `ITEMS_RETURNED` | `string` |
| `PAYMENT_CAPTURED` | `string` |
| `PAYMENT_CAPTURE_FAILED` | `string` |
| `PLACED` | `string` |
| `REFUND_CREATED` | `string` |
| `REFUND_FAILED` | `string` |
| `RETURN_ACTION_REQUIRED` | `string` |
| `RETURN_REQUESTED` | `string` |
| `SHIPMENT_CREATED` | `string` |
| `SWAP_CREATED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/order.js:6](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L6)
## Methods
### addShippingMethod
▸ **addShippingMethod**(`orderId`, `optionId`, `data`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `orderId` | `any` |
| `optionId` | `any` |
| `data` | `any` |
| `config` | `Object` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/order.js:806](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L806)
___
### archive
▸ **archive**(`orderId`): `Promise`<`any`\>
Archives an order. It only alloved, if the order has been fulfilled
and payment has been captured.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the order to archive |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/order.js:1301](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1301)
___
### cancel
▸ **cancel**(`orderId`): `Promise`<`any`\>
Cancels an order.
Throws if fulfillment process has been initiated.
Throws if payment process has been initiated.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of order to cancel. |
#### Returns
`Promise`<`any`\>
result of the update operation.
#### Defined in
[services/order.js:952](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L952)
___
### cancelFulfillment
▸ **cancelFulfillment**(`fulfillmentId`): `Promise`<`any`\>
Cancels a fulfillment (if related to an order)
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `fulfillmentId` | `string` | the ID of the fulfillment to cancel |
#### Returns
`Promise`<`any`\>
updated order
#### Defined in
[services/order.js:1242](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1242)
___
### capturePayment
▸ **capturePayment**(`orderId`): `Promise`<`any`\>
Captures payment for an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of order to capture payment for. |
#### Returns
`Promise`<`any`\>
result of the update operation.
#### Defined in
[services/order.js:1021](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1021)
___
### completeOrder
▸ **completeOrder**(`orderId`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of the order to complete |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/order.js:429](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L429)
___
### create
▸ **create**(`data`): `Promise`<`any`\>
Creates an order
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `any` | the data to create an order |
#### Returns
`Promise`<`any`\>
resolves to the creation result.
#### Defined in
[services/order.js:723](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L723)
___
### createFromCart
▸ **createFromCart**(`cartId`): `Promise`<`any`\>
Creates an order from a cart
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartId` | `string` | id of the cart to create an order from |
#### Returns
`Promise`<`any`\>
resolves to the creation result.
#### Defined in
[services/order.js:465](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L465)
___
### createFulfillment
▸ **createFulfillment**(`orderId`, `itemsToFulfill`, `config?`): `Promise`<`any`\>
Creates fulfillments for an order.
In a situation where the order has more than one shipping method,
we need to partition the order items, such that they can be sent
to their respective fulfillment provider.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of order to cancel. |
| `itemsToFulfill` | `any` | items to fulfil. |
| `config` | `any` | the config to cancel. |
#### Returns
`Promise`<`any`\>
result of the update operation.
#### Defined in
[services/order.js:1121](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1121)
___
### createRefund
▸ **createRefund**(`orderId`, `refundAmount`, `reason`, `note`, `config?`): `Promise`<`any`\>
Refunds a given amount back to the customer.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of the order to refund. |
| `refundAmount` | `float` | the amount to refund. |
| `reason` | `string` | the reason to refund. |
| `note` | `undefined` \| `string` | note for refund. |
| `config` | `any` | the config for refund. |
#### Returns
`Promise`<`any`\>
the result of the refund operation.
#### Defined in
[services/order.js:1328](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1328)
___
### createShipment
▸ **createShipment**(`orderId`, `fulfillmentId`, `trackingLinks`, `config?`): `order`
Adds a shipment to the order to indicate that an order has left the
warehouse. Will ask the fulfillment provider for any documents that may
have been created in regards to the shipment.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the id of the order that has been shipped |
| `fulfillmentId` | `string` | the fulfillment that has now been shipped |
| `trackingLinks` | `undefined` \| `TrackingLink`[] | array of tracking numebers associated with the shipment |
| `config` | `any` | the config of the order that has been shipped |
#### Returns
`order`
the resulting order following the update.
#### Defined in
[services/order.js:643](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L643)
___
### decorateTotals\_
▸ **decorateTotals_**(`order`, `totalsFields?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `order` | `any` | `undefined` |
| `totalsFields` | `any`[] | `[]` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/order.js:1377](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1377)
___
### deleteMetadata
▸ **deleteMetadata**(`orderId`, `key`): `Promise`<`any`\>
Dedicated method to delete metadata for an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the order to delete metadata from. |
| `key` | `string` | key for metadata field |
#### Returns
`Promise`<`any`\>
resolves to the updated result.
#### Defined in
[services/order.js:1550](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1550)
___
### existsByCartId
▸ **existsByCartId**(`cartId`): `Promise`<`Order`\>
Checks the existence of an order by cart id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartId` | `string` | cart id to find order |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/order.js:417](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L417)
___
### getFulfillmentItems\_
▸ **getFulfillmentItems_**(`order`, `items`, `transformer`): `Promise`<`LineItem`[]\>
Retrieves the order line items, given an array of items.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to get line items from |
| `items` | `Object` | the items to get |
| `items.item_id` | `string` | - |
| `items.quantity` | `number` | - |
| `transformer` | `Function` | a function to apply to each of the items retrieved from the order, should return a line item. If the transformer returns an undefined value the line item will be filtered from the returned array. |
#### Returns
`Promise`<`LineItem`[]\>
the line items generated by the transformer.
#### Defined in
[services/order.js:1284](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1284)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config to be used for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/order.js:148](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L148)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<`any`[]\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `selector` | `any` | `undefined` |
| `config` | `Object` | `undefined` |
| `config.order` | `Object` | `undefined` |
| `config.order.created_at` | `string` | `"DESC"` |
| `config.skip` | `number` | `0` |
| `config.take` | `number` | `50` |
#### Returns
`Promise`<`any`[]\>
#### Defined in
[services/order.js:173](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L173)
___
### registerReturnReceived
▸ **registerReturnReceived**(`orderId`, `receivedReturn`, `customRefundAmount`): `Promise`<`any`\>
Handles receiving a return. This will create a
refund to the customer. If the returned items don't match the requested
items the return status will be updated to requires_action. This behaviour
is useful in sitautions where a custom refund amount is requested, but the
retuned items are not matching the requested items. Setting the
allowMismatch argument to true, will process the return, ignoring any
mismatches.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the order to return. |
| `receivedReturn` | `any` | the received return |
| `customRefundAmount` | `float` | the custom refund amount return |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/order.js:1473](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1473)
___
### retrieve
▸ **retrieve**(`orderId`, `config?`): `Promise`<`Order`\>
Gets an order by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | id of order to retrieve |
| `config` | `any` | config of order to retrieve |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/order.js:305](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L305)
___
### retrieveByCartId
▸ **retrieveByCartId**(`cartId`, `config?`): `Promise`<`Order`\>
Gets an order by cart id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartId` | `string` | cart id to find order |
| `config` | `any` | the config to be used to find order |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/order.js:343](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L343)
___
### retrieveByExternalId
▸ **retrieveByExternalId**(`externalId`, `config?`): `Promise`<`Order`\>
Gets an order by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `externalId` | `string` | id of order to retrieve |
| `config` | `any` | query config to get order by |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/order.js:380](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L380)
___
### transformQueryForTotals\_
▸ **transformQueryForTotals_**(`config`): { `relations`: `any` ; `select`: `any` ; `totalsToSelect`: `never`[] = [] } \| { `relations`: `any` ; `select`: `any`[] = toSelect; `totalsToSelect`: `any` }
#### Parameters
| Name | Type |
| :------ | :------ |
| `config` | `any` |
#### Returns
{ `relations`: `any` ; `select`: `any` ; `totalsToSelect`: `never`[] = [] } \| { `relations`: `any` ; `select`: `any`[] = toSelect; `totalsToSelect`: `any` }
#### Defined in
[services/order.js:234](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L234)
___
### update
▸ **update**(`orderId`, `update`): `Promise`<`any`\>
Updates an order. Metadata updates should
use dedicated method, e.g. `setMetadata` etc. The function
will throw errors if metadata updates are attempted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderId` | `string` | the id of the order. Must be a string that can be casted to an ObjectId |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/order.js:864](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L864)
___
### updateBillingAddress\_
▸ **updateBillingAddress_**(`order`, `address`): `Promise`<`any`\>
Updates the order's billing address.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `any` | the order to update |
| `address` | `any` | the value to set the billing address to |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/order.js:744](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L744)
___
### updateShippingAddress\_
▸ **updateShippingAddress_**(`order`, `address`): `Promise`<`any`\>
Updates the order's shipping address.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `any` | the order to update |
| `address` | `any` | the value to set the shipping address to |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/order.js:779](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L779)
___
### validateFulfillmentLineItem\_
▸ **validateFulfillmentLineItem_**(`item`, `quantity`): `LineItem`
Checks that a given quantity of a line item can be fulfilled. Fails if the
fulfillable quantity is lower than the requested fulfillment quantity.
Fulfillable quantity is calculated by subtracting the already fulfilled
quantity from the quantity that was originally purchased.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `item` | `LineItem` | the line item to check has sufficient fulfillable quantity. |
| `quantity` | `number` | the quantity that is requested to be fulfilled. |
#### Returns
`LineItem`
a line item that has the requested fulfillment quantity
set.
#### Defined in
[services/order.js:1091](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L1091)
___
### validateId\_
▸ **validateId_**(`rawId`): `string`
Used to validate order ids. Throws an error if the cast fails
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `rawId` | `string` | the raw order id to validate. |
#### Returns
`string`
the validated id
#### Defined in
[services/order.js:139](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L139)
___
### withTransaction
▸ **withTransaction**(`manager`): [`OrderService`](OrderService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `manager` | `any` |
#### Returns
[`OrderService`](OrderService.md)
#### Defined in
[services/order.js:102](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/order.js#L102)
@@ -0,0 +1,497 @@
# Class: PaymentProviderService
Helps retrive payment providers
## Hierarchy
- `"medusa-interfaces"`
↳ **`PaymentProviderService`**
## Constructors
### constructor
• **new PaymentProviderService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `any` |
#### Overrides
BaseService.constructor
#### Defined in
[services/payment-provider.js:8](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L8)
## Properties
### manager\_
• **manager\_**: `any`
#### Defined in
[services/payment-provider.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L14)
___
### paymentRepository\_
• **paymentRepository\_**: `any`
#### Defined in
[services/payment-provider.js:18](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L18)
___
### paymentSessionRepository\_
• **paymentSessionRepository\_**: `any`
#### Defined in
[services/payment-provider.js:16](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L16)
___
### refundRepository\_
• **refundRepository\_**: `any`
#### Defined in
[services/payment-provider.js:20](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L20)
## Methods
### authorizePayment
▸ **authorizePayment**(`paymentSession`, `context`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `paymentSession` | `any` |
| `context` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:283](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L283)
___
### cancelPayment
▸ **cancelPayment**(`paymentObj`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `paymentObj` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:324](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L324)
___
### capturePayment
▸ **capturePayment**(`paymentObj`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `paymentObj` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:343](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L343)
___
### createPayment
▸ **createPayment**(`cart`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `cart` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:246](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L246)
___
### createSession
▸ **createSession**(`providerId`, `cart`): `Promise`<`any`\>
Creates a payment session with the given provider.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `providerId` | `string` | the id of the provider to create payment with |
| `cart` | `Cart` | a cart object used to calculate the amount, etc. from |
#### Returns
`Promise`<`any`\>
the payment session
#### Defined in
[services/payment-provider.js:121](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L121)
___
### deleteSession
▸ **deleteSession**(`paymentSession`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `paymentSession` | `any` |
#### Returns
`any`
#### Defined in
[services/payment-provider.js:202](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L202)
___
### getStatus
▸ **getStatus**(`payment`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `payment` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:338](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L338)
___
### list
▸ **list**(): `Promise`<`any`\>
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L47)
___
### listPayments
▸ **listPayments**(`selector`, `config?`): `any`
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `selector` | `any` | `undefined` |
| `config` | `Object` | `undefined` |
| `config.order` | `Object` | `undefined` |
| `config.order.created_at` | `string` | `"DESC"` |
| `config.skip` | `number` | `0` |
| `config.take` | `number` | `50` |
#### Returns
`any`
#### Defined in
[services/payment-provider.js:80](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L80)
___
### refreshSession
▸ **refreshSession**(`paymentSession`, `cart`): `Promise`<`any`\>
Refreshes a payment session with the given provider.
This means, that we delete the current one and create a new.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `paymentSession` | `PaymentSession` | the payment session object to update |
| `cart` | `Cart` | a cart object used to calculate the amount, etc. from |
#### Returns
`Promise`<`any`\>
the payment session
#### Defined in
[services/payment-provider.js:152](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L152)
___
### refundPayment
▸ **refundPayment**(`payObjs`, `amount`, `reason`, `note`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `payObjs` | `any` |
| `amount` | `any` |
| `reason` | `any` |
| `note` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:358](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L358)
___
### registerInstalledProviders
▸ **registerInstalledProviders**(`providers`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `providers` | `any` |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/payment-provider.js:35](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L35)
___
### retrievePayment
▸ **retrievePayment**(`id`, `relations?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `any` | `undefined` |
| `relations` | `any`[] | `[]` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:54](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L54)
___
### retrieveProvider
▸ **retrieveProvider**(`providerId`): `PaymentService`
Finds a provider given an id
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `providerId` | `string` | the id of the provider to get |
#### Returns
`PaymentService`
the payment provider
#### Defined in
[services/payment-provider.js:228](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L228)
___
### retrieveRefund
▸ **retrieveRefund**(`id`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
| `config` | `Object` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:422](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L422)
___
### retrieveSession
▸ **retrieveSession**(`id`, `relations?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `any` | `undefined` |
| `relations` | `any`[] | `[]` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:89](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L89)
___
### updatePayment
▸ **updatePayment**(`paymentId`, `update`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `paymentId` | `any` |
| `update` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:266](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L266)
___
### updateSession
▸ **updateSession**(`paymentSession`, `cart`): `Promise`<`any`\>
Updates an existing payment session.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `paymentSession` | `PaymentSession` | the payment session object to update |
| `cart` | `Cart` | the cart object to update for |
#### Returns
`Promise`<`any`\>
the updated payment session
#### Defined in
[services/payment-provider.js:188](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L188)
___
### updateSessionData
▸ **updateSessionData**(`paySession`, `update`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `paySession` | `any` |
| `update` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/payment-provider.js:308](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L308)
___
### withTransaction
▸ **withTransaction**(`manager`): [`PaymentProviderService`](PaymentProviderService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `manager` | `any` |
#### Returns
[`PaymentProviderService`](PaymentProviderService.md)
#### Defined in
[services/payment-provider.js:23](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/payment-provider.js#L23)
@@ -0,0 +1,264 @@
# Class: ProductCollectionService
Provides layer to manipulate product collections.
## Hierarchy
- `"medusa-interfaces"`
↳ **`ProductCollectionService`**
## Constructors
### constructor
• **new ProductCollectionService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/product-collection.js:11](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L11)
## Methods
### addProducts
▸ **addProducts**(`collectionId`, `productIds`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `collectionId` | `any` |
| `productIds` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product-collection.js:170](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L170)
___
### create
▸ **create**(`collection`): `Promise`<`ProductCollection`\>
Creates a product collection
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `collection` | `any` | the collection to create |
#### Returns
`Promise`<`ProductCollection`\>
created collection
#### Defined in
[services/product-collection.js:104](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L104)
___
### delete
▸ **delete**(`collectionId`): `Promise`<`any`\>
Deletes a product collection idempotently
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `collectionId` | `string` | id of collection to delete |
#### Returns
`Promise`<`any`\>
empty promise
#### Defined in
[services/product-collection.js:152](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L152)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`any`\>
Lists product collections
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config to be used for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/product-collection.js:206](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L206)
___
### listAndCount
▸ **listAndCount**(`selector?`, `config?`): `Promise`<`any`\>
Lists product collections and add count.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config to be used for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/product-collection.js:221](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L221)
___
### removeProducts
▸ **removeProducts**(`collectionId`, `productIds`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `collectionId` | `any` |
| `productIds` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product-collection.js:188](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L188)
___
### retrieve
▸ **retrieve**(`collectionId`, `config?`): `Promise`<`ProductCollection`\>
Retrieves a product collection by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `collectionId` | `string` | the id of the collection to retrieve. |
| `config` | `any` | the config of the collection to retrieve. |
#### Returns
`Promise`<`ProductCollection`\>
the collection.
#### Defined in
[services/product-collection.js:55](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L55)
___
### retrieveByHandle
▸ **retrieveByHandle**(`collectionHandle`, `config?`): `Promise`<`ProductCollection`\>
Retrieves a product collection by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `collectionHandle` | `string` | the handle of the collection to retrieve. |
| `config` | `any` | query config for request |
#### Returns
`Promise`<`ProductCollection`\>
the collection.
#### Defined in
[services/product-collection.js:81](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L81)
___
### update
▸ **update**(`collectionId`, `update`): `Promise`<`ProductCollection`\>
Updates a product collection
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `collectionId` | `string` | id of collection to update |
| `update` | `any` | update object |
#### Returns
`Promise`<`ProductCollection`\>
update collection
#### Defined in
[services/product-collection.js:125](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L125)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ProductCollectionService`](ProductCollectionService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`ProductCollectionService`](ProductCollectionService.md)
#### Defined in
[services/product-collection.js:32](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-collection.js#L32)
@@ -0,0 +1,662 @@
# Class: ProductService
Provides layer to manipulate products.
## Hierarchy
- `"medusa-interfaces"`
↳ **`ProductService`**
## Constructors
### constructor
• **new ProductService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/product.js:19](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L19)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `DELETED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/product.js:13](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L13)
___
### IndexName
▪ `Static` **IndexName**: `string`
#### Defined in
[services/product.js:12](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L12)
## Methods
### addOption
▸ **addOption**(`productId`, `optionTitle`): `Promise`<`any`\>
Adds an option to a product. Options can, for example, be "Size", "Color",
etc. Will update all the products variants with a dummy value for the newly
created option. The same option cannot be added more than once.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product to apply the new option to |
| `optionTitle` | `string` | the display title of the option, e.g. "Size" |
#### Returns
`Promise`<`any`\>
the result of the model update operation
#### Defined in
[services/product.js:707](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L707)
___
### count
▸ **count**(`selector?`): `Promise`<`any`\>
Return the total number of documents in database
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the selector to choose products by |
#### Returns
`Promise`<`any`\>
the result of the count operation
#### Defined in
[services/product.js:223](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L223)
___
### create
▸ **create**(`productObject`): `Promise`<`any`\>
Creates a product.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productObject` | `any` | the product to create |
#### Returns
`Promise`<`any`\>
resolves to the creation result.
#### Defined in
[services/product.js:483](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L483)
___
### decorate
▸ **decorate**(`productId`, `fields?`, `expandFields?`, `config?`): `Product`
Decorates a product with product variants.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `productId` | `string` | `undefined` | the productId to decorate. |
| `fields` | `string`[] | `[]` | the fields to include. |
| `expandFields` | `string`[] | `[]` | fields to expand. |
| `config` | `any` | `{}` | retrieve config for price calculation. |
#### Returns
`Product`
return the decorated product.
#### Defined in
[services/product.js:945](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L945)
___
### delete
▸ **delete**(`productId`): `Promise`<`any`\>
Deletes a product from a given product id. The product's associated
variants will also be deleted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the id of the product to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<`any`\>
empty promise
#### Defined in
[services/product.js:673](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L673)
___
### deleteOption
▸ **deleteOption**(`productId`, `optionId`): `Promise`<`any`\>
Delete an option from a product.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product to delete an option from |
| `optionId` | `string` | the option to delete |
#### Returns
`Promise`<`any`\>
the updated product
#### Defined in
[services/product.js:881](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L881)
___
### getFreeTextQueryBuilder\_
▸ **getFreeTextQueryBuilder_**(`productRepo`, `query`, `q`): `QueryBuilder`<`Product`\>
Creates a QueryBuilder that can fetch products based on free text.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productRepo` | `ProductRepository` | an instance of a ProductRepositry |
| `query` | `FindOptions`<`Product`\> | the query to get products by |
| `q` | `string` | the text to perform free text search from |
#### Returns
`QueryBuilder`<`Product`\>
a query builder that can fetch products
#### Defined in
[services/product.js:1014](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L1014)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`Product`[]\>
Lists products based on the provided parameters.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | an object that defines rules to filter products by |
| `config` | `any` | object that defines the scope for what should be returned |
#### Returns
`Promise`<`Product`[]\>
the result of the find operation
#### Defined in
[services/product.js:109](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L109)
___
### listAndCount
▸ **listAndCount**(`selector?`, `config?`): `Promise`<[`Product`[], `number`]\>
Lists products based on the provided parameters and includes the count of
products that match the query.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | an object that defines rules to filter products by |
| `config` | `any` | object that defines the scope for what should be returned |
#### Returns
`Promise`<[`Product`[], `number`]\>
an array containing the products as
the first element and the total count of products that matches the query
as the second element.
#### Defined in
[services/product.js:164](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L164)
___
### listTagsByUsage
▸ **listTagsByUsage**(`count?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `count` | `number` | `10` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product.js:412](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L412)
___
### listTypes
▸ **listTypes**(): `Promise`<`any`\>
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product.js:404](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L404)
___
### prepareListQuery\_
▸ **prepareListQuery_**(`selector`, `config`): `any`
Creates a query object to be used for list queries.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the selector to create the query from |
| `config` | `any` | the config to use for the query |
#### Returns
`any`
an object containing the query, relations and free-text
search param.
#### Defined in
[services/product.js:980](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L980)
___
### reorderOptions
▸ **reorderOptions**(`productId`, `optionOrder`): `Promise`<`any`\>
Changes the order of a product's options. Will throw if the length of
optionOrder and the length of the product's options are different. Will
throw optionOrder contains an id not associated with the product.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product whose options we are reordering |
| `optionOrder` | `string`[] | the ids of the product's options in the new order |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/product.js:790](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L790)
___
### reorderVariants
▸ **reorderVariants**(`productId`, `variantOrder`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `productId` | `any` |
| `variantOrder` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product.js:746](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L746)
___
### retrieve
▸ **retrieve**(`productId`, `config?`): `Promise`<`Product`\>
Gets a product by id.
Throws in case of DB Error and if product was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | id of the product to get. |
| `config` | `any` | object that defines what should be included in the query response |
#### Returns
`Promise`<`Product`\>
the result of the find one operation.
#### Defined in
[services/product.js:239](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L239)
___
### retrieveByExternalId
▸ **retrieveByExternalId**(`externalId`, `config?`): `Promise`<`Product`\>
Gets a product by external id.
Throws in case of DB Error and if product was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `externalId` | `string` | handle of the product to get. |
| `config` | `any` | details about what to get from the product |
#### Returns
`Promise`<`Product`\>
the result of the find one operation.
#### Defined in
[services/product.js:342](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L342)
___
### retrieveByHandle
▸ **retrieveByHandle**(`productHandle`, `config?`): `Promise`<`Product`\>
Gets a product by handle.
Throws in case of DB Error and if product was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productHandle` | `string` | handle of the product to get. |
| `config` | `any` | details about what to get from the product |
#### Returns
`Promise`<`Product`\>
the result of the find one operation.
#### Defined in
[services/product.js:291](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L291)
___
### retrieveVariants
▸ **retrieveVariants**(`productId`, `config?`): `Promise`<`any`\>
Gets all variants belonging to a product.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the id of the product to get variants from. |
| `config` | `FindConfig`<`Product`\> | The config to select and configure relations etc... |
#### Returns
`Promise`<`any`\>
an array of variants
#### Defined in
[services/product.js:392](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L392)
___
### setAdditionalPrices
▸ **setAdditionalPrices**(`products`, `currency_code`, `region_id`, `cart_id`, `customer_id`, `include_discount_prices?`): `Promise`<`Product`[]\>
Set additional prices on a list of products.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `products` | `any` | `undefined` | list of products on which to set additional prices |
| `currency_code` | `string` | `undefined` | currency code to fetch prices for |
| `region_id` | `string` | `undefined` | region to fetch prices for |
| `cart_id` | `string` | `undefined` | string of cart to use as a basis for getting currency and region |
| `customer_id` | `string` | `undefined` | id of potentially logged in customer, used to get prices valid for their customer groups |
| `include_discount_prices` | `boolean` | `false` | indication wether or not to include sales prices in result |
#### Returns
`Promise`<`Product`[]\>
A list of products with variants decorated with "additional_prices"
#### Defined in
[services/product.js:1055](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L1055)
___
### update
▸ **update**(`productId`, `update`): `Promise`<`any`\>
Updates a product. Product variant updates should use dedicated methods,
e.g. `addVariant`, etc. The function will throw errors if metadata or
product variant updates are attempted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the id of the product. Must be a string that can be casted to an ObjectId |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/product.js:573](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L573)
___
### updateOption
▸ **updateOption**(`productId`, `optionId`, `data`): `Promise`<`any`\>
Updates a product's option. Throws if the call tries to update an option
not associated with the product. Throws if the updated title already exists.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product whose option we are updating |
| `optionId` | `string` | the id of the option we are updating |
| `data` | `any` | the data to update the option with |
#### Returns
`Promise`<`any`\>
the updated product
#### Defined in
[services/product.js:831](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L831)
___
### upsertImages\_
▸ **upsertImages_**(`images`): `Promise`<`any`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `images` | `any` |
#### Returns
`Promise`<`any`[]\>
#### Defined in
[services/product.js:542](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L542)
___
### upsertProductTags\_
▸ **upsertProductTags_**(`tags`): `Promise`<`any`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `tags` | `any` |
#### Returns
`Promise`<`any`[]\>
#### Defined in
[services/product.js:455](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L455)
___
### upsertProductType\_
▸ **upsertProductType_**(`type`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `type` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/product.js:430](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L430)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ProductService`](ProductService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`ProductService`](ProductService.md)
#### Defined in
[services/product.js:76](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product.js#L76)
@@ -0,0 +1,145 @@
# Class: ProductTypeService
Provides layer to manipulate products.
## Hierarchy
- `"medusa-interfaces"`
↳ **`ProductTypeService`**
## Constructors
### constructor
• **new ProductTypeService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/product-type.ts:16](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L16)
## Properties
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/product-type.ts:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L14)
___
### typeRepository\_
• `Private` **typeRepository\_**: typeof `ProductTypeRepository`
#### Defined in
[services/product-type.ts:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L15)
## Methods
### list
▸ **list**(`selector?`, `config?`): `Promise`<`ProductType`[]\>
Lists product types
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableProductTypeProps` | the query object for find |
| `config` | `FindConfig`<`ProductType`\> | the config to be used for find |
#### Returns
`Promise`<`ProductType`[]\>
the result of the find operation
#### Defined in
[services/product-type.ts:72](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L72)
___
### listAndCount
▸ **listAndCount**(`selector?`, `config?`): `Promise`<[`ProductType`[], `number`]\>
Lists product tags and adds count.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableProductTypeProps` | the query object for find |
| `config` | `FindConfig`<`ProductType`\> | the config to be used for find |
#### Returns
`Promise`<[`ProductType`[], `number`]\>
the result of the find operation
#### Defined in
[services/product-type.ts:88](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L88)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`ProductType`\>
Gets a product by id.
Throws in case of DB Error and if product was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of the product to get. |
| `config` | `FindConfig`<`ProductType`\> | object that defines what should be included in the query response |
#### Returns
`Promise`<`ProductType`\>
the result of the find one operation.
#### Defined in
[services/product-type.ts:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L47)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ProductTypeService`](ProductTypeService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`ProductTypeService`](ProductTypeService.md)
#### Defined in
[services/product-type.ts:23](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-type.ts#L23)
@@ -0,0 +1,631 @@
# Class: ProductVariantService
Provides layer to manipulate product variants.
## Hierarchy
- `"medusa-interfaces"`
↳ **`ProductVariantService`**
## Constructors
### constructor
• **new ProductVariantService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/product-variant.ts:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L52)
## Properties
### cartRepository\_
• `Private` **cartRepository\_**: typeof `CartRepository`
#### Defined in
[services/product-variant.ts:50](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L50)
___
### eventBus\_
• `Private` **eventBus\_**: [`EventBusService`](EventBusService.md)
#### Defined in
[services/product-variant.ts:45](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L45)
___
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/product-variant.ts:42](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L42)
___
### moneyAmountRepository\_
• `Private` **moneyAmountRepository\_**: typeof `MoneyAmountRepository`
#### Defined in
[services/product-variant.ts:48](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L48)
___
### priceSelectionStrategy\_
• `Private` **priceSelectionStrategy\_**: `IPriceSelectionStrategy`
#### Defined in
[services/product-variant.ts:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L47)
___
### productOptionValueRepository\_
• `Private` **productOptionValueRepository\_**: typeof `ProductOptionValueRepository`
#### Defined in
[services/product-variant.ts:49](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L49)
___
### productRepository\_
• `Private` **productRepository\_**: typeof `ProductRepository`
#### Defined in
[services/product-variant.ts:44](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L44)
___
### productVariantRepository\_
• `Private` **productVariantRepository\_**: typeof `ProductVariantRepository`
#### Defined in
[services/product-variant.ts:43](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L43)
___
### regionService\_
• `Private` **regionService\_**: [`RegionService`](RegionService.md)
#### Defined in
[services/product-variant.ts:46](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L46)
___
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `DELETED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/product-variant.ts:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L36)
## Methods
### addOptionValue
▸ **addOptionValue**(`variantId`, `optionId`, `optionValue`): `Promise`<`ProductOptionValue`\>
Adds option value to a varaint.
Fails when product with variant does not exists or
if that product does not have an option with the given
option id. Fails if given variant is not found.
Option value must be of type string or number.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the variant to decorate. |
| `optionId` | `string` | the option from product. |
| `optionValue` | `string` | option value to add. |
#### Returns
`Promise`<`ProductOptionValue`\>
the result of the update operation.
#### Defined in
[services/product-variant.ts:553](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L553)
___
### create
▸ **create**(`productOrProductId`, `variant`): `Promise`<`ProductVariant`\>
Creates an unpublished product variant. Will validate against parent product
to ensure that the variant can in fact be created.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productOrProductId` | `string` \| `Product` | the product the variant will be added to |
| `variant` | `CreateProductVariantInput` | the variant to create |
#### Returns
`Promise`<`ProductVariant`\>
resolves to the creation result.
#### Defined in
[services/product-variant.ts:207](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L207)
___
### delete
▸ **delete**(`variantId`): `Promise`<`void`\>
Deletes variant.
Will never fail due to delete being idempotent.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<`void`\>
empty promise
#### Defined in
[services/product-variant.ts:746](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L746)
___
### deleteOptionValue
▸ **deleteOptionValue**(`variantId`, `optionId`): `Promise`<`void`\>
Deletes option value from given variant.
Will never fail due to delete being idempotent.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the variant to decorate. |
| `optionId` | `string` | the option from product. |
#### Returns
`Promise`<`void`\>
empty promise
#### Defined in
[services/product-variant.ts:580](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L580)
___
### getFreeTextQueryBuilder\_
▸ **getFreeTextQueryBuilder_**(`variantRepo`, `query`, `q?`): `SelectQueryBuilder`<`ProductVariant`\>
Lists variants based on the provided parameters and includes the count of
variants that match the query.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantRepo` | `ProductVariantRepository` | the variant repository |
| `query` | `FindWithRelationsOptions` | object that defines the scope for what should be returned |
| `q?` | `string` | free text query |
#### Returns
`SelectQueryBuilder`<`ProductVariant`\>
an array containing the products as the first element and the total
count of products that matches the query as the second element.
#### Defined in
[services/product-variant.ts:852](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L852)
___
### getRegionPrice
▸ **getRegionPrice**(`variantId`, `context`): `Promise`<`number`\>
Gets the price specific to a region. If no region specific money amount
exists the function will try to use a currency price. If no default
currency price exists the function will throw an error.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to get price from |
| `context` | `GetRegionPriceContext` | context for getting region price |
#### Returns
`Promise`<`number`\>
the price specific to the region
#### Defined in
[services/product-variant.ts:428](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L428)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`ProductVariant`[]\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableProductVariantProps` | the query object for find |
| `config` | `FindConfig`<`ProductVariant`\> & `PriceSelectionContext` | query config object for variant retrieval |
#### Returns
`Promise`<`ProductVariant`[]\>
the result of the find operation
#### Defined in
[services/product-variant.ts:677](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L677)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<[`ProductVariant`[], `number`]\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableProductVariantProps` | the query object for find |
| `config` | `FindConfig`<`ProductVariant`\> & `PriceSelectionContext` | query config object for variant retrieval |
#### Returns
`Promise`<[`ProductVariant`[], `number`]\>
the result of the find operation
#### Defined in
[services/product-variant.ts:607](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L607)
___
### prepareListQuery\_
▸ **prepareListQuery_**(`selector`, `config`): `Object`
Creates a query object to be used for list queries.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableProductVariantProps` | the selector to create the query from |
| `config` | `FindConfig`<`ProductVariant`\> | the config to use for the query |
#### Returns
`Object`
an object containing the query, relations and free-text
search param.
| Name | Type |
| :------ | :------ |
| `q?` | `string` |
| `query` | `FindWithRelationsOptions` |
| `relations` | `string`[] |
#### Defined in
[services/product-variant.ts:813](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L813)
___
### retrieve
▸ **retrieve**(`variantId`, `config?`): `Promise`<`ProductVariant`\>
Gets a product variant by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the product to get. |
| `config` | `FindConfig`<`ProductVariant`\> & `PriceSelectionContext` | query config object for variant retrieval. |
#### Returns
`Promise`<`ProductVariant`\>
the product document.
#### Defined in
[services/product-variant.ts:117](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L117)
___
### retrieveBySKU
▸ **retrieveBySKU**(`sku`, `config?`): `Promise`<`ProductVariant`\>
Gets a product variant by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `sku` | `string` | The unique stock keeping unit used to identify the product variant. |
| `config` | `FindConfig`<`ProductVariant`\> & `PriceSelectionContext` | query config object for variant retrieval. |
#### Returns
`Promise`<`ProductVariant`\>
the product document.
#### Defined in
[services/product-variant.ts:162](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L162)
___
### setAdditionalPrices
▸ **setAdditionalPrices**(`variant`, `currency_code`, `region_id`, `cart_id`, `customer_id`, `include_discount_prices?`): `Promise`<`ProductVariant` \| `ProductVariant`[]\>
Set additional prices on a list of variants.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `variant` | `any` | `undefined` | variant on which to set additional prices |
| `currency_code` | `any` | `undefined` | currency code to fetch prices for |
| `region_id` | `any` | `undefined` | region to fetch prices for |
| `cart_id` | `any` | `undefined` | string of cart to use as a basis for getting currency and region |
| `customer_id` | `any` | `undefined` | id of potentially logged in customer, used to get prices valid for their customer groups |
| `include_discount_prices` | `boolean` | `false` | should result include discount pricing |
#### Returns
`Promise`<`ProductVariant` \| `ProductVariant`[]\>
A list of variants with variants decorated with "additional_prices"
#### Defined in
[services/product-variant.ts:897](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L897)
___
### setCurrencyPrice
▸ **setCurrencyPrice**(`variantId`, `price`): `Promise`<`MoneyAmount`\>
Sets the default price for the given currency.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to set prices for |
| `price` | `ProductVariantPrice` | the price for the variant |
#### Returns
`Promise`<`MoneyAmount`\>
the result of the update operation
#### Defined in
[services/product-variant.ts:494](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L494)
___
### setMetadata\_
▸ **setMetadata_**(`variant`, `metadata`): `Record`<`string`, `unknown`\>
Dedicated method to set metadata for a variant.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variant` | `ProductVariant` | the variant to set metadata for. |
| `metadata` | `object` | the metadata to set |
#### Returns
`Record`<`string`, `unknown`\>
updated metadata object
#### Defined in
[services/product-variant.ts:781](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L781)
___
### setRegionPrice
▸ **setRegionPrice**(`variantId`, `price`): `Promise`<`MoneyAmount`\>
Sets the default price of a specific region
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of the variant to update |
| `price` | `ProductVariantPrice` | the price for the variant. |
#### Returns
`Promise`<`MoneyAmount`\>
the result of the update operation
#### Defined in
[services/product-variant.ts:457](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L457)
___
### update
▸ **update**(`variantOrVariantId`, `update`): `Promise`<`ProductVariant`\>
Updates a variant.
Price updates should use dedicated methods.
The function will throw, if price updates are attempted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantOrVariantId` | `string` \| `Partial`<`ProductVariant`\> | variant or id of a variant. |
| `update` | `UpdateProductVariantInput` | an object with the update values. |
#### Returns
`Promise`<`ProductVariant`\>
resolves to the update result.
#### Defined in
[services/product-variant.ts:312](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L312)
___
### updateOptionValue
▸ **updateOptionValue**(`variantId`, `optionId`, `optionValue`): `Promise`<`ProductOptionValue`\>
Updates variant's option value.
Option value must be of type string or number.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the variant to decorate. |
| `optionId` | `string` | the option from product. |
| `optionValue` | `string` | option value to add. |
#### Returns
`Promise`<`ProductOptionValue`\>
the result of the update operation.
#### Defined in
[services/product-variant.ts:515](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L515)
___
### updateVariantPrices
▸ **updateVariantPrices**(`variantId`, `prices`): `Promise`<`void`\>
Updates a variant's prices.
Deletes any prices that are not in the update object, and is not associated with a price list.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `variantId` | `string` | the id of variant variant |
| `prices` | `ProductVariantPrice`[] | the update prices |
#### Returns
`Promise`<`void`\>
empty promise
#### Defined in
[services/product-variant.ts:390](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L390)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ProductVariantService`](ProductVariantService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`ProductVariantService`](ProductVariantService.md)
#### Defined in
[services/product-variant.ts:89](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/product-variant.ts#L89)
@@ -0,0 +1,79 @@
# Class: QueryBuilderService
## Hierarchy
- `"medusa-interfaces"`
↳ **`QueryBuilderService`**
## Constructors
### constructor
• **new QueryBuilderService**()
#### Inherited from
BaseService.constructor
## Methods
### buildFilterQuery
▸ **buildFilterQuery**(`filters`): `undefined` \| {}
#### Parameters
| Name | Type |
| :------ | :------ |
| `filters` | `any` |
#### Returns
`undefined` \| {}
#### Defined in
[services/query-builder.js:25](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/query-builder.js#L25)
___
### buildQuery
▸ **buildQuery**(`params`, `properties`): `Object`
#### Parameters
| Name | Type |
| :------ | :------ |
| `params` | `any` |
| `properties` | `any` |
#### Returns
`Object`
#### Defined in
[services/query-builder.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/query-builder.js#L5)
___
### buildTextSearchQuery
▸ **buildTextSearchQuery**(`search`, `searchProperties`): `undefined` \| { `$or`: `any` = searchQuery }
#### Parameters
| Name | Type |
| :------ | :------ |
| `search` | `any` |
| `searchProperties` | `any` |
#### Returns
`undefined` \| { `$or`: `any` = searchQuery }
#### Defined in
[services/query-builder.js:39](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/query-builder.js#L39)
@@ -0,0 +1,457 @@
# Class: RegionService
Provides layer to manipulate regions.
## Hierarchy
- `"medusa-interfaces"`
↳ **`RegionService`**
## Constructors
### constructor
• **new RegionService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/region.js:16](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L16)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `DELETED` | `string` |
| `UPDATED` | `string` |
#### Defined in
[services/region.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L10)
## Methods
### addCountry
▸ **addCountry**(`regionId`, `code`): `Promise`<`any`\>
Adds a country to the region.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to add a country to |
| `code` | `string` | a 2 digit alphanumeric ISO country code. |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:460](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L460)
___
### addFulfillmentProvider
▸ **addFulfillmentProvider**(`regionId`, `providerId`): `Promise`<`any`\>
Adds a fulfillment provider that is available in the region. Fails if the
provider doesn't exist.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to add the provider to |
| `providerId` | `string` | the provider to add to the region |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:580](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L580)
___
### addPaymentProvider
▸ **addPaymentProvider**(`regionId`, `providerId`): `Promise`<`any`\>
Adds a payment provider that is available in the region. Fails if the
provider doesn't exist.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to add the provider to |
| `providerId` | `string` | the provider to add to the region |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:533](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L533)
___
### create
▸ **create**(`regionObject`): `Region`
Creates a region.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionObject` | `Region` | the unvalidated region |
#### Returns
`Region`
the newly created region
#### Defined in
[services/region.js:95](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L95)
___
### delete
▸ **delete**(`regionId`): `Promise`<`any`\>
Deletes a region.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to delete |
#### Returns
`Promise`<`any`\>
the result of the delete operation
#### Defined in
[services/region.js:430](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L430)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`any`\>
Lists all regions based on a query
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | query object for find |
| `config` | `any` | configuration settings |
#### Returns
`Promise`<`any`\>
result of the find operation
#### Defined in
[services/region.js:418](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L418)
___
### removeCountry
▸ **removeCountry**(`regionId`, `code`): `Promise`<`any`\>
Removes a country from a Region
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to remove from |
| `code` | `string` | a 2 digit alphanumeric ISO country code to remove |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:497](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L497)
___
### removeFulfillmentProvider
▸ **removeFulfillmentProvider**(`regionId`, `providerId`): `Promise`<`any`\>
Removes a fulfillment provider from a region. Is idempotent.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to remove the provider from |
| `providerId` | `string` | the provider to remove from the region |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:658](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L658)
___
### removePaymentProvider
▸ **removePaymentProvider**(`regionId`, `providerId`): `Promise`<`any`\>
Removes a payment provider from a region. Is idempotent.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to remove the provider from |
| `providerId` | `string` | the provider to remove from the region |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:624](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L624)
___
### retrieve
▸ **retrieve**(`regionId`, `config?`): `Region`
Retrieves a region by its id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the id of the region to retrieve |
| `config` | `any` | configuration settings |
#### Returns
`Region`
the region
#### Defined in
[services/region.js:394](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L394)
___
### retrieveByCountryCode
▸ **retrieveByCountryCode**(`code`, `config?`): `Promise`<`Region`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `code` | `any` |
| `config` | `Object` |
#### Returns
`Promise`<`Region`\>
#### Defined in
[services/region.js:360](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L360)
___
### update
▸ **update**(`regionId`, `update`): `Promise`<`any`\>
Updates a region
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `regionId` | `string` | the region to update |
| `update` | `any` | the data to update the region with |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/region.js:153](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L153)
___
### validateCountry\_
▸ **validateCountry_**(`code`, `regionId`): `Promise`<`any`\>
Validates a country code. Will normalize the code before checking for
existence.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `code` | `string` | a 2 digit alphanumeric ISO country code |
| `regionId` | `string` | the id of the current region to check against |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/region.js:323](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L323)
___
### validateCurrency\_
▸ **validateCurrency_**(`currencyCode`): `Promise`<`void`\>
Validates a currency code. Will throw if the currency code doesn't exist.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `currencyCode` | `string` | an ISO currency code |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/region.js:302](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L302)
___
### validateFields\_
▸ **validateFields_**(`region`, `id?`): `any`
Validates fields for creation and updates. If the region already exisits
the id can be passed to check that country updates are allowed.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `region` | `any` | `undefined` | the region data to validate |
| `id` | ``null`` \| `string` | `undefined` | optional id of the region to check against |
#### Returns
`any`
the validated region data
#### Defined in
[services/region.js:213](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L213)
___
### validateTaxRate\_
▸ **validateTaxRate_**(`taxRate`): `void`
Validates a tax rate. Will throw if the tax rate is not between 0 and 1.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `taxRate` | `number` | a number representing the tax rate of the region |
#### Returns
`void`
#### Defined in
[services/region.js:289](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L289)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`RegionService`](RegionService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`RegionService`](RegionService.md)
#### Defined in
[services/region.js:65](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/region.js#L65)
@@ -0,0 +1,156 @@
# Class: ReturnReasonService
## Hierarchy
- `"medusa-interfaces"`
↳ **`ReturnReasonService`**
## Constructors
### constructor
• **new ReturnReasonService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/return-reason.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L5)
## Methods
### create
▸ **create**(`data`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `any` |
#### Returns
`any`
#### Defined in
[services/return-reason.js:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L30)
___
### delete
▸ **delete**(`returnReasonId`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `returnReasonId` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/return-reason.js:114](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L114)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | config object |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/return-reason.js:82](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L82)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`Order`\>
Gets an order by id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | id of order to retrieve |
| `config` | `any` | config object |
#### Returns
`Promise`<`Order`\>
the order document
#### Defined in
[services/return-reason.js:97](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L97)
___
### update
▸ **update**(`id`, `data`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `any` |
| `data` | `any` |
#### Returns
`any`
#### Defined in
[services/return-reason.js:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L52)
___
### withTransaction
▸ **withTransaction**(`manager`): [`ReturnReasonService`](ReturnReasonService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `manager` | `any` |
#### Returns
[`ReturnReasonService`](ReturnReasonService.md)
#### Defined in
[services/return-reason.js:15](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return-reason.js#L15)
@@ -0,0 +1,355 @@
# Class: ReturnService
Handles Returns
## Hierarchy
- `"medusa-interfaces"`
↳ **`ReturnService`**
## Constructors
### constructor
• **new ReturnService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/return.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L9)
## Properties
### inventoryService\_
• **inventoryService\_**: `any`
#### Defined in
[services/return.js:49](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L49)
___
### returnReasonService\_
• **returnReasonService\_**: `any`
#### Defined in
[services/return.js:47](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L47)
___
### taxProviderService\_
• **taxProviderService\_**: `any`
#### Defined in
[services/return.js:39](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L39)
## Methods
### cancel
▸ **cancel**(`returnId`): `Promise`<`Return`\>
Cancels a return if possible. Returns can be canceled if it has not been received.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `returnId` | `string` | the id of the return to cancel. |
#### Returns
`Promise`<`Return`\>
the updated Return
#### Defined in
[services/return.js:134](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L134)
___
### create
▸ **create**(`data`): `Promise`<`Return`\>
Creates a return request for an order, with given items, and a shipping
method. If no refund amount is provided the refund amount is calculated from
the return lines and the shipping cost.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `any` | data to use for the return e.g. shipping_method, items or refund_amount |
#### Returns
`Promise`<`Return`\>
the created return
#### Defined in
[services/return.js:307](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L307)
___
### fulfill
▸ **fulfill**(`returnId`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `returnId` | `any` |
#### Returns
`any`
#### Defined in
[services/return.js:450](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L450)
___
### getFulfillmentItems\_
▸ **getFulfillmentItems_**(`order`, `items`, `transformer`): `Promise`<`LineItem`[]\>
Retrieves the order line items, given an array of items
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to get line items from |
| `items` | `Object` | the items to get |
| `items.item_id` | `string` | - |
| `items.quantity` | `number` | - |
| `transformer` | `Function` | a function to apply to each of the items retrieved from the order, should return a line item. If the transformer returns an undefined value the line item will be filtered from the returned array. |
#### Returns
`Promise`<`LineItem`[]\>
the line items generated by the transformer.
#### Defined in
[services/return.js:89](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L89)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config object for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/return.js:120](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L120)
___
### receive
▸ **receive**(`return_id`, `received_items`, `refund_amount`, `allow_mismatch?`): `Promise`<`any`\>
Registers a previously requested return as received. This will create a
refund to the customer. If the returned items don't match the requested
items the return status will be updated to requires_action. This behaviour
is useful in sitautions where a custom refund amount is requested, but the
retuned items are not matching the requested items. Setting the
allowMismatch argument to true, will process the return, ignoring any
mismatches.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `return_id` | `string` | `undefined` | the orderId to return to |
| `received_items` | `Item`[] | `undefined` | the items received after return. |
| `refund_amount` | `undefined` \| `number` | `undefined` | the amount to return |
| `allow_mismatch` | `bool` | `false` | whether to ignore return/received product mismatch |
#### Returns
`Promise`<`any`\>
the result of the update operation
#### Defined in
[services/return.js:524](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L524)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Return`
Retrieves a return by its id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the return to retrieve |
| `config` | `any` | the config object |
#### Returns
`Return`
the return
#### Defined in
[services/return.js:229](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L229)
___
### retrieveBySwap
▸ **retrieveBySwap**(`swapId`, `relations?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `swapId` | `any` | `undefined` |
| `relations` | `any`[] | `[]` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/return.js:248](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L248)
___
### update
▸ **update**(`returnId`, `update`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `returnId` | `any` |
| `update` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/return.js:271](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L271)
___
### validateReturnLineItem\_
▸ **validateReturnLineItem_**(`item`, `quantity`, `additional`): `LineItem`
Checks that a given quantity of a line item can be returned. Fails if the
item is undefined or if the returnable quantity of the item is lower, than
the quantity that is requested to be returned.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `item` | `any` | the line item to check has sufficient returnable quantity. |
| `quantity` | `number` | the quantity that is requested to be returned. |
| `additional` | `any` | the quantity that is requested to be returned. |
#### Returns
`LineItem`
a line item where the quantity is set to the requested
return quantity.
#### Defined in
[services/return.js:191](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L191)
___
### validateReturnStatuses\_
▸ **validateReturnStatuses_**(`order`): `void`
Checks that an order has the statuses necessary to complete a return.
fulfillment_status cannot be not_fulfilled or returned.
payment_status must be captured.
**`throws`** when statuses are not sufficient for returns.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to check statuses on |
#### Returns
`void`
#### Defined in
[services/return.js:161](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L161)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ReturnService`](ReturnService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`ReturnService`](ReturnService.md)
#### Defined in
[services/return.js:55](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/return.js#L55)
@@ -0,0 +1,222 @@
# Class: SearchService
Default class that implements SearchService but provides stuv implementation for all methods
## Hierarchy
- `"medusa-interfaces"`
↳ **`SearchService`**
## Constructors
### constructor
• **new SearchService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `any` |
#### Overrides
SearchService.constructor
#### Defined in
[services/search.js:8](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L8)
## Properties
### isDefault
• **isDefault**: `boolean`
#### Defined in
[services/search.js:11](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L11)
___
### logger\_
• **logger\_**: `any`
#### Defined in
[services/search.js:13](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L13)
## Methods
### addDocuments
▸ **addDocuments**(`indexName`, `documents`, `type`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `documents` | `any` |
| `type` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:28](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L28)
___
### createIndex
▸ **createIndex**(`indexName`, `options`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `options` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:16](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L16)
___
### deleteAllDocuments
▸ **deleteAllDocuments**(`indexName`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:46](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L46)
___
### deleteDocument
▸ **deleteDocument**(`indexName`, `document_id`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `document_id` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:40](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L40)
___
### getIndex
▸ **getIndex**(`indexName`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:22](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L22)
___
### replaceDocuments
▸ **replaceDocuments**(`indexName`, `documents`, `type`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `documents` | `any` |
| `type` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:34](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L34)
___
### search
▸ **search**(`indexName`, `query`, `options`): `Object`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `query` | `any` |
| `options` | `any` |
#### Returns
`Object`
| Name | Type |
| :------ | :------ |
| `hits` | `never`[] |
#### Defined in
[services/search.js:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L52)
___
### updateSettings
▸ **updateSettings**(`indexName`, `settings`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `indexName` | `any` |
| `settings` | `any` |
#### Returns
`void`
#### Defined in
[services/search.js:59](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/search.js#L59)
@@ -0,0 +1,478 @@
# Class: ShippingOptionService
Provides layer to manipulate profiles.
## Hierarchy
- `"medusa-interfaces"`
↳ **`ShippingOptionService`**
## Constructors
### constructor
• **new ShippingOptionService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/shipping-option.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L9)
## Methods
### addRequirement
▸ **addRequirement**(`optionId`, `requirement`): `Promise`<`any`\>
Adds a requirement to a shipping option. Only 1 requirement of each type
is allowed.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the option to add the requirement to. |
| `requirement` | `ShippingRequirement` | the requirement for the option. |
#### Returns
`Promise`<`any`\>
the result of update
#### Defined in
[services/shipping-option.js:594](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L594)
___
### create
▸ **create**(`data`): `Promise`<`ShippingOption`\>
Creates a new shipping option. Used both for outbound and inbound shipping
options. The difference is registered by the `is_return` field which
defaults to false.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `data` | `ShippingOption` | the data to create shipping options |
#### Returns
`Promise`<`ShippingOption`\>
the result of the create operation
#### Defined in
[services/shipping-option.js:350](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L350)
___
### createShippingMethod
▸ **createShippingMethod**(`optionId`, `data`, `config`): `ShippingMethod`
Creates a shipping method for a given cart.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the id of the option to use for the method. |
| `data` | `any` | the optional provider data to use. |
| `config` | `any` | the cart to create the shipping method for. |
#### Returns
`ShippingMethod`
the resulting shipping method.
#### Defined in
[services/shipping-option.js:231](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L231)
___
### decorate
▸ **decorate**(`optionId`, `fields?`, `expandFields?`): `ShippingOption`
Decorates a shipping option.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `optionId` | `ShippingOption` | `undefined` | the shipping option to decorate using optionId. |
| `fields` | `string`[] | `[]` | the fields to include. |
| `expandFields` | `string`[] | `[]` | fields to expand. |
#### Returns
`ShippingOption`
the decorated ShippingOption.
#### Defined in
[services/shipping-option.js:645](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L645)
___
### delete
▸ **delete**(`optionId`): `Promise`<`any`\>
Deletes a profile with a given profile id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the id of the profile to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<`any`\>
the result of the delete operation.
#### Defined in
[services/shipping-option.js:566](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L566)
___
### deleteShippingMethods
▸ **deleteShippingMethods**(`shippingMethods`): `Promise`<`any`\>
Removes a given shipping method
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `shippingMethods` | `any` | the shipping method to remove |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/shipping-option.js:213](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L213)
___
### getPrice\_
▸ **getPrice_**(`option`, `data`, `cart`): `Promise`<`number`\>
Returns the amount to be paid for a shipping method. Will ask the
fulfillment provider to calculate the price if the shipping option has the
price type "calculated".
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `option` | `ShippingOption` | the shipping option to retrieve the price for. |
| `data` | `ShippingData` | the shipping data to retrieve the price. |
| `cart` | `any` | the context in which the price should be retrieved. |
#### Returns
`Promise`<`number`\>
the price of the shipping option.
#### Defined in
[services/shipping-option.js:697](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L697)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | config object |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/shipping-option.js:123](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L123)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | config object |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/shipping-option.js:135](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L135)
___
### removeRequirement
▸ **removeRequirement**(`requirementId`): `Promise`<`any`\>
Removes a requirement from a shipping option
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `requirementId` | `string` | the id of the requirement to remove |
#### Returns
`Promise`<`any`\>
the result of update
#### Defined in
[services/shipping-option.js:620](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L620)
___
### retrieve
▸ **retrieve**(`optionId`, `options?`): `Promise`<`Product`\>
Gets a profile by id.
Throws in case of DB Error and if profile was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the id of the profile to get. |
| `options` | `any` | the options to get a profile |
#### Returns
`Promise`<`Product`\>
the profile document.
#### Defined in
[services/shipping-option.js:149](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L149)
___
### setMetadata\_
▸ **setMetadata_**(`option`, `metadata`): `Promise`<`any`\>
Dedicated method to set metadata for a shipping option.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `option` | `any` | the option to set metadata for. |
| `metadata` | `any` | object for metadata field |
#### Returns
`Promise`<`any`\>
resolves to the updated result.
#### Defined in
[services/shipping-option.js:664](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L664)
___
### update
▸ **update**(`optionId`, `update`): `Promise`<`any`\>
Updates a profile. Metadata updates and product updates should use
dedicated methods, e.g. `setMetadata`, etc. The function
will throw errors if metadata or product updates are attempted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the id of the option. Must be a string that can be casted to an ObjectId |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/shipping-option.js:464](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L464)
___
### updateShippingMethod
▸ **updateShippingMethod**(`id`, `update`): `Promise`<`ShippingMethod`\>
Updates a shipping method's associations. Useful when a cart is completed
and its methods should be copied to an order/swap entity.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the shipping method to update |
| `update` | `any` | the values to update the method with |
#### Returns
`Promise`<`ShippingMethod`\>
the resulting shipping method
#### Defined in
[services/shipping-option.js:184](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L184)
___
### validateCartOption
▸ **validateCartOption**(`option`, `cart`): `ShippingOption`
Checks if a given option id is a valid option for a cart. If it is the
option is returned with the correct price. Throws when region_ids do not
match, or when the shipping option requirements are not satisfied.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `option` | `any` | the option object to check |
| `cart` | `Cart` | the cart object to check against |
#### Returns
`ShippingOption`
the validated shipping option
#### Defined in
[services/shipping-option.js:309](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L309)
___
### validatePriceType\_
▸ **validatePriceType_**(`priceType`, `option`): `Promise`<`ShippingOptionPrice`\>
Validates a shipping option price
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `priceType` | `ShippingOptionPrice` | the price to validate |
| `option` | `ShippingOption` | the option to validate against |
#### Returns
`Promise`<`ShippingOptionPrice`\>
the validated price
#### Defined in
[services/shipping-option.js:431](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L431)
___
### validateRequirement\_
▸ **validateRequirement_**(`requirement`, `optionId`): `ShippingRequirement`
Validates a requirement
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `requirement` | `ShippingRequirement` | the requirement to validate |
| `optionId` | `string` | the id to validate the requirement |
#### Returns
`ShippingRequirement`
a validated shipping requirement
#### Defined in
[services/shipping-option.js:63](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L63)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ShippingOptionService`](ShippingOptionService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`ShippingOptionService`](ShippingOptionService.md)
#### Defined in
[services/shipping-option.js:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-option.js#L38)
@@ -0,0 +1,392 @@
# Class: ShippingProfileService
Provides layer to manipulate profiles.
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`ShippingProfileService`**
## Constructors
### constructor
• **new ShippingProfileService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/shipping-profile.js:12](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L12)
## Methods
### addProduct
▸ **addProduct**(`profileId`, `productId`): `Promise`<`any`\>
Adds a product to a profile. The method is idempotent, so multiple calls
with the same product variant will have the same result.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profileId` | `string` | the profile to add the product to. |
| `productId` | `string` | the product to add. |
#### Returns
`Promise`<`any`\>
the result of update
#### Defined in
[services/shipping-profile.js:343](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L343)
___
### addShippingOption
▸ **addShippingOption**(`profileId`, `optionId`): `Promise`<`any`\>
Adds a shipping option to the profile. The shipping option can be used to
fulfill the products in the products field.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profileId` | `string` | the profile to apply the shipping option to |
| `optionId` | `string` | the option to add to the profile |
#### Returns
`Promise`<`any`\>
the result of the model update operation
#### Defined in
[services/shipping-profile.js:361](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L361)
___
### create
▸ **create**(`profile`): `Promise`<`any`\>
Creates a new shipping profile.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profile` | `ShippingProfile` | the shipping profile to create from |
#### Returns
`Promise`<`any`\>
the result of the create operation
#### Defined in
[services/shipping-profile.js:235](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L235)
___
### createDefault
▸ **createDefault**(): `Promise`<`ShippingProfile`\>
Creates a default shipping profile, if this does not already exist.
#### Returns
`Promise`<`ShippingProfile`\>
the shipping profile
#### Defined in
[services/shipping-profile.js:167](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L167)
___
### createGiftCardDefault
▸ **createGiftCardDefault**(): `Promise`<`ShippingProfile`\>
Creates a default shipping profile, for gift cards if unless it already
exists.
#### Returns
`Promise`<`ShippingProfile`\>
the shipping profile
#### Defined in
[services/shipping-profile.js:209](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L209)
___
### decorate
▸ **decorate**(`profile`, `fields`, `expandFields?`): `Profile`
Decorates a profile.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `profile` | `Profile` | `undefined` | the profile to decorate. |
| `fields` | `string`[] | `undefined` | the fields to include. |
| `expandFields` | `string`[] | `[]` | fields to expand. |
#### Returns
`Profile`
return the decorated profile.
#### Defined in
[services/shipping-profile.js:379](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L379)
___
### delete
▸ **delete**(`profileId`): `Promise`<`any`\>
Deletes a profile with a given profile id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profileId` | `string` | the id of the profile to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<`any`\>
the result of the delete operation.
#### Defined in
[services/shipping-profile.js:317](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L317)
___
### fetchCartOptions
▸ **fetchCartOptions**(`cart`): [`ShippingOption`]
Finds all the shipping profiles that cover the products in a cart, and
validates all options that are available for the cart.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cart` | `Cart` | the cart object to find shipping options for |
#### Returns
[`ShippingOption`]
a list of the available shipping options
#### Defined in
[services/shipping-profile.js:425](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L425)
___
### fetchOptionsByProductIds
▸ **fetchOptionsByProductIds**(`productIds`, `filter`): `Promise`<`any`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `productIds` | `any` |
| `filter` | `any` |
#### Returns
`Promise`<`any`[]\>
#### Defined in
[services/shipping-profile.js:73](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L73)
___
### getProfilesInCart\_
▸ **getProfilesInCart_**(`cart`): [`string`]
Returns a list of all the productIds in the cart.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cart` | `Cart` | the cart to extract products from |
#### Returns
[`string`]
a list of product ids
#### Defined in
[services/shipping-profile.js:406](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L406)
___
### list
▸ **list**(`selector?`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the config object for find |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/shipping-profile.js:64](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L64)
___
### retrieve
▸ **retrieve**(`profileId`, `options?`): `Promise`<`Product`\>
Gets a profile by id.
Throws in case of DB Error and if profile was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profileId` | `string` | the id of the profile to get. |
| `options` | `any` | options opf the query. |
#### Returns
`Promise`<`Product`\>
the profile document.
#### Defined in
[services/shipping-profile.js:121](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L121)
___
### retrieveDefault
▸ **retrieveDefault**(): `Promise`<`any`\>
#### Returns
`Promise`<`any`\>
#### Defined in
[services/shipping-profile.js:151](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L151)
___
### retrieveGiftCardDefault
▸ **retrieveGiftCardDefault**(): `any`
Retrieves the default gift card profile
#### Returns
`any`
the shipping profile for gift cards
#### Defined in
[services/shipping-profile.js:192](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L192)
___
### update
▸ **update**(`profileId`, `update`): `Promise`<`any`\>
Updates a profile. Metadata updates and product updates should use
dedicated methods, e.g. `setMetadata`, `addProduct`, etc. The function
will throw errors if metadata or product updates are attempted.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `profileId` | `string` | the id of the profile. Must be a string that can be casted to an ObjectId |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/shipping-profile.js:263](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L263)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`ShippingProfileService`](ShippingProfileService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`ShippingProfileService`](ShippingProfileService.md)
#### Defined in
[services/shipping-profile.js:41](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/shipping-profile.js#L41)
@@ -0,0 +1,216 @@
# Class: StoreService
Provides layer to manipulate store settings.
## Hierarchy
- `"medusa-interfaces"`
↳ **`StoreService`**
## Constructors
### constructor
• **new StoreService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/store.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L10)
## Methods
### addCurrency
▸ **addCurrency**(`code`): `Promise`<`any`\>
Add a currency to the store
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `code` | `string` | 3 character ISO currency code |
#### Returns
`Promise`<`any`\>
result after update
#### Defined in
[services/store.js:203](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L203)
___
### create
▸ **create**(): `Promise`<`Store`\>
Creates a store if it doesn't already exist.
#### Returns
`Promise`<`Store`\>
the store.
#### Defined in
[services/store.js:52](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L52)
___
### decorate
▸ **decorate**(`store`, `fields`, `expandFields?`): `Store`
Decorates a store object.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `store` | `Store` | `undefined` | the store to decorate. |
| `fields` | `string`[] | `undefined` | the fields to include. |
| `expandFields` | `string`[] | `[]` | fields to expand. |
#### Returns
`Store`
return the decorated Store.
#### Defined in
[services/store.js:266](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L266)
___
### getDefaultCurrency\_
▸ **getDefaultCurrency_**(`code`): `Object`
#### Parameters
| Name | Type |
| :------ | :------ |
| `code` | `any` |
#### Returns
`Object`
| Name | Type |
| :------ | :------ |
| `code` | `any` |
| `name` | `any` |
| `symbol` | `any` |
| `symbol_native` | `any` |
#### Defined in
[services/store.js:92](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L92)
___
### removeCurrency
▸ **removeCurrency**(`code`): `Promise`<`any`\>
Removes a currency from the store
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `code` | `string` | 3 character ISO currency code |
#### Returns
`Promise`<`any`\>
result after update
#### Defined in
[services/store.js:242](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L242)
___
### retrieve
▸ **retrieve**(`relations?`): `Promise`<`Store`\>
Retrieve the store settings. There is always a maximum of one store.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `relations` | `string`[] | `[]` | relations to fetch with store |
#### Returns
`Promise`<`Store`\>
the store
#### Defined in
[services/store.js:84](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L84)
___
### update
▸ **update**(`update`): `Promise`<`any`\>
Updates a store
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `update` | `any` | an object with the update values. |
#### Returns
`Promise`<`any`\>
resolves to the update result.
#### Defined in
[services/store.js:108](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L108)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`StoreService`](StoreService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`StoreService`](StoreService.md)
#### Defined in
[services/store.js:31](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/store.js#L31)
@@ -0,0 +1,465 @@
# Class: SwapService
Handles swaps
## Hierarchy
- `"medusa-interfaces"`
↳ **`SwapService`**
## Constructors
### constructor
• **new SwapService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/swap.js:21](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L21)
## Properties
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `CREATED` | `string` |
| `FULFILLMENT_CREATED` | `string` |
| `PAYMENT_CAPTURED` | `string` |
| `PAYMENT_CAPTURE_FAILED` | `string` |
| `PAYMENT_COMPLETED` | `string` |
| `PROCESS_REFUND_FAILED` | `string` |
| `RECEIVED` | `string` |
| `REFUND_PROCESSED` | `string` |
| `SHIPMENT_CREATED` | `string` |
#### Defined in
[services/swap.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L9)
## Methods
### cancel
▸ **cancel**(`swapId`): `Promise`<`Swap`\>
Cancels a given swap if possible. A swap can only be canceled if all
related returns, fulfillments, and payments have been canceled. If a swap
is associated with a refund, it cannot be canceled.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `swapId` | `string` | the id of the swap to cancel. |
#### Returns
`Promise`<`Swap`\>
the canceled swap.
#### Defined in
[services/swap.js:790](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L790)
___
### cancelFulfillment
▸ **cancelFulfillment**(`fulfillmentId`): `Swap`
Cancels a fulfillment (if related to a swap)
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `fulfillmentId` | `string` | the ID of the fulfillment to cancel |
#### Returns
`Swap`
updated swap
#### Defined in
[services/swap.js:983](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L983)
___
### create
▸ **create**(`order`, `returnItems`, `additionalItems`, `returnShipping`, `custom?`): `Promise`<`Swap`\>
Creates a swap from an order, with given return items, additional items
and an optional return shipping method.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to base the swap off. |
| `returnItems` | `ReturnItem`[] | the items to return in the swap. |
| `additionalItems` | `undefined` \| `PreliminaryLineItem`[] | the items to send to the customer. |
| `returnShipping` | `any` | an optional shipping method for returning the returnItems. |
| `custom` | `any` | contains relevant custom information. This object may include no_notification which will disable sending notification when creating swap. If set, it overrules the attribute inherited from the order. |
#### Returns
`Promise`<`Swap`\>
the newly created swap.
#### Defined in
[services/swap.js:313](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L313)
___
### createCart
▸ **createCart**(`swapId`, `customShippingOptions?`): `Promise`<`Swap`\>
Creates a cart from the given swap and order. The cart can be used to pay
for differences associated with the swap. The swap represented by the
swapId must belong to the order. Fails if there is already a cart on the
swap.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `swapId` | `string` | `undefined` | the id of the swap to create the cart from |
| `customShippingOptions` | `any`[] | `[]` | the shipping options |
#### Returns
`Promise`<`Swap`\>
the swap with its cart_id prop set to the id of
the new cart.
#### Defined in
[services/swap.js:544](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L544)
___
### createFulfillment
▸ **createFulfillment**(`swapId`, `config?`): `Promise`<`Swap`\>
Fulfills the addtional items associated with the swap. Will call the
fulfillment providers associated with the shipping methods.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `swapId` | `string` | the id of the swap to fulfill, |
| `config` | `any` | optional configurations, includes optional metadata to attach to the shipment, and a no_notification flag. |
#### Returns
`Promise`<`Swap`\>
the updated swap with new status and fulfillments.
#### Defined in
[services/swap.js:848](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L848)
___
### createShipment
▸ **createShipment**(`swapId`, `fulfillmentId`, `trackingLinks`, `config?`): `Promise`<`Swap`\>
Marks a fulfillment as shipped and attaches tracking numbers.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `swapId` | `string` | the id of the swap that has been shipped. |
| `fulfillmentId` | `string` | the id of the specific fulfillment that has been shipped |
| `trackingLinks` | `undefined` \| `TrackingLink`[] | the tracking numbers associated with the shipment |
| `config` | `any` | optional configurations, includes optional metadata to attach to the shipment, and a noNotification flag. |
#### Returns
`Promise`<`Swap`\>
the updated swap with new fulfillments and status.
#### Defined in
[services/swap.js:1016](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L1016)
___
### deleteMetadata
▸ **deleteMetadata**(`swapId`, `key`): `Promise`<`any`\>
Dedicated method to delete metadata for a swap.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `swapId` | `string` | the order to delete metadata from. |
| `key` | `string` | key for metadata field |
#### Returns
`Promise`<`any`\>
resolves to the updated result.
#### Defined in
[services/swap.js:1089](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L1089)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `any` | the query object for find |
| `config` | `any` | the configuration used to find the objects. contains relations, skip, and take. |
#### Returns
`Promise`<`any`\>
the result of the find operation
#### Defined in
[services/swap.js:238](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L238)
___
### processDifference
▸ **processDifference**(`swapId`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `swapId` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/swap.js:395](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L395)
___
### registerCartCompletion
▸ **registerCartCompletion**(`swapId`): `Promise`<`any`\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `swapId` | `string` | The id of the swap |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/swap.js:659](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L659)
___
### registerReceived
▸ **registerReceived**(`id`): `Promise`<`Order`\>
Registers the swap return items as received so that they cannot be used
as a part of other swaps/returns.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the order with the swap. |
#### Returns
`Promise`<`Order`\>
the resulting order
#### Defined in
[services/swap.js:1114](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L1114)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`Swap`\>
Retrieves a swap with the given id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `id` | `string` | the id of the swap to retrieve |
| `config` | `any` | the configuration to retrieve the swap |
#### Returns
`Promise`<`Swap`\>
the swap
#### Defined in
[services/swap.js:181](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L181)
___
### retrieveByCartId
▸ **retrieveByCartId**(`cartId`, `relations?`): `Promise`<`Swap`\>
Retrieves a swap based on its associated cart id
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `cartId` | `string` | `undefined` | the cart id that the swap's cart has |
| `relations` | `string`[] | `[]` | the relations to retrieve swap |
#### Returns
`Promise`<`Swap`\>
the swap
#### Defined in
[services/swap.js:216](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L216)
___
### transformQueryForCart\_
▸ **transformQueryForCart_**(`config`): `any`
#### Parameters
| Name | Type |
| :------ | :------ |
| `config` | `any` |
#### Returns
`any`
#### Defined in
[services/swap.js:114](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L114)
___
### update
▸ **update**(`swapId`, `update`): `Promise`<`any`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `swapId` | `any` |
| `update` | `any` |
#### Returns
`Promise`<`any`\>
#### Defined in
[services/swap.js:511](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L511)
___
### validateReturnItems\_
▸ **validateReturnItems_**(`order`, `returnItems`): `ReturnItems`[]
Goes through a list of return items to ensure that they exist on the
original order. If the item exists it is verified that the quantity to
return is not higher than the original quantity ordered.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `OrderLike` | the order to return from |
| `returnItems` | `ReturnItem`[] | the items to return |
#### Returns
`ReturnItems`[]
the validated returnItems
#### Defined in
[services/swap.js:269](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L269)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`SwapService`](SwapService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `any` |
#### Returns
[`SwapService`](SwapService.md)
#### Defined in
[services/swap.js:86](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/swap.js#L86)
@@ -0,0 +1,237 @@
# Class: SystemPaymentProviderService
## Hierarchy
- `"medusa-interfaces"`
↳ **`SystemPaymentProviderService`**
## Constructors
### constructor
• **new SystemPaymentProviderService**(`_`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Overrides
BaseService.constructor
#### Defined in
[services/system-payment-provider.js:6](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L6)
## Properties
### identifier
▪ `Static` **identifier**: `string` = `"system"`
#### Defined in
[services/system-payment-provider.js:4](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L4)
## Methods
### authorizePayment
▸ **authorizePayment**(`_`): `Promise`<{ `data`: {} = {}; `status`: `string` = "authorized" }\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{ `data`: {} = {}; `status`: `string` = "authorized" }\>
#### Defined in
[services/system-payment-provider.js:22](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L22)
___
### cancelPayment
▸ **cancelPayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:46](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L46)
___
### capturePayment
▸ **capturePayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L38)
___
### createPayment
▸ **createPayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:10](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L10)
___
### deletePayment
▸ **deletePayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:34](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L34)
___
### getPaymentData
▸ **getPaymentData**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:18](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L18)
___
### getStatus
▸ **getStatus**(`_`): `Promise`<`string`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<`string`\>
#### Defined in
[services/system-payment-provider.js:14](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L14)
___
### refundPayment
▸ **refundPayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:42](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L42)
___
### updatePayment
▸ **updatePayment**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:30](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L30)
___
### updatePaymentData
▸ **updatePaymentData**(`_`): `Promise`<{}\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | `any` |
#### Returns
`Promise`<{}\>
#### Defined in
[services/system-payment-provider.js:26](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/system-payment-provider.js#L26)
@@ -0,0 +1,442 @@
# Class: TaxProviderService
Finds tax providers and assists in tax related operations.
## Hierarchy
- `"medusa-interfaces"`
↳ **`TaxProviderService`**
## Constructors
### constructor
• **new TaxProviderService**(`container`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `container` | `AwilixContainer`<`any`\> |
#### Overrides
BaseService.constructor
#### Defined in
[services/tax-provider.ts:44](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L44)
## Properties
### container\_
• `Private` **container\_**: `AwilixContainer`<`any`\>
#### Defined in
[services/tax-provider.ts:35](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L35)
___
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/tax-provider.ts:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L36)
___
### redis\_
• `Private` **redis\_**: `Redis`
#### Defined in
[services/tax-provider.ts:42](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L42)
___
### smTaxLineRepo\_
• `Private` **smTaxLineRepo\_**: typeof `ShippingMethodTaxLineRepository`
#### Defined in
[services/tax-provider.ts:40](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L40)
___
### taxLineRepo\_
• `Private` **taxLineRepo\_**: typeof `LineItemTaxLineRepository`
#### Defined in
[services/tax-provider.ts:39](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L39)
___
### taxProviderRepo\_
• `Private` **taxProviderRepo\_**: typeof `TaxProviderRepository`
#### Defined in
[services/tax-provider.ts:41](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L41)
___
### taxRateService\_
• `Private` **taxRateService\_**: [`TaxRateService`](TaxRateService.md)
#### Defined in
[services/tax-provider.ts:38](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L38)
___
### transactionManager\_
• `Private` **transactionManager\_**: `EntityManager`
#### Defined in
[services/tax-provider.ts:37](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L37)
## Methods
### clearTaxLines
▸ **clearTaxLines**(`cartId`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `cartId` | `string` |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-provider.ts:98](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L98)
___
### createShippingTaxLines
▸ **createShippingTaxLines**(`shippingMethod`, `calculationContext`): `Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
Persists the tax lines relevant for a shipping method to the database. Used
for return shipping methods.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `shippingMethod` | `ShippingMethod` | the shipping method to create tax lines for |
| `calculationContext` | `TaxCalculationContext` | the calculation context to get tax lines by |
#### Returns
`Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
the newly created tax lines
#### Defined in
[services/tax-provider.ts:166](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L166)
___
### createTaxLines
▸ **createTaxLines**(`cartOrLineItems`, `calculationContext`): `Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
Persists the tax lines relevant for an order to the database.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrLineItems` | `Cart` \| `LineItem`[] | the cart or line items to create tax lines for |
| `calculationContext` | `TaxCalculationContext` | the calculation context to get tax lines by |
#### Returns
`Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
the newly created tax lines
#### Defined in
[services/tax-provider.ts:116](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L116)
___
### getCacheEntry
▸ `Private` **getCacheEntry**(`productId`, `regionId`): `Promise`<``null`` \| `TaxServiceRate`[]\>
Gets the cache results for a set of ids
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product id to cache |
| `regionId` | `string` | the region id to cache |
#### Returns
`Promise`<``null`` \| `TaxServiceRate`[]\>
the cached result or null
#### Defined in
[services/tax-provider.ts:450](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L450)
___
### getCacheKey
▸ `Private` **getCacheKey**(`productId`, `regionId`): `string`
The cache key to get cache hits by.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product id to cache |
| `regionId` | `string` | the region id to cache |
#### Returns
`string`
the cache key to use for the id set
#### Defined in
[services/tax-provider.ts:419](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L419)
___
### getRegionRatesForProduct
▸ **getRegionRatesForProduct**(`productId`, `region`): `Promise`<`TaxServiceRate`[]\>
Gets the tax rates configured for a product. The rates are cached between
calls.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product id to get rates for |
| `region` | `Region` | the region to get configured rates for. |
#### Returns
`Promise`<`TaxServiceRate`[]\>
the tax rates configured for the shipping option.
#### Defined in
[services/tax-provider.ts:374](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L374)
___
### getRegionRatesForShipping
▸ **getRegionRatesForShipping**(`optionId`, `region`): `Promise`<`TaxServiceRate`[]\>
Gets the tax rates configured for a shipping option. The rates are cached
between calls.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `optionId` | `string` | the option id of the shipping method. |
| `region` | `Region` | the region to get configured rates for. |
#### Returns
`Promise`<`TaxServiceRate`[]\>
the tax rates configured for the shipping option.
#### Defined in
[services/tax-provider.ts:327](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L327)
___
### getShippingTaxLines
▸ **getShippingTaxLines**(`shippingMethod`, `calculationContext`): `Promise`<`ShippingMethodTaxLine`[]\>
Gets the relevant tax lines for a shipping method. Note: this method
doesn't persist the tax lines. Use createShippingTaxLines if you wish to
persist the tax lines to the DB layer.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `shippingMethod` | `ShippingMethod` | the shipping method to get tax lines for |
| `calculationContext` | `TaxCalculationContext` | the calculation context to get tax lines by |
#### Returns
`Promise`<`ShippingMethodTaxLine`[]\>
the computed tax lines
#### Defined in
[services/tax-provider.ts:185](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L185)
___
### getTaxLines
▸ **getTaxLines**(`lineItems`, `calculationContext`): `Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
Gets the relevant tax lines for an order or cart. If an order is provided
the order's tax lines will be returned. If a cart is provided the tax lines
will be computed from the tax rules and potentially a 3rd party tax plugin.
Note: this method doesn't persist the tax lines. Use createTaxLines if you
wish to persist the tax lines to the DB layer.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `lineItems` | `LineItem`[] | the cart or order to get tax lines for |
| `calculationContext` | `TaxCalculationContext` | the calculation context to get tax lines by |
#### Returns
`Promise`<(`ShippingMethodTaxLine` \| `LineItemTaxLine`)[]\>
the computed tax lines
#### Defined in
[services/tax-provider.ts:237](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L237)
___
### list
▸ **list**(): `Promise`<`TaxProvider`[]\>
#### Returns
`Promise`<`TaxProvider`[]\>
#### Defined in
[services/tax-provider.ts:70](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L70)
___
### registerInstalledProviders
▸ **registerInstalledProviders**(`providers`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `providers` | `string`[] |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-provider.ts:471](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L471)
___
### retrieveProvider
▸ **retrieveProvider**(`region`): `ITaxService`
Retrieves the relevant tax provider for the given region.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `region` | `Region` | the region to get tax provider for. |
#### Returns
`ITaxService`
the region specific tax provider
#### Defined in
[services/tax-provider.ts:80](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L80)
___
### setCache
▸ `Private` **setCache**(`productId`, `regionId`, `value`): `Promise`<`void`\>
Sets the cache results for a set of ids
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `productId` | `string` | the product id to cache |
| `regionId` | `string` | the region id to cache |
| `value` | `TaxServiceRate`[] | tax rates to cache |
#### Returns
`Promise`<`void`\>
promise that resolves after the cache has been set
#### Defined in
[services/tax-provider.ts:430](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L430)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`TaxProviderService`](TaxProviderService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`TaxProviderService`](TaxProviderService.md)
#### Defined in
[services/tax-provider.ts:57](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-provider.ts#L57)
@@ -0,0 +1,392 @@
# Class: TaxRateService
## Hierarchy
- `"medusa-interfaces"`
↳ **`TaxRateService`**
## Constructors
### constructor
• **new TaxRateService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `Object` |
#### Overrides
BaseService.constructor
#### Defined in
[services/tax-rate.ts:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L27)
## Properties
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/tax-rate.ts:21](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L21)
___
### productService\_
• `Private` **productService\_**: [`ProductService`](ProductService.md)
#### Defined in
[services/tax-rate.ts:22](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L22)
___
### productTypeService\_
• `Private` **productTypeService\_**: [`ProductTypeService`](ProductTypeService.md)
#### Defined in
[services/tax-rate.ts:23](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L23)
___
### shippingOptionService\_
• `Private` **shippingOptionService\_**: [`ShippingOptionService`](ShippingOptionService.md)
#### Defined in
[services/tax-rate.ts:24](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L24)
___
### taxRateRepository\_
• `Private` **taxRateRepository\_**: typeof `TaxRateRepository`
#### Defined in
[services/tax-rate.ts:25](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L25)
## Methods
### addToProduct
▸ **addToProduct**(`id`, `productIds`, `replace?`): `Promise`<`ProductTaxRate` \| `ProductTaxRate`[]\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `string` | `undefined` |
| `productIds` | `string` \| `string`[] | `undefined` |
| `replace` | `boolean` | `false` |
#### Returns
`Promise`<`ProductTaxRate` \| `ProductTaxRate`[]\>
#### Defined in
[services/tax-rate.ts:197](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L197)
___
### addToProductType
▸ **addToProductType**(`id`, `productTypeIds`, `replace?`): `Promise`<`ProductTypeTaxRate`[]\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `string` | `undefined` |
| `productTypeIds` | `string` \| `string`[] | `undefined` |
| `replace` | `boolean` | `false` |
#### Returns
`Promise`<`ProductTypeTaxRate`[]\>
#### Defined in
[services/tax-rate.ts:233](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L233)
___
### addToShippingOption
▸ **addToShippingOption**(`id`, `optionIds`, `replace?`): `Promise`<`ShippingTaxRate`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `id` | `string` | `undefined` |
| `optionIds` | `string` \| `string`[] | `undefined` |
| `replace` | `boolean` | `false` |
#### Returns
`Promise`<`ShippingTaxRate`\>
#### Defined in
[services/tax-rate.ts:273](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L273)
___
### create
▸ **create**(`data`): `Promise`<`TaxRate`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `data` | `CreateTaxRateInput` |
#### Returns
`Promise`<`TaxRate`\>
#### Defined in
[services/tax-rate.ts:104](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L104)
___
### delete
▸ **delete**(`id`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` \| `string`[] |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-rate.ts:135](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L135)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`TaxRate`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `selector` | `FilterableTaxRateProps` |
| `config` | `FindConfig`<`TaxRate`\> |
#### Returns
`Promise`<`TaxRate`[]\>
#### Defined in
[services/tax-rate.ts:62](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L62)
___
### listAndCount
▸ **listAndCount**(`selector`, `config?`): `Promise`<[`TaxRate`[], `number`]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `selector` | `FilterableTaxRateProps` |
| `config` | `FindConfig`<`TaxRate`\> |
#### Returns
`Promise`<[`TaxRate`[], `number`]\>
#### Defined in
[services/tax-rate.ts:73](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L73)
___
### listByProduct
▸ **listByProduct**(`productId`, `config`): `Promise`<`TaxRate`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `productId` | `string` |
| `config` | `TaxRateListByConfig` |
#### Returns
`Promise`<`TaxRate`[]\>
#### Defined in
[services/tax-rate.ts:321](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L321)
___
### listByShippingOption
▸ **listByShippingOption**(`shippingOptionId`, `config`): `Promise`<`TaxRate`[]\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `shippingOptionId` | `string` |
| `config` | `TaxRateListByConfig` |
#### Returns
`Promise`<`TaxRate`[]\>
#### Defined in
[services/tax-rate.ts:332](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L332)
___
### removeFromProduct
▸ **removeFromProduct**(`id`, `productIds`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `productIds` | `string` \| `string`[] |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-rate.ts:143](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L143)
___
### removeFromProductType
▸ **removeFromProductType**(`id`, `typeIds`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `typeIds` | `string` \| `string`[] |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-rate.ts:161](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L161)
___
### removeFromShippingOption
▸ **removeFromShippingOption**(`id`, `optionIds`): `Promise`<`void`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `optionIds` | `string` \| `string`[] |
#### Returns
`Promise`<`void`\>
#### Defined in
[services/tax-rate.ts:179](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L179)
___
### retrieve
▸ **retrieve**(`id`, `config?`): `Promise`<`TaxRate`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `config` | `FindConfig`<`TaxRate`\> |
#### Returns
`Promise`<`TaxRate`\>
#### Defined in
[services/tax-rate.ts:84](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L84)
___
### update
▸ **update**(`id`, `data`): `Promise`<`TaxRate`\>
#### Parameters
| Name | Type |
| :------ | :------ |
| `id` | `string` |
| `data` | `UpdateTaxRateInput` |
#### Returns
`Promise`<`TaxRate`\>
#### Defined in
[services/tax-rate.ts:120](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L120)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`TaxRateService`](TaxRateService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`TaxRateService`](TaxRateService.md)
#### Defined in
[services/tax-rate.ts:43](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/tax-rate.ts#L43)
@@ -0,0 +1,607 @@
# Class: TotalsService
A service that calculates total and subtotals for orders, carts etc..
**`implements`** {BaseService}
## Hierarchy
- `"medusa-interfaces"`
↳ **`TotalsService`**
## Constructors
### constructor
• **new TotalsService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `TotalsServiceProps` |
#### Overrides
BaseService.constructor
#### Defined in
[services/totals.ts:90](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L90)
## Properties
### taxCalculationStrategy\_
• `Private` **taxCalculationStrategy\_**: `ITaxCalculationStrategy`
#### Defined in
[services/totals.ts:88](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L88)
___
### taxProviderService\_
• `Private` **taxProviderService\_**: [`TaxProviderService`](TaxProviderService.md)
#### Defined in
[services/totals.ts:87](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L87)
## Methods
### calculateDiscount\_
▸ **calculateDiscount_**(`lineItem`, `variant`, `variantPrice`, `value`, `discountType`): `LineDiscount`
Calculates either fixed or percentage discount of a variant
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `lineItem` | `LineItem` | id of line item |
| `variant` | `string` | id of variant in line item |
| `variantPrice` | `number` | price of the variant based on region |
| `value` | `number` | discount value |
| `discountType` | `DiscountRuleType` | the type of discount (fixed or percentage) |
#### Returns
`LineDiscount`
triples of lineitem, variant and applied discount
#### Defined in
[services/totals.ts:545](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L545)
___
### getAllocationItemDiscounts
▸ **getAllocationItemDiscounts**(`discount`, `cart`): `LineDiscount`[]
If the rule of a discount has allocation="item", then we need
to calculate discount on each item in the cart. Furthermore, we need to
make sure to only apply the discount on valid variants. And finally we
return ether an array of percentages discounts or fixed discounts
alongside the variant on which the discount was applied.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `discount` | `Discount` | the discount to which we do the calculation |
| `cart` | `Cart` \| `Order` | the cart to calculate discounts for |
#### Returns
`LineDiscount`[]
array of triples of lineitem, variant and applied discount
#### Defined in
[services/totals.ts:587](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L587)
___
### getAllocationMap
▸ **getAllocationMap**(`orderOrCart`, `options?`): `LineAllocationsMap`
Gets a map of discounts and gift cards that apply to line items in an
order. The function calculates the amount of a discount or gift card that
applies to a specific line item.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `orderOrCart` | `Cart` \| `Order` | the order or cart to get an allocation map for |
| `options` | `AllocationMapOptions` | controls what should be included in allocation map |
#### Returns
`LineAllocationsMap`
the allocation map for the line items in the cart or order.
#### Defined in
[services/totals.ts:368](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L368)
___
### getCalculationContext
▸ **getCalculationContext**(`cartOrOrder`, `options?`): `TaxCalculationContext`
Prepares the calculation context for a tax total calculation.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to get the calculation context for |
| `options` | `CalculationContextOptions` | options to gather context by |
#### Returns
`TaxCalculationContext`
the tax calculation context
#### Defined in
[services/totals.ts:892](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L892)
___
### getDiscountTotal
▸ **getDiscountTotal**(`cartOrOrder`): `number`
Calculates the total discount amount for each of the different supported
discount types. If discounts aren't present or invalid returns 0.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to calculate discounts for |
#### Returns
`number`
the total discounts amount
#### Defined in
[services/totals.ts:858](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L858)
___
### getGiftCardTotal
▸ **getGiftCardTotal**(`cartOrOrder`): `number`
Gets the gift card amount on a cart or order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to get gift card amount for |
#### Returns
`number`
the gift card amount applied to the cart or order
#### Defined in
[services/totals.ts:830](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L830)
___
### getLineDiscounts
▸ **getLineDiscounts**(`cartOrOrder`, `discount`): `LineDiscountAmount`[]
Returns the discount amount allocated to the line items of an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to get line discount allocations for |
| `discount` | `Discount` | the discount to use as context for the calculation |
#### Returns
`LineDiscountAmount`[]
the allocations that the discount has on the items in the cart or
order
#### Defined in
[services/totals.ts:638](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L638)
___
### getLineItemAdjustmentsTotal
▸ **getLineItemAdjustmentsTotal**(`cartOrOrder`): `number`
#### Parameters
| Name | Type |
| :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` |
#### Returns
`number`
#### Defined in
[services/totals.ts:615](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L615)
___
### getLineItemDiscountAdjustment
▸ **getLineItemDiscountAdjustment**(`lineItem`, `discount`): `number`
#### Parameters
| Name | Type |
| :------ | :------ |
| `lineItem` | `LineItem` |
| `discount` | `Discount` |
#### Returns
`number`
#### Defined in
[services/totals.ts:600](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L600)
___
### getLineItemRefund
▸ **getLineItemRefund**(`order`, `lineItem`): `number`
The amount that can be refunded for a given line item.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | order to use as context for the calculation |
| `lineItem` | `LineItem` | the line item to calculate the refund amount for. |
#### Returns
`number`
the line item refund amount.
#### Defined in
[services/totals.ts:460](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L460)
___
### getLineItemTotal
▸ **getLineItemTotal**(`lineItem`, `cartOrOrder`, `options?`): `Promise`<`number`\>
Gets a total for a line item. The total can take gift cards, discounts and
taxes into account. This can be controlled through the options.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `lineItem` | `LineItem` | the line item to calculate a total for |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to use as context for the calculation |
| `options` | `GetLineItemTotalOptions` | the options to use for the calculation |
#### Returns
`Promise`<`number`\>
the line item total
#### Defined in
[services/totals.ts:800](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L800)
___
### getLineItemTotals
▸ **getLineItemTotals**(`lineItem`, `cartOrOrder`, `options?`): `Promise`<`LineItemTotals`\>
Breaks down the totals related to a line item; these are the subtotal, the
amount of discount applied to the line item, the amount of a gift card
applied to a line item and the amount of tax applied to a line item.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `lineItem` | `LineItem` | the line item to calculate totals for |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to use as context for the calculation |
| `options` | `LineItemTotalsOptions` | the options to evaluate the line item totals for |
#### Returns
`Promise`<`LineItemTotals`\>
the breakdown of the line item totals
#### Defined in
[services/totals.ts:684](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L684)
___
### getPaidTotal
▸ **getPaidTotal**(`order`): `number`
Gets the total payments made on an order
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to calculate paid amount for |
#### Returns
`number`
the total paid amount
#### Defined in
[services/totals.ts:125](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L125)
___
### getRefundTotal
▸ **getRefundTotal**(`order`, `lineItems`): `number`
Calculates refund total of line items.
If any of the items to return have been discounted, we need to
apply the discount again before refunding them.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | cart or order to calculate subtotal for |
| `lineItems` | `LineItem`[] | the line items to calculate refund total for |
#### Returns
`number`
the calculated subtotal
#### Defined in
[services/totals.ts:504](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L504)
___
### getRefundedTotal
▸ **getRefundedTotal**(`order`): `number`
Gets the total refund amount for an order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to get total refund amount for. |
#### Returns
`number`
the total refunded amount for an order.
#### Defined in
[services/totals.ts:445](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L445)
___
### getShippingMethodTotals
▸ **getShippingMethodTotals**(`shippingMethod`, `cartOrOrder`, `opts?`): `Promise`<`ShippingMethodTotals`\>
Gets the totals breakdown for a shipping method. Fetches tax lines if not
already provided.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `shippingMethod` | `ShippingMethod` | the shipping method to get totals breakdown for. |
| `cartOrOrder` | `Cart` \| `Order` | the cart or order to use as context for the breakdown |
| `opts` | `GetShippingMethodTotalsOptions` | options for what should be included |
#### Returns
`Promise`<`ShippingMethodTotals`\>
An object that breaks down the totals for the shipping method
#### Defined in
[services/totals.ts:159](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L159)
___
### getShippingTotal
▸ **getShippingTotal**(`cartOrOrder`): `number`
Calculates shipping total
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | cart or order to calculate subtotal for |
#### Returns
`number`
shipping total
#### Defined in
[services/totals.ts:267](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L267)
___
### getSubtotal
▸ **getSubtotal**(`cartOrOrder`, `opts?`): `number`
Calculates subtotal of a given cart or order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | cart or order to calculate subtotal for |
| `opts` | `SubtotalOptions` | options |
#### Returns
`number`
the calculated subtotal
#### Defined in
[services/totals.ts:243](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L243)
___
### getSwapTotal
▸ **getSwapTotal**(`order`): `number`
The total paid for swaps. May be negative in case of negative swap
difference.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `order` | `Order` | the order to calculate swap total for |
#### Returns
`number`
the swap total
#### Defined in
[services/totals.ts:140](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L140)
___
### getTaxTotal
▸ **getTaxTotal**(`cartOrOrder`, `forceTaxes?`): `Promise`<``null`` \| `number`\>
Calculates tax total
Currently based on the Danish tax system
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | `undefined` | cart or order to calculate tax total for |
| `forceTaxes` | `boolean` | `false` | whether taxes should be calculated regardless of region settings |
#### Returns
`Promise`<``null`` \| `number`\>
tax total
#### Defined in
[services/totals.ts:282](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L282)
___
### getTotal
▸ **getTotal**(`cartOrOrder`, `options?`): `Promise`<`number`\>
Calculates subtotal of a given cart or order.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `cartOrOrder` | `Cart` \| `Order` | object to calculate total for |
| `options` | `GetTotalsOptions` | options to calculate by |
#### Returns
`Promise`<`number`\>
the calculated subtotal
#### Defined in
[services/totals.ts:106](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L106)
___
### rounded
▸ **rounded**(`value`): `number`
Rounds a number using Math.round.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `value` | `number` | the value to round |
#### Returns
`number`
the rounded value
#### Defined in
[services/totals.ts:922](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/totals.ts#L922)
@@ -0,0 +1,35 @@
# Class: TransactionService
## Hierarchy
- `"medusa-interfaces"`
↳ **`TransactionService`**
## Constructors
### constructor
• **new TransactionService**()
#### Overrides
BaseService.constructor
#### Defined in
[services/transaction.js:5](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/transaction.js#L5)
## Methods
### createSession
▸ **createSession**(): `Promise`<`ClientSession`\>
#### Returns
`Promise`<`ClientSession`\>
#### Defined in
[services/transaction.js:9](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/transaction.js#L9)
@@ -0,0 +1,384 @@
# Class: UserService
Provides layer to manipulate users.
## Hierarchy
- `"medusa-interfaces"`
↳ **`UserService`**
## Constructors
### constructor
• **new UserService**(`__namedParameters`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `__namedParameters` | `UserServiceProps` |
#### Overrides
BaseService.constructor
#### Defined in
[services/user.ts:36](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L36)
## Properties
### eventBus\_
• `Private` **eventBus\_**: [`EventBusService`](EventBusService.md)
#### Defined in
[services/user.ts:32](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L32)
___
### manager\_
• `Private` **manager\_**: `EntityManager`
#### Defined in
[services/user.ts:33](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L33)
___
### transactionManager\_
• `Private` **transactionManager\_**: `EntityManager`
#### Defined in
[services/user.ts:34](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L34)
___
### userRepository\_
• `Private` **userRepository\_**: typeof `UserRepository`
#### Defined in
[services/user.ts:31](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L31)
___
### Events
▪ `Static` **Events**: `Object`
#### Type declaration
| Name | Type |
| :------ | :------ |
| `PASSWORD_RESET` | `string` |
#### Defined in
[services/user.ts:27](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L27)
## Methods
### create
▸ **create**(`user`, `password`): `Promise`<`User`\>
Creates a user with username being validated.
Fails if email is not a valid format.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `user` | `CreateUserInput` | the user to create |
| `password` | `string` | user's password to hash |
#### Returns
`Promise`<`User`\>
the result of create
#### Defined in
[services/user.ts:188](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L188)
___
### delete
▸ **delete**(`userId`): `Promise`<``null``\>
Deletes a user from a given user id.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `userId` | `string` | the id of the user to delete. Must be castable as an ObjectId |
#### Returns
`Promise`<``null``\>
the result of the delete operation.
#### Defined in
[services/user.ts:257](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L257)
___
### generateResetPasswordToken
▸ **generateResetPasswordToken**(`userId`): `Promise`<`string`\>
Generate a JSON Web token, that will be sent to a user, that wishes to
reset password.
The token will be signed with the users current password hash as a secret
a long side a payload with userId and the expiry time for the token, which
is always 15 minutes.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `userId` | `string` | the id of the user to reset password for |
#### Returns
`Promise`<`string`\>
the generated JSON web token
#### Defined in
[services/user.ts:311](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L311)
___
### hashPassword\_
▸ **hashPassword_**(`password`): `Promise`<`string`\>
Hashes a password
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `password` | `string` | the value to hash |
#### Returns
`Promise`<`string`\>
hashed password
#### Defined in
[services/user.ts:176](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L176)
___
### list
▸ **list**(`selector`, `config?`): `Promise`<`User`[]\>
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `selector` | `FilterableUserProps` | the query object for find |
| `config` | `Object` | the configuration object for the query |
#### Returns
`Promise`<`User`[]\>
the result of the find operation
#### Defined in
[services/user.ts:88](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L88)
___
### retrieve
▸ **retrieve**(`userId`, `config?`): `Promise`<`User`\>
Gets a user by id.
Throws in case of DB Error and if user was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `userId` | `string` | the id of the user to get. |
| `config` | `FindConfig`<`User`\> | query configs |
#### Returns
`Promise`<`User`\>
the user document.
#### Defined in
[services/user.ts:100](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L100)
___
### retrieveByApiToken
▸ **retrieveByApiToken**(`apiToken`, `relations?`): `Promise`<`User`\>
Gets a user by api token.
Throws in case of DB Error and if user was not found.
#### Parameters
| Name | Type | Default value | Description |
| :------ | :------ | :------ | :------ |
| `apiToken` | `string` | `undefined` | the token of the user to get. |
| `relations` | `string`[] | `[]` | relations to include with the user |
#### Returns
`Promise`<`User`\>
the user document.
#### Defined in
[services/user.ts:124](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L124)
___
### retrieveByEmail
▸ **retrieveByEmail**(`email`, `config?`): `Promise`<`User`\>
Gets a user by email.
Throws in case of DB Error and if user was not found.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `email` | `string` | the email of the user to get. |
| `config` | `FindConfig`<`User`\> | query config |
#### Returns
`Promise`<`User`\>
the user document.
#### Defined in
[services/user.ts:152](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L152)
___
### setPassword\_
▸ **setPassword_**(`userId`, `password`): `Promise`<`User`\>
Sets a password for a user
Fails if no user exists with userId and if the hashing of the new
password does not work.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `userId` | `string` | the userId to set password for |
| `password` | `string` | the old password to set |
#### Returns
`Promise`<`User`\>
the result of the update operation
#### Defined in
[services/user.ts:282](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L282)
___
### update
▸ **update**(`userId`, `update`): `Promise`<`User`\>
Updates a user.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `userId` | `string` | id of the user to update |
| `update` | `UpdateUserInput` | the values to be updated on the user |
#### Returns
`Promise`<`User`\>
the result of create
#### Defined in
[services/user.ts:216](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L216)
___
### validateEmail\_
▸ **validateEmail_**(`email`): `string`
Used to validate user email.
#### Parameters
| Name | Type | Description |
| :------ | :------ | :------ |
| `email` | `string` | email to validate |
#### Returns
`string`
the validated email
#### Defined in
[services/user.ts:70](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L70)
___
### withTransaction
▸ **withTransaction**(`transactionManager`): [`UserService`](UserService.md)
#### Parameters
| Name | Type |
| :------ | :------ |
| `transactionManager` | `EntityManager` |
#### Returns
[`UserService`](UserService.md)
#### Defined in
[services/user.ts:49](https://github.com/medusajs/medusa/blob/2d3e404f/packages/medusa/src/services/user.ts#L49)
+45
View File
@@ -0,0 +1,45 @@
# Services Reference
## Classes
- [AuthService](classes/AuthService.md)
- [CartService](classes/CartService.md)
- [ClaimItemService](classes/ClaimItemService.md)
- [ClaimService](classes/ClaimService.md)
- [CustomShippingOptionService](classes/CustomShippingOptionService.md)
- [CustomerGroupService](classes/CustomerGroupService.md)
- [CustomerService](classes/CustomerService.md)
- [DiscountService](classes/DiscountService.md)
- [DraftOrderService](classes/DraftOrderService.md)
- [EventBusService](classes/EventBusService.md)
- [FulfillmentProviderService](classes/FulfillmentProviderService.md)
- [FulfillmentService](classes/FulfillmentService.md)
- [GiftCardService](classes/GiftCardService.md)
- [IdempotencyKeyService](classes/IdempotencyKeyService.md)
- [InventoryService](classes/InventoryService.md)
- [LineItemService](classes/LineItemService.md)
- [MiddlewareService](classes/MiddlewareService.md)
- [NoteService](classes/NoteService.md)
- [NotificationService](classes/NotificationService.md)
- [OauthService](classes/OauthService.md)
- [OrderService](classes/OrderService.md)
- [PaymentProviderService](classes/PaymentProviderService.md)
- [ProductCollectionService](classes/ProductCollectionService.md)
- [ProductService](classes/ProductService.md)
- [ProductTypeService](classes/ProductTypeService.md)
- [ProductVariantService](classes/ProductVariantService.md)
- [QueryBuilderService](classes/QueryBuilderService.md)
- [RegionService](classes/RegionService.md)
- [ReturnReasonService](classes/ReturnReasonService.md)
- [ReturnService](classes/ReturnService.md)
- [SearchService](classes/SearchService.md)
- [ShippingOptionService](classes/ShippingOptionService.md)
- [ShippingProfileService](classes/ShippingProfileService.md)
- [StoreService](classes/StoreService.md)
- [SwapService](classes/SwapService.md)
- [SystemPaymentProviderService](classes/SystemPaymentProviderService.md)
- [TaxProviderService](classes/TaxProviderService.md)
- [TaxRateService](classes/TaxRateService.md)
- [TotalsService](classes/TotalsService.md)
- [TransactionService](classes/TransactionService.md)
- [UserService](classes/UserService.md)
@@ -1,126 +0,0 @@
---
title: Set up your development environment
---
# Set up your development environment
## Introduction
Welcome to Medusa - we are so excited to get you on board!
This tutorial will walk you through the steps to take to set up your local development environment. You will familiarize yourself with some of the core parts that make Medusa work and learn how to configure your development environment. Furthermore you will be introduced to how the plugin architecture works and how to customize your commerce functionalities with custom logic and endpoints.
<!-- As a final part of the tutorial you will be linking your local project to Medusa Cloud where you can leverage advanced tools that make it easy to develop, test and deploy your Medusa project. -->
## Background Knowledge and Prerequisites
This tutorial aims to be as inclusive as possible so that most people with a bit of web development exeperience will be able to follow along and understand what is going on. In case you are completely new to programming and are just setting out to start working on your first project it will be helpful to familiarize yourself with a couple of the technologies that Medusa is build on
- **JavaScript**: The programming language that Medusa is written in. It is the language that runs in your browser to create dynamic web applications and has over the past decade gained a lot of traction as a backend language. If you wish to customize or extend Medusa it is highly recommended that you learn how JavaScript works. You can learn more about JavaScript with the [Basic JavaScript course from freeCodeCamp.](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-javascript)
- **SQL & Postgresql**: Medusa uses the relational database PostgreSQL as the database layer where data is persisted. To understand how different entities relate to each other in Medusa it is helpful to have a good understanding of SQL. You can learn more about SQL and relational databases with the [SQL and Databases course from freeCodeCamp.](https://www.freecodecamp.org/news/sql-and-databases-full-course/)
- The **command line**: The command line is a text interface for your computer. It is used to run commands such as starting a program, performing a task or interfacing with the files on your computer. If you have never used the command line before you can check out [this tutorial](https://www.learnenough.com/command-line-tutorial) to get the basics in place.
To get a further understanding of what powers Medusa you can lookup these concepts:
- [**REST APIs**](https://en.wikipedia.org/wiki/Representational_state_transfer)
- [**Dependency Injection**](https://en.wikipedia.org/wiki/Dependency_injection)
- [**Idempotency Keys**](https://brandur.org/idempotency-keys)
## Installations
To get your development environment ready you need to install the following tools:
- Node.js
- Git
- Postgresql
- Redis
- Medusa CLI
### Node.js
Node.js is an environment that can execute JavaScript code on outside of the browser making it possible to run on a server. Node.js is the environment that makes it possible for Medusa to run so you must install Node.js on your computer to start Medusa development.
Node.js has a bundled package manager called npm. npm helps you install "packages" which are small pieces of code that you can leverage in your Node.js applications. Medusa's core is itself a package distributed via npm and so are all of the plugins that exist around the core. [You can install Node.js from here.](https://nodejs.org/en/)
:::caution
Medusa supports Node versions 14 and 16. You can check which Node version you have using the following command:
```bash
node -v
```
:::
If you prefer using something like homebrew you can also run:
```
brew install node
```
:::tip
**Mac users**: Make sure that you have Xcode command line tools installed; if not run `xcode-select --install`
:::
### Git
Git is a version control system that keeps track on files within a project and makes it possible to do things like going back in history if you have made mistakes or collaborate with teammates without overriding each other's work. Almost all developers use Git for version control. Medusa uses git behind the scenes when you create a new project so you'll have to install it on your computer to get started.
If you are a Mac user you will already have Git installed as part of the Xcode command line tools, but for good measure check out installation of Git on different systems below:
- [Install Git on macOS](https://www.atlassian.com/git/tutorials/install-git)
- [Install Git on Windows](https://www.atlassian.com/git/tutorials/install-git#windows)
- [Install Git on Linux](https://www.atlassian.com/git/tutorials/install-git#linux)
### PostgreSQL
PostgreSQL is an open-source relational database system with more than 30 years of active development. It is robust, reliable and ensures data integrity so there's no need to worry about those when you scale your project. Medusa uses PostgreSQL as its database and you will need to install it on your computer to get going. [Install PostgreSQL from here.](https://www.postgresql.org/download/).
If you prefer to use homebrew you may install PostgreSQL by running:
```
brew install postgresql
brew services start postgresql
createdb
```
### Redis
Redis is an open-source in memory data structure store which is used in Medusa to emit messages in the system and cache data. [Install Redis from here.](https://redis.io/download)
If you prefer to use homebrew you may install Redis by running:
```
brew install redis
brew services start redis
```
### Medusa CLI
The final installation to do to get started with Medusa is the Medusa CLI, which is an npm package you can install globally on your computer to get instant access to commands that help you manage and run your Medusa project. As the Medusa CLI is distributed as an npm package it is very easily installed by running:
```bash npm2yarn
npm install @medusajs/medusa-cli -g
```
### Text editor
If you don't already have a text editor of choice you should find one you like - here is a couple of candidates:
- [Neovim](https://neovim.io/) (if you are super oldschool there's also plain [Vim](https://www.vim.org/))
- [VS Code](https://code.visualstudio.com/)
- [Atom](https://atom.io/)
It is not important which editor you use as long as you feel comfortable working with it.
<!-- ## Medusa Cloud account
As the final step in this part of the tutorial you should create a Medusa Cloud account. Medusa Cloud is the platform that works with Medusa; the platform is where you view and manage your store, but is also a key part of the development process as you will be linking your local project to the platform so that you can manage your store while in development.
[Sign up for Medusa Cloud](https://app.medusajs.com) -->
## Summary
You now have all required software installed on your computer and have been introduced to a bit of our tech stack. In the next part of this tutorial we will be setting up a Medusa project for the first time and start making API requests.
@@ -0,0 +1,364 @@
import styles from './development.module.css';
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';
# Set up your development environment
This document will guide you to set up your development environment to efficiently and properly use Medusa.
## Prerequisite Background Knowledge
### JavaScript
Medusa is built with JavaScript. If you’re not familiar with JavaScript, it is the language that runs in your browser to create dynamic web applications and has over the past decade gained a lot of traction as a backend language. If you wish to customize or extend Medusa, it is highly recommended that you learn how JavaScript works.
You can learn more about JavaScript with the [Basic JavaScript course from freeCodeCamp.](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#basic-javascript)
### Express
Medusa uses [Express](https://expressjs.com), a Node.js web application framework, to create your ecommerce server. It facilitates creating REST APIs in Node.js. If you’re interested in customizing Medusa or understanding more about how it works, you should learn more about Express.
You can learn more about Node.js and Express with the [Free 8-hour-long Node.js + Express course from freeCodeCamp](https://www.freecodecamp.org/news/free-8-hour-node-express-course/).
### SQL
SQL is a programming language used to interact with relational databases and store data in your ecommerce server. To understand how different entities relate to each other in Medusa it is helpful to have a good understanding of SQL.
You can learn more about SQL and relational databases with the [SQL and Databases course from freeCodeCamp.](https://www.freecodecamp.org/news/sql-and-databases-full-course/)
### Command Line Interface (CLI)
To install and use Medusa, you’ll need to be familiar with CLI tools. If you’re not familiar with the command line, it is a text interface for your computer. It is used to run commands such as starting a program, performing a task, or interfacing with the files on your computer.
If you have never used the command line before you can check out [this tutorial](https://www.learnenough.com/command-line-tutorial) to get the basics in place.
### Additional Information
To get a further understanding of what powers Medusa you can lookup these concepts:
- [REST APIs](https://en.wikipedia.org/wiki/Representational_state_transfer)
- [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection)
- [Idempotency Keys](https://brandur.org/idempotency-keys)
## Installations[](https://docs.medusajs.com/tutorial/set-up-your-development-environment#installations)
To get your development environment ready you need to install the following tools:
- [Node.js](#nodejs)
- [Git](#git)
- [Postgresql](#postgresql)
- [Redis](#redis)
- [Medusa CLI](#medusa-cli)
- [Code Editor](#code-editor)
### Node.js
:::info
Node.js is an environment that can execute JavaScript code outside of the browser, making it possible to run on a server.
Node.js has a bundled package manager called NPM. NPM helps you install "packages" which are small pieces of code that you can leverage in your Node.js applications. Medusa's core is itself a package distributed via NPM and so are all of the plugins that exist around the core.
:::
Node.js is the environment that makes it possible for Medusa to run, so you must install Node.js on your computer to start Medusa development.
:::caution
Medusa supports versions 14 and 16 of Node.js. You can check your Node.js version using the following command:
```bash
node -v
```
:::
<Tabs groupId="operating-systems" wrapperClassName={styles.osTabs}>
<TabItem value="windows" label="Windows" default>
You can install the executable directly from [the Node.js website](https://nodejs.org/en/#home-downloadhead).
For other approaches, you can check out [Node.js’s guide](https://nodejs.org/en/download/package-manager/#windows-1).
</TabItem>
<TabItem value="linux" label="Linux">
You can use the following commands to install Node.js on Ubuntu:
```bash
#Ubuntu
sudo apt update
sudo apt install nodejs
```
For other Linux distributions, you can check out [Node.js’s guide](https://nodejs.org/en/download/package-manager/).
</TabItem>
<TabItem value="macos" label="macOS">
You can use the following commands to install Node.js on macOS:
<Tabs>
<TabItem value="homebrew" label="Homebrew">
```bash
brew install node
```
</TabItem>
<TabItem value="no-homebrew" label="Without Homebrew">
```bash
curl "https://nodejs.org/dist/latest/node-${VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg</a>.*|\1|p')}.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/"
```
</TabItem>
</Tabs>
For other approaches, you can check out [Node.js’s guide](https://nodejs.org/en/download/package-manager/#macos).
:::tip
Make sure that you have Xcode command line tools installed; if not, run the following command to install it: `xcode-select --install`
:::
</TabItem>
</Tabs>
### Git
:::info
Git is a version control system that keeps track of files within a project and makes it possible to do things like going back in history if you have made mistakes or collaborate with teammates without overriding each other's work.
:::
Medusa uses Git behind the scenes when you create a new project so you'll have to install it on your computer to get started.
<Tabs groupId="operating-systems" wrapperClassName={styles.osTabs}>
<TabItem value="windows" label="Windows" default>
To install Git on Windows, you need to [download the installable package](https://git-scm.com/download/win).
</TabItem>
<TabItem value="linux" label="Linux">
For Debian/Ubuntu, you can use the following command:
```bash
apt-get install git
```
As for other Linux distributions, please check [git’s guide](https://git-scm.com/download/linux).
</TabItem>
<TabItem value="macos" label="macOS">
You should already have Git installed as part of the Xcode command-line tools.
However, if for any reason you need to install it manually, you can install it with Homebrew:
```bash
brew install git
```
You can also check out [git’s guide](https://git-scm.com/download/mac) for more installation options.
</TabItem>
</Tabs>
### PostgreSQL
:::info
PostgreSQL is an open-source relational database system with more than 30 years of active development. It is robust, reliable, and ensures data integrity so there's no need to worry about those when you scale your project.
:::
Although you can use an SQLite database with Medusa which would require no necessary database installations, it is recommended to use a PostgreSQL database for your server.
<Tabs groupId="operating-systems" wrapperClassName={styles.osTabs}>
<TabItem value="windows" label="Windows">
You can [download the PostgreSQL Windows installer](https://www.postgresql.org/download/windows/) from their website.
</TabItem>
<TabItem value="linux" label="Linux">
If you’re using Ubuntu, you can use the following commands to download and install PostgreSQL:
```bash
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get -y install postgresql
```
For other distributions, you can check out [PostgreSQL’s website for more guides](https://www.postgresql.org/download/linux/).
</TabItem>
<TabItem value="macos" label="macOS">
You can download PostgreSQL on your macOS using [the installer on their website](https://www.postgresql.org/download/macosx/).
</TabItem>
</Tabs>
### Redis
:::info
Redis is an open-source in-memory data structure store. It can be used for distributing and emitting messages and caching, among other purposes.
:::
Medusa uses Redis as the event queue in the server. If you want to use subscribers to handle events such as when an order is placed and perform actions based on the events, then you need to install and configure Redis.
If you don’t install and configure Redis with your Medusa server, then it will work without any events-related features.
<Tabs groupId="operating-systems" wrapperClassName={styles.osTabs}>
<TabItem value="windows" label="Windows">
To use Redis on Windows, you must have [Windows Subsystem for Linux (WSL2) enabled](https://docs.microsoft.com/en-us/windows/wsl/install). This lets you run Linux binaries on Windows.
After installing and enabling WSL2, if you use an Ubuntu distribution you can run the following commands to install Redis:
```bash
sudo apt-add-repository ppa:redislabs/redis
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install redis-server
## Start Redis server
sudo service redis-server start
```
</TabItem>
<TabItem value="linux" label="Linux">
If you use Ubuntu you can use the following commands to install Redis:
```bash
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list
sudo apt-get update
sudo apt-get install redis
## Start Redis server
sudo service redis-server start
```
For other distributions, you can check out [Redis’ guide on this](https://redis.io/docs/getting-started/installation/install-redis-on-linux/).
</TabItem>
<TabItem value="macos" label="macOS">
You can install Redis on macOS using Homebrew with the following command:
```bash
brew install redis
## Start Redis server
brew services start redis
```
To install Redis without Homebrew you can check out [Redis’s guide on installing it from source](https://redis.io/docs/getting-started/installation/install-redis-from-source/).
</TabItem>
</Tabs>
### Medusa CLI
The final installation required to get started with Medusa is the Medusa CLI. It is an NPM package you can install globally on your machine to get instant access to commands that help you manage and run your Medusa project.
You can install Medusa’s CLI with the following command:
```bash npm2yarn
npm install @medusajs/medusa-cli -g
```
### Code editor
If you don't already have a code editor of choice, we recommend using [VSCode](https://code.visualstudio.com/) as it is a widely used IDE (Integrated Development Environment) by developers.
Here are some other options:
- [Atom](https://atom.io/)
- [Neovim](https://neovim.io/) (if you are super old school there's also plain [Vim](https://www.vim.org/))
It is not important which editor you use as long as you feel comfortable working with it.
## Configuring Your Server
After installing all the requirements mentioned above and following along with our [quickstart guide](../quickstart/quick-start.md), you need to configure some information on your server to connect it to some of the requirements you installed.
### PostgreSQL
After creating a new database schema in PostgreSQL, you need to add the URL to connect to it on your Medusa server.
To do that, add the following environment variable to the `.env` file on the root of your Medusa server:
```bash
DATABASE_URL=postgres://<USER>:<PASSWORD>@<HOST>:<PORT>/<DB_NAME>
```
Notice that there are some details in the URL above you need to fill in yourself:
- `<USER>`: the username of the user that has access to the database schema you created.
- `<PASSWORD>`: the password of the user that has access to the database schema you created.
- `<HOST>`: the hostname where the PostgreSQL database is hosted. In local development, you can use `localhost`.
- `<PORT>`: the port where the PostgreSQL database can be contacted on the host. By default, it’s 5432**.**
- `<DB_NAME>`: the name of the database schema you created.
Then, in `medusa-config.js`, change the following properties in the object `projecConfig`:
```jsx
module.exports = {
projectConfig: {
...,
database_url: DATABASE_URL,
database_type: "postgres",
// comment out or remove these lines:
// database_database: "./medusa-db.sql",
// database_type: "sqlite",
},
plugins,
};
```
The last recommended step is running the following command to migrate Medusa’s database schema into your database and seed the database with dummy data:
```bash npm2yarn
npm run seed
```
### Redis
After installing Redis and running the Redis server, you must configure Medusa to use it.
In `.env` add a new environment variable:
```bash
REDIS_URL=redis://localhost:6379
```
This is the default Redis URL to connect to, especially in development. However, if you’re deploying your server, have configured your Redis installation differently, or just need to check the format of the connection URL, you can check [this guide](https://github.com/lettuce-io/lettuce-core/wiki/Redis-URI-and-connection-details) for more details.
:::tip
If you use the default connection string mentioned here then you can skip over adding the environment variable.
:::
Then, in `medusa-config.js`, comment out the following line in the object `projectConfig`:
```jsx
redis_url: REDIS_URL,
```
## What’s Next 🚀
- Learn how to install a storefront with [Next.js](../starters/nextjs-medusa-starter.md) or [Gatsby](./../starters/gatsby-medusa-starter.md).
- Learn how to install the [Medusa Admin](../admin/quickstart.md).
@@ -1,96 +0,0 @@
---
title: Creating your Medusa server
---
# Creating your Medusa server
## Introduction
With the required software installed on your computer you are ready to start working on your first Medusa project.
In this part of the tutorial we will setup the skeleton for a Medusa store and will be making the first requests to your Medusa server.
Once you have completed this part of the tutorial you will have a powerful backend for digital commerce experiences. The server will be capable of handling orders, ensuring payments are going through, keeping basic product and customer data in sync, etc. You can use one of the frontend starters to quickly hook up your server to a presentation layer ([Gatsby](https://github.com/medusajs/gatsby-starter-medusa) or [Next](https://github.com/medusajs/nextjs-starter-medusa)).
## Setup a Medusa project
With Medusa CLI installed it is very easy to setup a new Medusa project, with the `new` command. In your command line run:
```shell
medusa new my-medusa-server --seed
```
The command will do a number of things:
- build a new project in a folder called my-medusa-server
- install the dependencies through yarn or npm
- setup a new git environment for version controlling your project
- create a database in postgres with the name my-medusa-server
- the `--seed` flag indicates that the database should be populated with some test data after the project has been set up
If you navigate to the root folder of your new project you will see the following files in your directory:
```
.
├── node_modules
├── src
│ ├── api
│ └── services
├── .babelrc
├── .gitignore
├── medusa-config.js
├── README.md
└── package.json
```
There is not a lot of files needed to get your Medusa store setup and this is all due to the fact that the main Medusa core (`@medusajs/medusa`) is installed as a dependency in your project giving you all the fundamental needs for a digital commerce experience.
Much of Medusa's power lies in the `medusa-config.js` which is the file that configures your store and orchestrates the plugins that you wish to use together with your store. There are some different types of plugin categories such as payment plugins, notification plugins and fulfillment plugins, but plugins can contain any form of extension that enhances your store.
For customizations that are more particular to your project you can extend your Medusa server by adding files in the `api` and `services` directories. More about customizing your server will follow in the following parts.
## Starting your Medusa server
:::note
For your server to run correctly you should configure your `COOKIE_SECRET` and `JWT_SECRET` environment variables by adding a `.env` file to the root of your Medusa project.
:::
After your project has been set up with `medusa new`, you can run the following commands to start your server:
```shell
cd my-medusa-server
medusa develop
```
If you ran the new command with the `--seed` flag you will already have products available in your store. To view these you can run the following command in your command line:
```shell
curl -X GET localhost:9000/store/products | python -m json.tool
```
## What's next?
At this point you are all set to start creating amazing digital commerce experiences. You can take a number of different routes from here and the next part of this tutorial will revolve around creating custom functionality within your Medusa project.
Other options you could take are:
### Add a frontend to your server
We have created two starters for you that can help you lay a foundation for your storefront. The starters work with your new server with minimal configuration simply clone the starters from here:
- [Nextjs Starter](https://github.com/medusajs/nextjs-starter-medusa)
- [Gatsby Starter](https://github.com/medusajs/gatsby-starter-medusa)
### Browse the API reference
In the API reference docs you can find all the available requests that are exposed by your new Medusa server. Interacting with the API is the first step to creating truly unique experiences.
### Setup Stripe as a payment provider (Guide coming soon)
One of the first things you may want to do when building out your store would be to add a payment provider. Your starter project comes with a dummy payment provider that simply fakes payments being processed. In the real world you want a payment provider that can handle credit card information securely and make sure that funds are being transferred to your account. Stripe is one of the most popular payment providers and Medusa has an official plugin that you can easily install in your project.
## Summary
In this part of the tutorial we have setup your first Medusa project using the `medusa new` command. You have now reached a key milestone as you are ready to start building your Medusa store; from here there are no limits to how you can use Medusa as you can customize and extend the functionality of the core. In the next part of the tutorial we will be exploring how you can add custom services and endpoints to fit your exact needs.
@@ -0,0 +1,10 @@
.osTabs {
background-color: #f4f4f4;
padding: 10px;
border-radius: 6.4px;
color: #000;
}
.osTabs li:not([aria-selected=true]) {
color: #000;
}
@@ -1,5 +1,67 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/discounts GET /admin/discounts/:id/conditions/:condition_id should get condition 1`] = `
Object {
"created_at": Any<String>,
"discount_rule": Object {
"allocation": "total",
"created_at": Any<String>,
"deleted_at": null,
"description": null,
"id": Any<String>,
"metadata": null,
"type": "percentage",
"updated_at": Any<String>,
"value": 10,
},
"discount_rule_id": Any<String>,
"id": "test-condition",
"operator": "in",
"type": "products",
"updated_at": Any<String>,
}
`;
exports[`/admin/discounts GET /admin/discounts/:id/conditions/:condition_id should get condition with expand + fields 1`] = `
Object {
"id": "test-condition",
"products": Array [
Object {
"collection_id": null,
"created_at": Any<String>,
"deleted_at": null,
"description": null,
"discountable": true,
"external_id": null,
"handle": null,
"height": null,
"hs_code": null,
"id": "test-product",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": Any<String>,
"status": "draft",
"subtitle": null,
"thumbnail": null,
"title": "Practical Frozen Fish",
"type_id": Any<String>,
"updated_at": Any<String>,
"weight": null,
"width": null,
},
],
"type": "products",
}
`;
exports[`/admin/discounts GET /admin/discounts/:id/conditions/:condition_id throws if condition does not belong to discount: DiscountCondition with id test-condition was not found for Discount test-discount-2 1`] = `"Request failed with status code 404"`;
exports[`/admin/discounts GET /admin/discounts/:id/conditions/:condition_id throws if condition does not exist: DiscountCondition with id test-condition was not found 1`] = `"Request failed with status code 404"`;
exports[`/admin/discounts POST /admin/discounts fails if multiple types of resources are provided on update 1`] = `
Object {
"message": "Only one of products, product_types is allowed, Only one of product_types, products is allowed",
@@ -14,3 +76,128 @@ Object {
"type": "duplicate_error",
}
`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions fails if more than one condition type is provided: Only one of products, customer_groups is allowed, Only one of customer_groups, products is allowed 1`] = `"Request failed with status code 400"`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions should create a condition 1`] = `
Object {
"code": "TEST",
"created_at": Any<String>,
"deleted_at": null,
"ends_at": null,
"id": "test-discount",
"is_disabled": false,
"is_dynamic": false,
"metadata": null,
"parent_discount": null,
"parent_discount_id": null,
"regions": Array [],
"rule": Object {
"allocation": "total",
"conditions": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"discount_rule_id": Any<String>,
"id": Any<String>,
"metadata": null,
"operator": "in",
"type": "products",
"updated_at": Any<String>,
},
],
"created_at": Any<String>,
"deleted_at": null,
"description": null,
"id": Any<String>,
"metadata": null,
"type": "percentage",
"updated_at": Any<String>,
"value": 10,
},
"rule_id": Any<String>,
"starts_at": Any<String>,
"updated_at": Any<String>,
"usage_count": 0,
"usage_limit": null,
"valid_duration": null,
}
`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions throws if discount does not exist: Discount with id does-not-exist was not found 1`] = `"Request failed with status code 404"`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions/:condition_id should update a condition 1`] = `
Object {
"code": "TEST",
"created_at": Any<String>,
"deleted_at": null,
"ends_at": null,
"id": "test-discount",
"is_disabled": false,
"is_dynamic": false,
"metadata": null,
"parent_discount_id": null,
"rule": Object {
"allocation": "total",
"conditions": Array [
Object {
"created_at": Any<String>,
"deleted_at": null,
"discount_rule_id": Any<String>,
"id": Any<String>,
"metadata": null,
"operator": "in",
"products": Array [
Object {
"collection_id": null,
"created_at": Any<String>,
"deleted_at": null,
"description": null,
"discountable": true,
"external_id": null,
"handle": null,
"height": null,
"hs_code": null,
"id": "test-product",
"is_giftcard": false,
"length": null,
"material": null,
"metadata": null,
"mid_code": null,
"origin_country": null,
"profile_id": Any<String>,
"status": "draft",
"subtitle": null,
"thumbnail": null,
"title": "Practical Frozen Fish",
"type_id": Any<String>,
"updated_at": Any<String>,
"weight": null,
"width": null,
},
],
"type": "products",
"updated_at": Any<String>,
},
],
"created_at": Any<String>,
"deleted_at": null,
"description": null,
"id": Any<String>,
"metadata": null,
"type": "percentage",
"updated_at": Any<String>,
"value": 10,
},
"rule_id": Any<String>,
"starts_at": Any<String>,
"updated_at": Any<String>,
"usage_count": 0,
"usage_limit": null,
"valid_duration": null,
}
`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions/:condition_id throws if condition does not exist: DiscountCondition with id does-not-exist was not found for Discount test-discount 1`] = `"Request failed with status code 404"`;
exports[`/admin/discounts POST /admin/discounts/:id/conditions/:condition_id throws if discount does not exist: Discount with id does-not-exist was not found 1`] = `"Request failed with status code 404"`;
@@ -149,6 +149,37 @@ Object {
}
`;
exports[`/admin/price-lists POST /admin/price-lists/:id updates price list prices (inser a new MA for a specific region) 1`] = `
Array [
Object {
"amount": 101,
"created_at": Any<String>,
"currency_code": "eur",
"deleted_at": null,
"id": Any<String>,
"max_quantity": null,
"min_quantity": null,
"price_list_id": "pl_with_some_ma",
"region_id": "region-pl",
"updated_at": Any<String>,
"variant_id": "test-variant",
},
Object {
"amount": 1001,
"created_at": Any<String>,
"currency_code": "usd",
"deleted_at": null,
"id": "ma_test_4",
"max_quantity": null,
"min_quantity": null,
"price_list_id": "pl_with_some_ma",
"region_id": null,
"updated_at": Any<String>,
"variant_id": "test-variant",
},
]
`;
exports[`/admin/price-lists POST /admin/price-lists/:id updates the amount and currency of a price in the price list 1`] = `
Object {
"amount": 250,
@@ -291,3 +322,47 @@ Array [
},
]
`;
exports[`/admin/price-lists POST /admin/price-lists/:id/prices/batch Adds a batch of new prices where a MA record have a \`region_id\` instead of \`currency_code\` 1`] = `
Array [
Object {
"amount": 70,
"created_at": Any<String>,
"currency_code": "usd",
"deleted_at": null,
"id": "ma_test_4",
"max_quantity": null,
"min_quantity": null,
"price_list_id": "pl_with_some_ma",
"region_id": null,
"updated_at": Any<String>,
"variant_id": "test-variant",
},
Object {
"amount": 100,
"created_at": Any<String>,
"currency_code": "eur",
"deleted_at": null,
"id": Any<String>,
"max_quantity": null,
"min_quantity": null,
"price_list_id": "pl_with_some_ma",
"region_id": "region-pl",
"updated_at": Any<String>,
"variant_id": "test-variant",
},
Object {
"amount": 200,
"created_at": Any<String>,
"currency_code": "usd",
"deleted_at": null,
"id": Any<String>,
"max_quantity": null,
"min_quantity": null,
"price_list_id": "pl_with_some_ma",
"region_id": null,
"updated_at": Any<String>,
"variant_id": "test-variant",
},
]
`;
@@ -22,3 +22,26 @@ Array [
},
]
`;
exports[`/admin/product-tags GET /admin/product-tags returns a list of product tags matching free text search param 1`] = `
Array [
Object {
"created_at": Any<String>,
"id": "tag1",
"updated_at": Any<String>,
"value": "123",
},
Object {
"created_at": Any<String>,
"id": "tag3",
"updated_at": Any<String>,
"value": "123",
},
Object {
"created_at": Any<String>,
"id": "tag4",
"updated_at": Any<String>,
"value": "123",
},
]
`;
@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/product-types GET /admin/product-types returns a list of product types 1`] = `
Array [
Object {
"created_at": Any<String>,
"id": "test-type",
"updated_at": Any<String>,
"value": "test-type",
},
Object {
"created_at": Any<String>,
"id": "test-type-new",
"updated_at": Any<String>,
"value": "test-type-new",
},
]
`;
exports[`/admin/product-types GET /admin/product-types returns a list of product types matching free text search param 1`] = `
Array [
Object {
"created_at": Any<String>,
"id": "test-type-new",
"updated_at": Any<String>,
"value": "test-type-new",
},
]
`;
+794 -61
View File
@@ -1,6 +1,5 @@
const path = require("path")
const {
Region,
DiscountRule,
Discount,
Customer,
@@ -12,7 +11,6 @@ const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const discountSeeder = require("../../helpers/discount-seeder")
const { exportAllDeclaration } = require("@babel/types")
const { simpleProductFactory } = require("../../factories")
const {
simpleDiscountFactory,
@@ -636,12 +634,12 @@ describe("/admin/discounts", () => {
{
rule: {
id: createdRule.id,
type: createdRule.type,
value: createdRule.value,
allocation: createdRule.allocation,
conditions: [
{
id: condsToUpdate.id,
operator: "not_in",
products: [product.id, anotherProduct.id],
},
],
@@ -658,24 +656,26 @@ describe("/admin/discounts", () => {
})
expect(updated.status).toEqual(200)
expect(updated.data.discount.rule.conditions).toEqual([
expect.objectContaining({
type: "products",
operator: "in",
products: expect.arrayContaining([
expect.objectContaining({
id: product.id,
}),
expect.objectContaining({
id: anotherProduct.id,
}),
]),
}),
expect.objectContaining({
type: "product_types",
operator: "not_in",
}),
])
expect(updated.data.discount.rule.conditions).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "products",
operator: "not_in",
products: expect.arrayContaining([
expect.objectContaining({
id: product.id,
}),
expect.objectContaining({
id: anotherProduct.id,
}),
]),
}),
expect.objectContaining({
type: "product_types",
operator: "not_in",
}),
])
)
})
it("fails to add condition on rule with existing comb. of type and operator", async () => {
@@ -729,9 +729,7 @@ describe("/admin/discounts", () => {
{
rule: {
id: createdRule.id,
type: createdRule.type,
value: createdRule.value,
allocation: createdRule.allocation,
conditions: [
{
products: [anotherProduct.id],
@@ -842,7 +840,6 @@ describe("/admin/discounts", () => {
{
rule: {
id: createdRule.id,
type: createdRule.type,
value: createdRule.value,
allocation: createdRule.allocation,
conditions: [
@@ -923,6 +920,121 @@ describe("/admin/discounts", () => {
)
})
it("creates a discount and fails to update it because attempting type update", async () => {
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
rule: {
description: "test",
type: "percentage",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD",
usage_limit: 10,
})
)
await api
.post(
`/admin/discounts/${response.data.discount.id}`,
{
usage_limit: 20,
rule: {
id: response.data.discount.rule.id,
type: "free_shipping",
},
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual(
"property type should not exist"
)
})
})
it("creates a discount and fails to update it because attempting is_dynamic update", async () => {
const api = useApi()
const response = await api
.post(
"/admin/discounts",
{
code: "HELLOWORLD",
is_dynamic: true,
rule: {
description: "test",
type: "percentage",
value: 10,
allocation: "total",
},
usage_limit: 10,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(response.status).toEqual(200)
expect(response.data.discount).toEqual(
expect.objectContaining({
code: "HELLOWORLD",
usage_limit: 10,
is_dynamic: true,
})
)
await api
.post(
`/admin/discounts/${response.data.discount.id}`,
{
usage_limit: 20,
is_dynamic: false,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
expect(err.response.status).toEqual(400)
expect(err.response.data.message).toEqual(
"property is_dynamic should not exist"
)
})
})
it("automatically sets the code to an uppercase string on update", async () => {
const api = useApi()
@@ -1329,7 +1441,7 @@ describe("/admin/discounts", () => {
expect.assertions(2)
const api = useApi()
const response = await api
await api
.post(
"/admin/discounts",
{
@@ -1468,41 +1580,37 @@ describe("/admin/discounts", () => {
describe("POST /admin/discounts/:discount_id/dynamic-codes", () => {
beforeEach(async () => {
const manager = dbConnection.manager
try {
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Dynamic rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "DYNAMIC",
is_dynamic: true,
is_disabled: false,
rule_id: "test-discount-rule",
valid_duration: "P2Y",
})
await manager.insert(DiscountRule, {
id: "test-discount-rule1",
description: "Dynamic rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount1",
code: "DYNAMICCode",
is_dynamic: true,
is_disabled: false,
rule_id: "test-discount-rule1",
})
} catch (err) {
console.log(err)
throw err
}
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule",
description: "Dynamic rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount",
code: "DYNAMIC",
is_dynamic: true,
is_disabled: false,
rule_id: "test-discount-rule",
valid_duration: "P2Y",
})
await manager.insert(DiscountRule, {
id: "test-discount-rule1",
description: "Dynamic rule",
type: "percentage",
value: 10,
allocation: "total",
})
await manager.insert(Discount, {
id: "test-discount1",
code: "DYNAMICCode",
is_dynamic: true,
is_disabled: false,
rule_id: "test-discount-rule1",
})
})
afterEach(async () => {
@@ -1554,7 +1662,7 @@ describe("/admin/discounts", () => {
}
)
.catch((err) => {
// console.log(err)
console.log(err)
})
expect(response.status).toEqual(200)
@@ -1566,4 +1674,629 @@ describe("/admin/discounts", () => {
)
})
})
describe("DELETE /admin/discounts/:id/conditions/:condition_id", () => {
beforeEach(async () => {
const manager = dbConnection.manager
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule-fixed",
description: "Test discount rule",
type: "fixed",
value: 10,
allocation: "total",
})
const prod = await simpleProductFactory(dbConnection, { type: "pants" })
await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
type: "products",
operator: "in",
products: [prod.id],
},
],
},
})
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should delete condition", async () => {
const api = useApi()
const group = await dbConnection.manager.insert(CustomerGroup, {
id: "customer-group-1",
name: "vip-customers",
})
await dbConnection.manager.insert(Customer, {
id: "cus_1234",
email: "oli@email.com",
groups: [group],
})
await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
id: "test-condition",
type: "customer_groups",
operator: "in",
customer_groups: ["customer-group-1"],
},
],
},
})
const response = await api
.delete("/admin/discounts/test-discount/conditions/test-condition", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
const disc = response.data
expect(response.status).toEqual(200)
expect(disc).toEqual(
expect.objectContaining({
id: "test-condition",
deleted: true,
object: "discount-condition",
})
)
})
it("should not fail if condition does not exist", async () => {
const api = useApi()
const response = await api
.delete("/admin/discounts/test-discount/conditions/test-condition", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
const disc = response.data
expect(response.status).toEqual(200)
expect(disc).toEqual(
expect.objectContaining({
id: "test-condition",
deleted: true,
object: "discount-condition",
})
)
})
it("should fail if discount does not exist", async () => {
const api = useApi()
try {
await api.delete(
"/admin/discounts/not-exist/conditions/test-condition",
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"Discount with id not-exist was not found"
)
}
})
})
describe("POST /admin/discounts/:id/conditions", () => {
beforeEach(async () => {
const manager = dbConnection.manager
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule-fixed",
description: "Test discount rule",
type: "fixed",
value: 10,
allocation: "total",
})
await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
},
})
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should create a condition", async () => {
const api = useApi()
const prod = await simpleProductFactory(dbConnection, { type: "pants" })
const response = await api
.post(
"/admin/discounts/test-discount/conditions",
{
operator: "in",
products: [prod.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
const disc = response.data.discount
expect(response.status).toEqual(200)
expect(disc).toMatchSnapshot({
id: "test-discount",
code: "TEST",
created_at: expect.any(String),
updated_at: expect.any(String),
rule_id: expect.any(String),
starts_at: expect.any(String),
rule: {
id: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
conditions: [
{
id: expect.any(String),
discount_rule_id: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
},
})
})
it("fails if more than one condition type is provided", async () => {
const api = useApi()
const prod = await simpleProductFactory(dbConnection, { type: "pants" })
const group = await dbConnection.manager.insert(CustomerGroup, {
id: "customer-group-1",
name: "vip-customers",
})
await dbConnection.manager.insert(Customer, {
id: "cus_1234",
email: "oli@email.com",
groups: [group],
})
try {
await api.post(
"/admin/discounts/test-discount/conditions",
{
operator: "in",
products: [prod.id],
customer_groups: ["customer-group-1"],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"Only one of products, customer_groups is allowed, Only one of customer_groups, products is allowed"
)
}
})
it("throws if discount does not exist", async () => {
expect.assertions(1)
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/does-not-exist/conditions/test-condition",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"Discount with id does-not-exist was not found"
)
}
})
})
describe("POST /admin/discounts/:id/conditions/:condition_id", () => {
beforeEach(async () => {
const manager = dbConnection.manager
await adminSeeder(dbConnection)
await manager.insert(DiscountRule, {
id: "test-discount-rule-fixed",
description: "Test discount rule",
type: "fixed",
value: 10,
allocation: "total",
})
const prod = await simpleProductFactory(dbConnection, { type: "pants" })
await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
id: "test-condition",
type: "products",
operator: "in",
products: [prod.id],
},
],
},
})
await simpleDiscountFactory(dbConnection, {
id: "test-discount-2",
code: "TEST2",
rule: {
type: "percentage",
value: "10",
allocation: "total",
},
})
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should update a condition", async () => {
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, {
id: "test-product",
type: "pants",
})
const discount = await api
.get("/admin/discounts/test-discount", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
const cond = discount.data.discount.rule.conditions[0]
const response = await api
.post(
`/admin/discounts/test-discount/conditions/${cond.id}?expand=rule,rule.conditions,rule.conditions.products`,
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
const disc = response.data.discount
expect(response.status).toEqual(200)
expect(disc).toMatchSnapshot({
id: "test-discount",
code: "TEST",
created_at: expect.any(String),
updated_at: expect.any(String),
rule_id: expect.any(String),
starts_at: expect.any(String),
rule: {
id: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
conditions: [
{
id: expect.any(String),
discount_rule_id: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
products: [
{
created_at: expect.any(String),
updated_at: expect.any(String),
profile_id: expect.any(String),
type_id: expect.any(String),
id: "test-product",
},
],
},
],
},
})
})
it("throws if condition does not exist", async () => {
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/test-discount/conditions/does-not-exist",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"DiscountCondition with id does-not-exist was not found for Discount test-discount"
)
}
})
it("throws if discount does not exist", async () => {
expect.assertions(1)
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/does-not-exist/conditions/test-condition",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"Discount with id does-not-exist was not found"
)
}
})
it("throws if condition does not belong to discount", async () => {
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/test-discount-2/conditions/test-condition",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"DiscountCondition with id test-condition was not found for Discount test-discount-2"
)
}
})
})
describe("GET /admin/discounts/:id/conditions/:condition_id", () => {
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
} catch (err) {
console.log(err)
}
const prod = await simpleProductFactory(dbConnection, {
type: "pants",
id: "test-product",
})
await simpleDiscountFactory(dbConnection, {
id: "test-discount",
code: "TEST",
rule: {
type: "percentage",
value: "10",
allocation: "total",
conditions: [
{
id: "test-condition",
type: "products",
operator: "in",
products: [prod.id],
},
],
},
})
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should get condition", async () => {
const api = useApi()
const discountCondition = await api
.get("/admin/discounts/test-discount/conditions/test-condition", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
const cond = discountCondition.data.discount_condition
expect(discountCondition.status).toEqual(200)
expect(cond).toMatchSnapshot({
id: "test-condition",
type: "products",
operator: "in",
created_at: expect.any(String),
updated_at: expect.any(String),
discount_rule_id: expect.any(String),
discount_rule: {
id: expect.any(String),
updated_at: expect.any(String),
created_at: expect.any(String),
},
})
})
it("should get condition with expand + fields", async () => {
const api = useApi()
const discountCondition = await api
.get(
"/admin/discounts/test-discount/conditions/test-condition?expand=products&fields=id,type",
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
const cond = discountCondition.data.discount_condition
console.log(cond.products)
expect(discountCondition.status).toEqual(200)
expect(cond).toMatchSnapshot({
id: "test-condition",
type: "products",
products: [
{
id: "test-product",
profile_id: expect.any(String),
type_id: expect.any(String),
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
})
})
it("throws if condition does not exist", async () => {
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/test-discount/conditions/does-not-exist",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"DiscountCondition with id test-condition was not found"
)
}
})
it("throws if condition does not belong to discount", async () => {
const api = useApi()
const prod2 = await simpleProductFactory(dbConnection, { type: "pants" })
try {
await api.post(
"/admin/discounts/test-discount-2/conditions/test-condition",
{
products: [prod2.id],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
} catch (error) {
expect(error.message).toMatchSnapshot(
"DiscountCondition with id test-condition was not found for Discount test-discount-2"
)
}
})
})
})
@@ -4,6 +4,7 @@ const {
Order,
LineItem,
CustomShippingOption,
ShippingMethod,
} = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
@@ -914,6 +915,215 @@ describe("/admin/orders", () => {
])
})
it("creates a claim on a claim additional item", async () => {
const api = useApi()
const response = await api
.post(
"/admin/orders/test-order/claims",
{
type: "replace",
shipping_methods: [
{
id: "test-method",
},
],
claim_items: [
{
item_id: "test-item",
quantity: 1,
reason: "production_failure",
tags: ["fluff"],
images: ["https://test.image.com"],
},
],
additional_items: [
{
variant_id: "test-variant",
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
const cid = response.data.order.claims[0].id
const fulRes = await api.post(
`/admin/orders/test-order/claims/${cid}/fulfillments`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
const claimItemIdToClaim =
fulRes.data.order.claims[0].additional_items[0].id
const claimRes = await api
.post(
"/admin/orders/test-order/claims",
{
type: "replace",
shipping_methods: [
{
id: "test-method",
},
],
claim_items: [
{
item_id: claimItemIdToClaim,
quantity: 1,
reason: "production_failure",
tags: ["fluff"],
images: ["https://test.image2.com"],
},
],
additional_items: [
{
variant_id: "test-variant-2",
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(claimRes.status).toEqual(200)
expect(claimRes.data.order.claims.length).toEqual(2)
const newClaim = claimRes.data.order.claims.find(
(c) => c.fulfillment_status === "not_fulfilled"
)
expect(newClaim.claim_items[0].item.id).toEqual(claimItemIdToClaim)
})
it("creates a claim on a swap additional item", async () => {
const api = useApi()
// create a swap
const response = await api
.post(
"/admin/orders/test-order/swaps",
{
custom_shipping_options: [{ option_id: "test-option", price: 0 }],
return_items: [
{
item_id: "test-item",
quantity: 1,
},
],
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
},
{
headers: {
authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
const sid = response.data.order.swaps[0].id
const manager = dbConnection.manager
// add a shipping method so we can fulfill the swap
const sm = await manager.create(ShippingMethod, {
id: "test-method-swap-cart",
swap_id: sid,
shipping_option_id: "test-option",
price: 0,
data: {},
})
await manager.save(sm)
// fulfill the swap
const fulRes = await api
.post(
`/admin/orders/test-order/swaps/${sid}/fulfillments`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
// ship the swap
await api
.post(
`/admin/orders/test-order/swaps/${sid}/shipments`,
{
fulfillment_id: fulRes.data.order.swaps[0].fulfillments[0].id,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
const claimItemIdToClaim =
fulRes.data.order.swaps[0].additional_items[0].id
// create a claim on the exchange
const claimRes = await api
.post(
"/admin/orders/test-order/claims",
{
type: "replace",
claim_items: [
{
item_id: claimItemIdToClaim,
quantity: 1,
reason: "production_failure",
tags: ["fluff"],
images: ["https://test.image2.com"],
},
],
additional_items: [
{
variant_id: "test-variant-2",
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
expect(claimRes.status).toEqual(200)
expect(claimRes.data.order.claims.length).toEqual(1)
const newClaim = claimRes.data.order.claims[0]
expect(newClaim.claim_items[0].item.id).toEqual(claimItemIdToClaim)
})
it("Only allow canceling claim after canceling fulfillments", async () => {
const order_id = "order-with-claim"
@@ -1,3 +1,4 @@
const { PriceList, CustomerGroup } = require("@medusajs/medusa")
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
@@ -8,6 +9,9 @@ const {
simpleProductFactory,
simplePriceListFactory,
} = require("../../factories")
const {
simpleCustomerGroupFactory,
} = require("../../factories/simple-customer-group-factory")
const adminSeeder = require("../../helpers/admin-seeder")
const customerSeeder = require("../../helpers/customer-seeder")
const priceListSeeder = require("../../helpers/price-list-seeder")
@@ -211,6 +215,159 @@ describe("/admin/price-lists", () => {
])
)
})
it("given a search query, returns matching results by name", async () => {
const api = useApi()
const response = await api
.get("/admin/price-lists?q=winter", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "VIP winter sale",
}),
])
)
expect(response.data.count).toEqual(1)
})
it("given a search query, returns matching results by description", async () => {
const api = useApi()
const response = await api
.get("/admin/price-lists?q=25%", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "VIP winter sale",
description:
"Winter sale for VIP customers. 25% off selected items.",
}),
])
)
expect(response.data.count).toEqual(1)
})
it("given a search query, returns empty list when does not exist", async () => {
const api = useApi()
const response = await api
.get("/admin/price-lists?q=blablabla", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists).toEqual([])
expect(response.data.count).toEqual(0)
})
it("given a search query and a status filter not matching any price list, returns an empty set", async () => {
const api = useApi()
const response = await api
.get("/admin/price-lists?q=vip&status[]=draft", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists).toEqual([])
expect(response.data.count).toEqual(0)
})
it("given a search query and a status filter matching a price list, returns a price list", async () => {
const api = useApi()
const response = await api
.get("/admin/price-lists?q=vip&status[]=active", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "VIP winter sale",
status: "active",
}),
])
)
expect(response.data.count).toEqual(1)
})
it("lists only price lists with customer_group", async () => {
await customerSeeder(dbConnection)
await simplePriceListFactory(dbConnection, {
id: "test-list-cgroup-1",
customer_groups: ["customer-group-1"],
})
await simplePriceListFactory(dbConnection, {
id: "test-list-cgroup-2",
customer_groups: ["customer-group-2"],
})
await simplePriceListFactory(dbConnection, {
id: "test-list-cgroup-3",
customer_groups: ["customer-group-3"],
})
await simplePriceListFactory(dbConnection, {
id: "test-list-no-cgroup",
})
const api = useApi()
const response = await api
.get(
`/admin/price-lists?customer_groups[]=customer-group-1,customer-group-2`,
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_lists.length).toEqual(2)
expect(response.data.price_lists).toEqual([
expect.objectContaining({ id: "test-list-cgroup-1" }),
expect.objectContaining({ id: "test-list-cgroup-2" }),
])
})
})
describe("POST /admin/price-lists/:id", () => {
@@ -231,6 +388,41 @@ describe("/admin/price-lists", () => {
await db.teardown()
})
it("removes configuration with update", async () => {
const priceList = await simplePriceListFactory(dbConnection, {
ends_at: new Date(),
starts_at: new Date(),
customer_groups: ["customer-group-1"],
})
const api = useApi()
const getResult = await api.get(`/admin/price-lists/${priceList.id}`, {
headers: {
Authorization: "Bearer test_token",
},
})
expect(getResult.status).toEqual(200)
expect(getResult.data.price_list.starts_at).toBeTruthy()
expect(getResult.data.price_list.ends_at).toBeTruthy()
expect(getResult.data.price_list.customer_groups.length).toEqual(1)
const updateResult = await api.post(
`/admin/price-lists/${priceList.id}`,
{ ends_at: null, starts_at: null, customer_groups: [] },
{
headers: {
Authorization: "Bearer test_token",
},
}
)
expect(updateResult.status).toEqual(200)
expect(updateResult.data.price_list.starts_at).toBeFalsy()
expect(updateResult.data.price_list.ends_at).toBeFalsy()
expect(updateResult.data.price_list.customer_groups.length).toEqual(0)
})
it("updates a price list", async () => {
const api = useApi()
@@ -398,6 +590,68 @@ describe("/admin/price-lists", () => {
updated_at: expect.any(String),
})
})
it("updates price list prices (inser a new MA for a specific region)", async () => {
const api = useApi()
const payload = {
prices: [
// update MA
{
id: "ma_test_4",
amount: 1001,
currency_code: "usd",
variant_id: "test-variant",
},
// create MA
{
amount: 101,
variant_id: "test-variant",
region_id: "region-pl",
},
],
}
const response = await api
.post("/admin/price-lists/pl_with_some_ma", payload, {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_list.prices.length).toEqual(2)
expect(response.data.price_list.prices).toMatchSnapshot([
{
id: expect.any(String),
currency_code: "eur",
amount: 101,
min_quantity: null,
max_quantity: null,
price_list_id: "pl_with_some_ma",
variant_id: "test-variant",
region_id: "region-pl",
created_at: expect.any(String),
updated_at: expect.any(String),
deleted_at: null,
},
{
id: "ma_test_4",
currency_code: "usd",
amount: 1001,
price_list_id: "pl_with_some_ma",
variant_id: "test-variant",
region_id: null,
created_at: expect.any(String),
updated_at: expect.any(String),
deleted_at: null,
},
])
})
})
describe("POST /admin/price-lists/:id/prices/batch", () => {
@@ -462,7 +716,9 @@ describe("/admin/price-lists", () => {
expect(response.status).toEqual(200)
expect(response.data.price_list.prices.length).toEqual(6)
expect(response.data.price_list.prices).toMatchSnapshot([
expect(
response.data.price_list.prices.sort((a, b) => b.amount - a.amount)
).toMatchSnapshot([
{
id: expect.any(String),
price_list_id: "pl_no_customer_groups",
@@ -614,6 +870,78 @@ describe("/admin/price-lists", () => {
},
])
})
it("Adds a batch of new prices where a MA record have a `region_id` instead of `currency_code`", async () => {
const api = useApi()
const payload = {
prices: [
{
amount: 100,
variant_id: "test-variant",
region_id: "region-pl",
},
{
amount: 200,
variant_id: "test-variant",
currency_code: "usd",
},
],
}
const response = await api
.post("/admin/price-lists/pl_with_some_ma/prices/batch", payload, {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.warn(err.response.data)
})
expect(response.status).toEqual(200)
expect(response.data.price_list.prices.length).toEqual(3) // initially this PL has 1 MA record
expect(response.data.price_list.prices).toMatchSnapshot([
{
id: "ma_test_4",
currency_code: "usd",
amount: 70,
price_list_id: "pl_with_some_ma",
variant_id: "test-variant",
region_id: null,
created_at: expect.any(String),
updated_at: expect.any(String),
deleted_at: null,
},
{
id: expect.any(String),
currency_code: "eur",
amount: 100,
min_quantity: null,
max_quantity: null,
price_list_id: "pl_with_some_ma",
variant_id: "test-variant",
region_id: "region-pl",
created_at: expect.any(String),
updated_at: expect.any(String),
deleted_at: null,
},
{
id: expect.any(String),
currency_code: "usd",
amount: 200,
min_quantity: null,
max_quantity: null,
price_list_id: "pl_with_some_ma",
variant_id: "test-variant",
region_id: null,
created_at: expect.any(String),
updated_at: expect.any(String),
deleted_at: null,
},
])
})
})
describe("DELETE /admin/price-lists/:id", () => {
@@ -652,6 +980,19 @@ describe("/admin/price-lists", () => {
object: "price-list",
deleted: true,
})
try {
await api.get("/admin/price-lists/pl_no_customer_groups", {
headers: {
Authorization: "Bearer test_token",
},
})
} catch (error) {
expect(error.response.status).toBe(404)
expect(error.response.data.message).toEqual(
"Price list with id: pl_no_customer_groups was not found"
)
}
})
})
@@ -794,9 +1135,17 @@ describe("/admin/price-lists", () => {
await simplePriceListFactory(dbConnection, {
id: "test-list",
customer_groups: ["test-group"],
prices: [
{ variant_id: "test-variant-1", currency_code: "usd", amount: 100 },
{ variant_id: "test-variant-4", currency_code: "usd", amount: 100 },
{ variant_id: "test-variant-1", currency_code: "usd", amount: 150 },
{ variant_id: "test-variant-4", currency_code: "usd", amount: 150 },
],
})
await simplePriceListFactory(dbConnection, {
id: "test-list-2",
prices: [
{ variant_id: "test-variant-1", currency_code: "usd", amount: 200 },
{ variant_id: "test-variant-4", currency_code: "usd", amount: 200 },
],
})
} catch (err) {
@@ -810,7 +1159,7 @@ describe("/admin/price-lists", () => {
await db.teardown()
})
it("lists only product 1, 2", async () => {
it("lists only product 1, 2 with price list prices", async () => {
const api = useApi()
const response = await api
@@ -826,8 +1175,50 @@ describe("/admin/price-lists", () => {
expect(response.status).toEqual(200)
expect(response.data.count).toEqual(2)
expect(response.data.products).toEqual([
expect.objectContaining({ id: "test-prod-1" }),
expect.objectContaining({ id: "test-prod-2" }),
expect.objectContaining({
id: "test-prod-1",
variants: [
expect.objectContaining({
id: "test-variant-1",
prices: [
expect.objectContaining({ currency_code: "usd", amount: 100 }),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
],
}),
expect.objectContaining({
id: "test-variant-2",
prices: [
expect.objectContaining({ currency_code: "usd", amount: 100 }),
],
}),
],
}),
expect.objectContaining({
id: "test-prod-2",
variants: [
expect.objectContaining({
id: "test-variant-3",
prices: [
expect.objectContaining({ currency_code: "usd", amount: 100 }),
],
}),
expect.objectContaining({
id: "test-variant-4",
prices: [
expect.objectContaining({ currency_code: "usd", amount: 100 }),
expect.objectContaining({
currency_code: "usd",
amount: 150,
price_list_id: "test-list",
}),
],
}),
],
}),
])
})
@@ -851,4 +1242,155 @@ describe("/admin/price-lists", () => {
])
})
})
describe("delete prices from price list related to the specified product or variant", () => {
let product1
let product2
function getCustomPriceIdFromVariant(variantId, index) {
return "ma_" + index + "_" + variantId
}
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
product1 = await simpleProductFactory(
dbConnection,
{
id: "test-prod-1",
title: "some product",
variants: [
{
id: `simple-test-variant-${Math.random() * 1000}`,
title: "Test",
prices: [{ currency: "usd", amount: 100 }],
},
{
id: `simple-test-variant-${Math.random() * 1000}`,
title: "Test 2",
prices: [{ currency: "usd", amount: 200 }],
},
],
},
1
)
product2 = await simpleProductFactory(
dbConnection,
{
id: "test-prod-2",
title: "some product 2",
},
2
)
await simplePriceListFactory(dbConnection, {
id: "test-list",
customer_groups: ["test-group"],
prices: [
...product1.variants.map((variant, i) => ({
id: getCustomPriceIdFromVariant(variant.id, i),
variant_id: variant.id,
currency_code: "usd",
amount: (i + 1) * 150,
})),
...product2.variants.map((variant, i) => ({
id: getCustomPriceIdFromVariant(variant.id, i),
variant_id: variant.id,
currency_code: "usd",
amount: (i + 1) * 150,
})),
],
})
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should delete all the prices that are part of the price list for the specified product", async () => {
const api = useApi()
response = await api.get("/admin/price-lists/test-list", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toBe(200)
expect(response.data.price_list.prices.length).toBe(3)
let response = await api.delete(
`/admin/price-lists/test-list/products/${product1.id}/prices`,
{
headers: {
Authorization: "Bearer test_token",
},
}
)
expect(response.status).toBe(200)
expect(response.data).toEqual({
ids: product1.variants.map((variant, i) => {
return getCustomPriceIdFromVariant(variant.id, i)
}),
object: "money-amount",
deleted: true,
})
response = await api.get("/admin/price-lists/test-list", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toBe(200)
expect(response.data.price_list.prices.length).toBe(1)
})
it("should delete all the prices that are part of the price list for the specified variant", async () => {
const api = useApi()
response = await api.get("/admin/price-lists/test-list", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toBe(200)
expect(response.data.price_list.prices.length).toBe(3)
const variant = product2.variants[0]
let response = await api.delete(
`/admin/price-lists/test-list/variants/${variant.id}/prices`,
{
headers: {
Authorization: "Bearer test_token",
},
}
)
expect(response.status).toBe(200)
expect(response.data).toEqual({
ids: [getCustomPriceIdFromVariant(variant.id, 0)],
object: "money-amount",
deleted: true,
})
response = await api.get("/admin/price-lists/test-list", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toBe(200)
expect(response.data.price_list.prices.length).toBe(2)
})
})
})
@@ -68,5 +68,38 @@ describe("/admin/product-tags", () => {
tagMatch,
])
})
it("returns a list of product tags matching free text search param", async () => {
const api = useApi()
const res = await api
.get("/admin/product-tags?q=123", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(res.status).toEqual(200)
const tagMatch = {
created_at: expect.any(String),
updated_at: expect.any(String),
}
expect(res.data.product_tags.map((pt) => pt.value)).toEqual([
"123",
"123",
"123",
])
expect(res.data.product_tags).toMatchSnapshot([
tagMatch,
tagMatch,
tagMatch,
])
})
})
})
@@ -0,0 +1,102 @@
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const productSeeder = require("../../helpers/product-seeder")
jest.setTimeout(50000)
describe("/admin/product-types", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("GET /admin/product-types", () => {
beforeEach(async () => {
try {
await productSeeder(dbConnection)
await adminSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("returns a list of product types", async () => {
const api = useApi()
const res = await api
.get("/admin/product-types", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(res.status).toEqual(200)
const typeMatch = {
created_at: expect.any(String),
updated_at: expect.any(String),
}
expect(res.data.product_types).toMatchSnapshot([
typeMatch,
typeMatch,
])
})
it("returns a list of product types matching free text search param", async () => {
const api = useApi()
const res = await api
.get("/admin/product-types?q=test-type-new", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(res.status).toEqual(200)
const typeMatch = {
created_at: expect.any(String),
updated_at: expect.any(String),
}
// The value of the type should match the search param
expect(res.data.product_types.map((pt) => pt.value)).toEqual([
"test-type-new"
])
// Should only return one type as there is only one match to the search param
expect(res.data.product_types).toMatchSnapshot([
typeMatch
])
})
})
})
@@ -6,7 +6,7 @@ const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const productSeeder = require("../../helpers/product-seeder")
const { ProductVariant } = require("@medusajs/medusa")
const { ProductVariant, ProductOptionValue, MoneyAmount } = require("@medusajs/medusa")
const priceListSeeder = require("../../helpers/price-list-seeder")
jest.setTimeout(50000)
@@ -1387,6 +1387,48 @@ describe("/admin/products", () => {
})
})
describe("GET /admin/products/:id/variants", () => {
beforeEach(async() => {
try {
await productSeeder(dbConnection)
await adminSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async() => {
const db = useDb()
await db.teardown()
})
it('should return the variants related to the requested product', async () => {
const api = useApi()
const res = await api
.get("/admin/products/test-product/variants", {
headers: {
Authorization: "Bearer test_token",
},
})
.catch((err) => {
console.log(err)
})
expect(res.status).toEqual(200)
expect(res.data.variants.length).toBe(4)
expect(res.data.variants).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "test-variant", product_id: "test-product" }),
expect.objectContaining({ id: "test-variant_1", product_id: "test-product" }),
expect.objectContaining({ id: "test-variant_2", product_id: "test-product" }),
expect.objectContaining({ id: "test-variant-sale", product_id: "test-product" }),
])
)
})
})
describe("updates a variant's default prices (ignores prices associated with a Price List)", () => {
beforeEach(async () => {
try {
@@ -1737,6 +1779,177 @@ describe("/admin/products", () => {
expect(variant).toEqual(undefined)
})
it("successfully deletes a product variant and its associated option values", async () => {
const api = useApi()
// Validate that the option value exists
const optValPre = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
})
expect(optValPre).not.toEqual(undefined)
// Soft delete the variant
const response = await api.delete(
"/admin/products/test-product/variants/test-variant_2",
{
headers: {
Authorization: "Bearer test_token",
},
}
)
expect(response.status).toEqual(200)
// Validate that the option value was deleted
const optValPost = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
}
)
expect(optValPost).toEqual(undefined)
// Validate that the option still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
}, {
withDeleted: true,
})
expect(optValDeleted).toEqual(expect.objectContaining({
deleted_at: expect.any(Date),
variant_id: "test-variant_2",
}))
})
it("successfully deletes a product and any option value associated with one of its variants", async () => {
const api = useApi()
// Validate that the option value exists
const optValPre = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
})
expect(optValPre).not.toEqual(undefined)
// Soft delete the product
const response = await api.delete("/admin/products/test-product", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toEqual(200)
// Validate that the option value has been deleted
const optValPost = await dbConnection.manager.findOne(
ProductOptionValue,
{
variant_id: "test-variant_2",
}
)
expect(optValPost).toEqual(undefined)
// Validate that the option still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(ProductOptionValue, {
variant_id: "test-variant_2",
}, {
withDeleted: true,
})
expect(optValDeleted).toEqual(expect.objectContaining({
deleted_at: expect.any(Date),
variant_id: "test-variant_2",
}))
})
it("successfully deletes a product variant and its associated prices", async () => {
const api = useApi()
// Validate that the price exists
const pricePre = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
})
expect(pricePre).not.toEqual(undefined)
// Soft delete the variant
const response = await api.delete(
"/admin/products/test-product/variants/test-variant",
{
headers: {
Authorization: "Bearer test_token",
},
}
)
expect(response.status).toEqual(200)
// Validate that the price was deleted
const pricePost = await dbConnection.manager.findOne(
MoneyAmount,
{
id: "test-price",
}
)
expect(pricePost).toEqual(undefined)
// Validate that the price still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
}, {
withDeleted: true,
})
expect(optValDeleted).toEqual(expect.objectContaining({
deleted_at: expect.any(Date),
id: "test-price",
}))
})
it("successfully deletes a product and any prices associated with one of its variants", async () => {
const api = useApi()
// Validate that the price exists
const pricePre = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
})
expect(pricePre).not.toEqual(undefined)
// Soft delete the product
const response = await api.delete("/admin/products/test-product", {
headers: {
Authorization: "Bearer test_token",
},
})
expect(response.status).toEqual(200)
// Validate that the price has been deleted
const pricePost = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
})
expect(pricePost).toEqual(undefined)
// Validate that the price still exists in the DB with deleted_at
const optValDeleted = await dbConnection.manager.findOne(MoneyAmount, {
id: "test-price",
}, {
withDeleted: true,
})
expect(optValDeleted).toEqual(expect.objectContaining({
deleted_at: expect.any(Date),
id: "test-price",
}))
})
it("successfully creates product with soft-deleted product handle and deletes it again", async () => {
const api = useApi()
@@ -0,0 +1,270 @@
const path = require("path")
import { ReturnReason, ShippingMethod } from "@medusajs/medusa"
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const orderSeeder = require("../../helpers/order-seeder")
const adminSeeder = require("../../helpers/admin-seeder")
jest.setTimeout(30000)
describe("/admin/returns", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("POST /admin/returns/:id", () => {
let rrId
beforeEach(async () => {
try {
await adminSeeder(dbConnection)
await orderSeeder(dbConnection)
const created = dbConnection.manager.create(ReturnReason, {
value: "too_big",
label: "Too Big",
})
const resultRR = await dbConnection.manager.save(created)
rrId = resultRR.id
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("should receive a return on an item added through swap additional items", async () => {
const api = useApi()
// create a swap
const response = await api
.post(
"/admin/orders/test-order/swaps",
{
custom_shipping_options: [{ option_id: "test-option", price: 0 }],
return_items: [
{
item_id: "test-item",
quantity: 1,
},
],
additional_items: [{ variant_id: "test-variant-2", quantity: 1 }],
},
{
headers: {
authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
const sid = response.data.order.swaps[0].id
const manager = dbConnection.manager
// add a shipping method so we can fulfill the swap
const sm = await manager.create(ShippingMethod, {
id: "test-method-swap-cart",
swap_id: sid,
shipping_option_id: "test-option",
price: 0,
data: {},
})
await manager.save(sm)
// fulfill the swap
const fulRes = await api
.post(
`/admin/orders/test-order/swaps/${sid}/fulfillments`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
// ship the swap
await api
.post(
`/admin/orders/test-order/swaps/${sid}/shipments`,
{
fulfillment_id: fulRes.data.order.swaps[0].fulfillments[0].id,
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e))
const swapItemId = fulRes.data.order.swaps[0].additional_items[0].id
// request a return
const returnRes = await api
.post(
`/admin/orders/test-order/return`,
{
items: [
{
item_id: swapItemId,
quantity: 1,
reason_id: rrId,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e.response))
const returnId = returnRes.data.order.returns[0].id
const receiveRes = await api
.post(
`/admin/returns/${returnId}/receive`,
{
items: [
{
item_id: swapItemId,
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e.response))
expect(receiveRes.status).toEqual(200)
})
it("should receive a return on an item added through claim additional items", async () => {
const api = useApi()
const response = await api
.post(
"/admin/orders/test-order/claims",
{
type: "replace",
shipping_methods: [
{
id: "test-method",
},
],
claim_items: [
{
item_id: "test-item",
quantity: 1,
reason: "production_failure",
tags: ["fluff"],
images: ["https://test.image.com"],
},
],
additional_items: [
{
variant_id: "test-variant",
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((err) => {
console.log(err)
})
const cid = response.data.order.claims[0].id
const fulRes = await api.post(
`/admin/orders/test-order/claims/${cid}/fulfillments`,
{},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
const claimItemId = fulRes.data.order.claims[0].additional_items[0].id
// request a return
const returnRes = await api
.post(
`/admin/orders/test-order/return`,
{
items: [
{
item_id: claimItemId,
quantity: 1,
reason_id: rrId,
},
],
return_shipping: {
option_id: "test-option",
price: 0,
}
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e.response))
const returnId = returnRes.data.order.returns[0].id
const receiveRes = await api
.post(
`/admin/returns/${returnId}/receive`,
{
items: [
{
item_id: claimItemId,
quantity: 1,
},
],
},
{
headers: {
Authorization: "Bearer test_token",
},
}
)
.catch((e) => console.log(e.response))
expect(receiveRes.status).toEqual(200)
})
})
})
@@ -0,0 +1,44 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`/admin/batch GET /admin/batch lists batch jobs created by the user 1`] = `
Object {
"batch_jobs": Array [
Object {
"context": Object {},
"created_at": Any<String>,
"created_by": "admin_user",
"deleted_at": null,
"id": "job_3",
"result": null,
"status": "created",
"type": "batch_2",
"updated_at": Any<String>,
},
Object {
"context": Object {},
"created_at": Any<String>,
"created_by": "admin_user",
"deleted_at": null,
"id": "job_2",
"result": null,
"status": "created",
"type": "batch_2",
"updated_at": Any<String>,
},
Object {
"context": Object {},
"created_at": Any<String>,
"created_by": "admin_user",
"deleted_at": null,
"id": "job_1",
"result": null,
"status": "created",
"type": "batch_1",
"updated_at": Any<String>,
},
],
"count": 3,
"limit": 10,
"offset": 0,
}
`;
@@ -0,0 +1,94 @@
const path = require("path")
const setupServer = require("../../../helpers/setup-server")
const { useApi } = require("../../../helpers/use-api")
const { initDb, useDb } = require("../../../helpers/use-db")
const adminSeeder = require("../../helpers/admin-seeder")
const { simpleBatchJobFactory } = require("../../factories")
jest.setTimeout(50000)
const adminReqConfig = {
headers: {
Authorization: "Bearer test_token",
},
}
describe("/admin/batch", () => {
let medusaProcess
let dbConnection
beforeAll(async () => {
const cwd = path.resolve(path.join(__dirname, "..", ".."))
dbConnection = await initDb({ cwd })
medusaProcess = await setupServer({ cwd, verbose: false })
})
afterAll(async () => {
const db = useDb()
await db.shutdown()
medusaProcess.kill()
})
describe("GET /admin/batch", () => {
beforeEach(async () => {
try {
await simpleBatchJobFactory(dbConnection, {
id: "job_1",
type: "batch_1",
created_by: "admin_user",
})
await simpleBatchJobFactory(dbConnection, {
id: "job_2",
type: "batch_2",
created_by: "admin_user",
})
await simpleBatchJobFactory(dbConnection, {
id: "job_3",
type: "batch_2",
created_by: "admin_user",
})
await simpleBatchJobFactory(dbConnection, {
id: "job_4",
type: "batch_1",
created_by: "not_this_user",
})
await adminSeeder(dbConnection)
} catch (err) {
console.log(err)
throw err
}
})
afterEach(async () => {
const db = useDb()
await db.teardown()
})
it("lists batch jobs created by the user", async () => {
const api = useApi()
const response = await api.get("/admin/batch", adminReqConfig)
expect(response.status).toEqual(200)
expect(response.data.batch_jobs.length).toEqual(3)
expect(response.data).toMatchSnapshot({
batch_jobs: [
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
{
created_at: expect.any(String),
updated_at: expect.any(String),
},
],
})
})
})
})
@@ -222,6 +222,92 @@ describe("/admin/orders", () => {
}),
])
})
test("receives a return with a claimed line item", async () => {
await adminSeeder(dbConnection)
const order = await createReturnableOrder(dbConnection, { shipped: true })
const option = await simpleShippingOptionFactory(dbConnection, {
region_id: "test-region",
})
const api = useApi()
const createRes = await api.post(
`/admin/orders/${order.id}/claims`,
{
type: "replace",
shipping_methods: [
{
option_id: option.id,
price: 0,
},
],
additional_items: [{ variant_id: "test-variant", quantity: 1 }],
claim_items: [
{
item_id: "test-item",
reason: "missing_item",
quantity: 1,
},
],
},
{ headers: { authorization: "Bearer test_token" } }
)
const claimId = createRes.data.order.claims[0].id
const claimLineItem = createRes.data.order.claims[0].additional_items[0]
const claimFulfillmentCreatedResponse = await api.post(
`/admin/orders/${order.id}/claims/${claimId}/fulfillments`,
{},
{ headers: { authorization: "Bearer test_token" } }
)
const fulfillmentId =
claimFulfillmentCreatedResponse.data.order.claims[0].fulfillments[0].id
await api.post(
`/admin/orders/${order.id}/claims/${claimId}/shipments`,
{ fulfillment_id: fulfillmentId },
{ headers: { authorization: "Bearer test_token" } }
)
const returnCreatedResponse = await api.post(
`/admin/orders/${order.id}/return`,
{
items: [
{
item_id: claimLineItem.id,
quantity: 1,
note: "TOO SMALL",
},
],
},
{
headers: {
authorization: "Bearer test_token",
},
}
)
const returnOrder = returnCreatedResponse.data.order.returns[0]
const returnId = returnOrder.id
const returnReceivedResponse = await api.post(
`/admin/returns/${returnId}/receive`,
{
items: returnOrder.items.map((i) => ({
item_id: i.item_id,
quantity: i.quantity,
})),
},
{
headers: {
authorization: "Bearer test_token",
},
}
)
expect(returnReceivedResponse.status).toEqual(200)
})
})
const createReturnableOrder = async (dbConnection, options) => {
@@ -258,6 +344,8 @@ const createReturnableOrder = async (dbConnection, options) => {
id: "test-item",
variant_id: "test-variant",
quantity: 2,
fulfilled_quantity: options.shipped ? 2 : undefined,
shipped_quantity: options.shipped ? 2 : undefined,
unit_price: 1000,
adjustments: [
{
@@ -98,7 +98,7 @@ Object {
"payment_authorized_at": null,
"payment_id": null,
"region_id": "test-region",
"shipping_address_id": StringMatching /\\^addr_\\*/,
"shipping_address_id": "test-shipping-address",
"type": "swap",
"updated_at": Any<String>,
},
@@ -274,7 +274,7 @@ Object {
"payment_authorized_at": null,
"payment_id": null,
"region_id": "test-region",
"shipping_address_id": StringMatching /\\^addr_\\*/,
"shipping_address_id": "test-shipping-address",
"type": "swap",
"updated_at": Any<String>,
},
+2 -13
View File
@@ -1,18 +1,7 @@
const path = require("path")
const {
Region,
Order,
Customer,
ShippingProfile,
Product,
ProductVariant,
MoneyAmount,
LineItem,
Payment,
Cart,
ShippingMethod,
ShippingOption,
Swap,
} = require("@medusajs/medusa")
const setupServer = require("../../../helpers/setup-server")
@@ -137,7 +126,7 @@ describe("/store/carts", () => {
type: "swap",
created_at: expect.any(String),
updated_at: expect.any(String),
shipping_address_id: expect.stringMatching(/^addr_*/),
shipping_address_id: "test-shipping-address",
metadata: {
swap_id: expect.stringMatching(/^swap_*/),
},
@@ -221,7 +210,7 @@ describe("/store/carts", () => {
cart: {
id: expect.stringMatching(/^cart_*/),
billing_address_id: "test-billing-address",
shipping_address_id: expect.stringMatching(/^addr_*/),
shipping_address_id: "test-shipping-address",
type: "swap",
created_at: expect.any(String),
updated_at: expect.any(String),
+1
View File
@@ -1,4 +1,5 @@
export * from "./simple-payment-factory"
export * from "./simple-batch-job-factory"
export * from "./simple-order-factory"
export * from "./simple-cart-factory"
export * from "./simple-region-factory"
@@ -0,0 +1,27 @@
import { Connection } from "typeorm"
import { BatchJob, BatchJobStatus } from "@medusajs/medusa"
export type BatchJobFactoryData = {
id?: string
type?: string
status?: BatchJobStatus
created_by?: string
context?: Record<string, unknown>
}
export const simpleBatchJobFactory = async (
connection: Connection,
data: BatchJobFactoryData = {}
): Promise<BatchJob> => {
const manager = connection.manager
const job = manager.create(BatchJob, {
id: data.id,
status: data.status ?? BatchJobStatus.CREATED,
type: data.type ?? "test-job",
created_by: data.created_by ?? null,
context: data.context ?? {},
})
return await manager.save(job)
}
@@ -22,7 +22,7 @@ export const simpleCustomerGroupFactory = async (
data.id || `simple-customer-group-${Math.random() * 1000}`
const c = manager.create(CustomerGroup, {
id: customerGroupId,
name: data.name,
name: data.name || faker.company.companyName(),
})
const group = await manager.save(c)
@@ -13,6 +13,7 @@ import faker from "faker"
import { Connection } from "typeorm"
export type DiscuntConditionFactoryData = {
id?: string
rule_id: string
type: DiscountConditionType
operator: DiscountConditionOperator
@@ -93,11 +94,17 @@ export const simpleDiscountConditionFactory = async (
resources = data.customer_groups
}
const condToSave = manager.create(DiscountCondition, {
const toCreate = {
type: data.type,
operator: data.operator,
discount_rule_id: data.rule_id,
})
}
if (data.id) {
toCreate["id"] = data.id
}
const condToSave = manager.create(DiscountCondition, toCreate)
const { conditionTable, resourceKey } = getJoinTableResourceIdentifiers(
data.type
@@ -3,9 +3,11 @@ import {
MoneyAmount,
PriceListType,
PriceListStatus,
CustomerGroup,
} from "@medusajs/medusa"
import faker from "faker"
import { Connection } from "typeorm"
import { simpleCustomerGroupFactory } from "./simple-customer-group-factory"
type ProductListPrice = {
variant_id: string
@@ -38,6 +40,16 @@ export const simplePriceListFactory = async (
const manager = connection.manager
const listId = data.id || `simple-price-list-${Math.random() * 1000}`
let customerGroups = []
if (typeof data.customer_groups !== "undefined") {
customerGroups = await Promise.all(
data.customer_groups.map((group) =>
simpleCustomerGroupFactory(connection, { id: group })
)
)
}
const toCreate = {
id: listId,
name: data.name || faker.commerce.productName(),
@@ -46,6 +58,7 @@ export const simplePriceListFactory = async (
type: data.type || PriceListType.OVERRIDE,
starts_at: data.starts_at || null,
ends_at: data.ends_at || null,
customer_groups: customerGroups,
}
const toSave = manager.create(PriceList, toCreate)
@@ -112,5 +112,5 @@ export const simpleProductFactory = async (
await simpleProductVariantFactory(connection, factoryData)
}
return manager.findOne(Product, { id: prodId }, { relations: ["tags"] })
return manager.findOne(Product, { id: prodId }, { relations: ["tags", "variants", "variants.prices"] })
}
@@ -153,6 +153,7 @@ module.exports = async (connection, data = {}) => {
currency_code: "usd",
amount_refunded: 0,
provider_id: "test-pay",
captured_at: new Date(),
data: {},
},
],
@@ -1,4 +1,4 @@
const { PriceList, MoneyAmount } = require("@medusajs/medusa")
const { Region, PriceList, MoneyAmount } = require("@medusajs/medusa")
module.exports = async (connection, data = {}) => {
const manager = connection.manager
@@ -15,6 +15,13 @@ module.exports = async (connection, data = {}) => {
await manager.save(priceListNoCustomerGroups)
await manager.insert(Region, {
id: "region-pl",
name: "Test Region",
currency_code: "eur",
tax_rate: 0,
})
const moneyAmount1 = await manager.create(MoneyAmount, {
id: "ma_test_1",
amount: 100,
@@ -50,4 +57,27 @@ module.exports = async (connection, data = {}) => {
})
await manager.save(moneyAmount3)
const moneyAmount4 = await manager.create(MoneyAmount, {
id: "ma_test_4",
amount: 70,
currency_code: "usd",
variant_id: "test-variant",
})
await manager.save(moneyAmount4)
const priceListWithMA = await manager.create(PriceList, {
id: "pl_with_some_ma",
name: "Weeken sale",
description: "Desc. of the list",
type: "sale",
status: "active",
starts_at: "2022-07-01T00:00:00.000Z",
ends_at: "2022-07-31T00:00:00.000Z",
})
priceListWithMA.prices = [moneyAmount4]
await manager.save(priceListWithMA)
}
@@ -69,6 +69,13 @@ module.exports = async (connection, data = {}) => {
await manager.save(type)
const type2 = await manager.create(ProductType, {
id: "test-type-new",
value: "test-type-new",
})
await manager.save(type2)
const image = manager.create(Image, {
id: "test-image",
url: "test-image.png",
+1
View File
@@ -5,6 +5,7 @@ module.exports = {
name: "api",
testEnvironment: `node`,
rootDir: "./",
testTimeout: 10000,
testPathIgnorePatterns: [
`/examples/`,
`/www/`,
+3 -3
View File
@@ -8,16 +8,16 @@
"build": "babel src -d dist --extensions \".ts,.js\""
},
"dependencies": {
"@medusajs/medusa": "1.2.1-dev-1649181615374",
"@medusajs/medusa": "1.3.0-dev-1652704115624",
"faker": "^5.5.3",
"medusa-interfaces": "1.2.1-dev-1649181615374",
"medusa-interfaces": "1.3.0-dev-1652704115624",
"typeorm": "^0.2.31"
},
"devDependencies": {
"@babel/cli": "^7.12.10",
"@babel/core": "^7.12.10",
"@babel/node": "^7.12.10",
"babel-preset-medusa-package": "1.1.19-dev-1649181615374",
"babel-preset-medusa-package": "1.1.19-dev-1652704115624",
"jest": "^26.6.3"
}
}
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more