feat(medusa): Stock location module (#2907)

* feat: stock location module
This commit is contained in:
Carlos R. L. Rodrigues
2023-01-04 13:11:59 -03:00
committed by GitHub
parent cc10c20f35
commit c07ffb6165
50 changed files with 2040 additions and 198 deletions
+1
View File
@@ -0,0 +1 @@
export const CONNECTION_NAME = "stock_location_connection"
+7
View File
@@ -0,0 +1,7 @@
import ConnectionLoader from "./loaders/connection"
import StockLocationService from "./services/stock-location"
import * as SchemaMigration from "./migrations/schema-migrations/1665749860179-setup"
export const service = StockLocationService
export const migrations = [SchemaMigration]
export const loaders = [ConnectionLoader]
@@ -0,0 +1,22 @@
import { ConfigModule } from "@medusajs/medusa"
import { ConnectionOptions, createConnection } from "typeorm"
import { CONNECTION_NAME } from "../config"
import { StockLocation, StockLocationAddress } from "../models"
export default async ({
configModule,
}: {
configModule: ConfigModule
}): Promise<void> => {
await createConnection({
name: CONNECTION_NAME,
type: configModule.projectConfig.database_type,
url: configModule.projectConfig.database_url,
database: configModule.projectConfig.database_database,
schema: configModule.projectConfig.database_schema,
extra: configModule.projectConfig.database_extra || {},
entities: [StockLocation, StockLocationAddress],
logging: configModule.projectConfig.database_logging || false,
} as ConnectionOptions)
}
@@ -0,0 +1,94 @@
import { ConfigModule } from "@medusajs/medusa"
import {
createConnection,
ConnectionOptions,
MigrationInterface,
QueryRunner,
} from "typeorm"
import { CONNECTION_NAME } from "../../config"
export const up = async ({ configModule }: { configModule: ConfigModule }) => {
const connection = await createConnection({
name: CONNECTION_NAME,
type: configModule.projectConfig.database_type,
url: configModule.projectConfig.database_url,
database: configModule.projectConfig.database_database,
schema: configModule.projectConfig.database_schema,
extra: configModule.projectConfig.database_extra || {},
migrations: [setup1665749860179],
logging: true,
} as ConnectionOptions)
await connection.runMigrations()
}
export const down = async ({
configModule,
}: {
configModule: ConfigModule
}) => {
const connection = await createConnection({
name: CONNECTION_NAME,
type: configModule.projectConfig.database_type,
url: configModule.projectConfig.database_url,
database: configModule.projectConfig.database_database,
schema: configModule.projectConfig.database_schema,
extra: configModule.projectConfig.database_extra || {},
migrations: [setup1665749860179],
logging: true,
} as ConnectionOptions)
await connection.undoLastMigration({ transaction: "all" })
}
export class setup1665749860179 implements MigrationInterface {
name = "setup1665749860179"
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "stock_location_address"
(
"id" CHARACTER VARYING NOT NULL,
"created_at" TIMESTAMP WITH TIME zone NOT NULL DEFAULT Now(),
"updated_at" TIMESTAMP WITH TIME zone NOT NULL DEFAULT Now(),
"deleted_at" TIMESTAMP WITH TIME zone,
"address_1" TEXT NOT NULL,
"address_2" TEXT,
"city" TEXT,
"country_code" TEXT NOT NULL,
"phone" TEXT,
"province" TEXT,
"postal_code" TEXT,
"metadata" JSONB,
CONSTRAINT "PK_b79bc27285bede680501b7b81a5" PRIMARY KEY ("id")
);
CREATE INDEX "IDX_stock_location_address_country_code" ON "stock_location_address" ("country_code");
CREATE TABLE "stock_location"
(
"id" CHARACTER VARYING NOT NULL,
"created_at" TIMESTAMP WITH time zone NOT NULL DEFAULT Now(),
"updated_at" TIMESTAMP WITH time zone NOT NULL DEFAULT Now(),
"deleted_at" TIMESTAMP WITH time zone,
"name" TEXT NOT NULL,
"address_id" TEXT NOT NULL,
"metadata" JSONB,
CONSTRAINT "PK_adf770067d0df1421f525fa25cc" PRIMARY KEY ("id")
);
CREATE INDEX "IDX_stock_location_address_id" ON "stock_location" ("address_id");
`)
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
DROP INDEX "IDX_stock_location_address_id";
DROP TABLE "stock_location";
DROP INDEX "IDX_stock_location_address_country_code";
DROP TABLE "stock_location_address";
`)
}
}
@@ -0,0 +1,2 @@
export * from "./stock-location"
export * from "./stock-location-address"
@@ -0,0 +1,35 @@
import { BeforeInsert, Column, Entity, Index } from "typeorm"
import { SoftDeletableEntity, generateEntityId } from "@medusajs/medusa"
@Entity()
export class StockLocationAddress extends SoftDeletableEntity {
@Column({ type: "text" })
address_1: string
@Column({ type: "text", nullable: true })
address_2: string | null
@Column({ type: "text", nullable: true })
city: string | null
@Index()
@Column({ type: "text" })
country_code: string
@Column({ type: "text", nullable: true })
phone: string | null
@Column({ type: "text", nullable: true })
province: string | null
@Column({ type: "text", nullable: true })
postal_code: string | null
@Column({ type: "jsonb", nullable: true })
metadata: Record<string, unknown> | null
@BeforeInsert()
private beforeInsert(): void {
this.id = generateEntityId(this.id, "laddr")
}
}
@@ -0,0 +1,33 @@
import {
BeforeInsert,
Column,
Entity,
Index,
JoinColumn,
ManyToOne,
} from "typeorm"
import { SoftDeletableEntity, generateEntityId } from "@medusajs/medusa"
import { StockLocationAddress } from "."
@Entity()
export class StockLocation extends SoftDeletableEntity {
@Column({ type: "text" })
name: string
@Index()
@Column({ type: "text" })
address_id: string
@ManyToOne(() => StockLocationAddress)
@JoinColumn({ name: "address_id" })
address: StockLocationAddress | null
@Column({ type: "jsonb", nullable: true })
metadata: Record<string, unknown> | null
@BeforeInsert()
private beforeInsert(): void {
this.id = generateEntityId(this.id, "sloc")
}
}
@@ -0,0 +1 @@
export { default as StockLocationService } from "./stock-location"
@@ -0,0 +1,253 @@
import { getConnection, EntityManager } from "typeorm"
import { isDefined, MedusaError } from "medusa-core-utils"
import {
FindConfig,
buildQuery,
FilterableStockLocationProps,
CreateStockLocationInput,
UpdateStockLocationInput,
StockLocationAddressInput,
IEventBusService,
setMetadata,
} from "@medusajs/medusa"
import { StockLocation, StockLocationAddress } from "../models"
import { CONNECTION_NAME } from "../config"
type InjectedDependencies = {
eventBusService: IEventBusService
}
/**
* Service for managing stock locations.
*/
export default class StockLocationService {
static Events = {
CREATED: "stock-location.created",
UPDATED: "stock-location.updated",
DELETED: "stock-location.deleted",
}
protected readonly manager_: EntityManager
protected readonly eventBusService_: IEventBusService
constructor({ eventBusService }: InjectedDependencies) {
this.eventBusService_ = eventBusService
}
private getManager(): EntityManager {
const connection = getConnection(CONNECTION_NAME)
return connection.manager
}
/**
* Lists all stock locations that match the given selector.
* @param {FilterableStockLocationProps} [selector={}] - Properties to filter by.
* @param {FindConfig} [config={ relations: [], skip: 0, take: 10 }] - Additional configuration for the query.
* @return {Promise<StockLocation[]>} A list of stock locations.
*/
async list(
selector: FilterableStockLocationProps = {},
config: FindConfig<StockLocation> = { relations: [], skip: 0, take: 10 }
): Promise<StockLocation[]> {
const manager = this.getManager()
const locationRepo = manager.getRepository(StockLocation)
const query = buildQuery(selector, config)
return await locationRepo.find(query)
}
/**
* Lists all stock locations that match the given selector and returns the count of matching stock locations.
* @param {FilterableStockLocationProps} [selector={}] - Properties to filter by.
* @param {FindConfig} [config={ relations: [], skip: 0, take: 10 }] - Additional configuration for the query.
* @return {Promise<[StockLocation[], number]>} A list of stock locations and the count of matching stock locations.
*/
async listAndCount(
selector: FilterableStockLocationProps = {},
config: FindConfig<StockLocation> = { relations: [], skip: 0, take: 10 }
): Promise<[StockLocation[], number]> {
const manager = this.getManager()
const locationRepo = manager.getRepository(StockLocation)
const query = buildQuery(selector, config)
return await locationRepo.findAndCount(query)
}
/**
* Retrieves a stock location by its ID.
* @param {string} stockLocationId - The ID of the stock location.
* @param {FindConfig} [config={}] - Additional configuration for the query.
* @return {Promise<StockLocation>} The stock location.
* @throws {MedusaError} If the stock location ID is not defined.
* @throws {MedusaError} If the stock location with the given ID was not found.
*/
async retrieve(
stockLocationId: string,
config: FindConfig<StockLocation> = {}
): Promise<StockLocation> {
if (!isDefined(stockLocationId)) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`"stockLocationId" must be defined`
)
}
const manager = this.getManager()
const locationRepo = manager.getRepository(StockLocation)
const query = buildQuery({ id: stockLocationId }, config)
const loc = await locationRepo.findOne(query)
if (!loc) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`StockLocation with id ${stockLocationId} was not found`
)
}
return loc
}
/**
* Creates a new stock location.
* @param {CreateStockLocationInput} data - The input data for creating a stock location.
* @returns {Promise<StockLocation>} - The created stock location.
*/
async create(data: CreateStockLocationInput): Promise<StockLocation> {
const defaultManager = this.getManager()
return await defaultManager.transaction(async (manager) => {
const locationRepo = manager.getRepository(StockLocation)
const loc = locationRepo.create({
name: data.name,
})
if (isDefined(data.address) || isDefined(data.address_id)) {
if (typeof data.address === "string" || data.address_id) {
const addrId = (data.address ?? data.address_id) as string
const address = await this.retrieve(addrId, {
select: ["id"],
})
loc.address_id = address.id
} else {
const locAddressRepo = manager.getRepository(StockLocationAddress)
const locAddress = locAddressRepo.create(data.address!)
const addressResult = await locAddressRepo.save(locAddress)
loc.address_id = addressResult.id
}
}
const { metadata } = data
if (metadata) {
loc.metadata = setMetadata(loc, metadata)
}
const result = await locationRepo.save(loc)
await this.eventBusService_.emit(StockLocationService.Events.CREATED, {
id: result.id,
})
return result
})
}
/**
* Updates an existing stock location.
* @param {string} stockLocationId - The ID of the stock location to update.
* @param {UpdateStockLocationInput} updateData - The update data for the stock location.
* @returns {Promise<StockLocation>} - The updated stock location.
*/
async update(
stockLocationId: string,
updateData: UpdateStockLocationInput
): Promise<StockLocation> {
const defaultManager = this.getManager()
return await defaultManager.transaction(async (manager) => {
const locationRepo = manager.getRepository(StockLocation)
const item = await this.retrieve(stockLocationId)
const { address, metadata, ...data } = updateData
if (address) {
if (item.address_id) {
await this.updateAddress(item.address_id, address, { manager })
} else {
const locAddressRepo = manager.getRepository(StockLocationAddress)
const locAddress = locAddressRepo.create(address)
const addressResult = await locAddressRepo.save(locAddress)
data.address_id = addressResult.id
}
}
if (metadata) {
item.metadata = setMetadata(item, metadata)
}
const toSave = locationRepo.merge(item, data)
await locationRepo.save(toSave)
await this.eventBusService_.emit(StockLocationService.Events.UPDATED, {
id: stockLocationId,
})
return item
})
}
/**
* Updates an address for a stock location.
* @param {string} addressId - The ID of the address to update.
* @param {StockLocationAddressInput} address - The update data for the address.
* @param {Object} context - Context for the update.
* @param {EntityManager} context.manager - The entity manager to use for the update.
* @returns {Promise<StockLocationAddress>} - The updated stock location address.
*/
protected async updateAddress(
addressId: string,
address: StockLocationAddressInput,
context: { manager?: EntityManager } = {}
): Promise<StockLocationAddress> {
const manager = context.manager || this.getManager()
const locationAddressRepo = manager.getRepository(StockLocationAddress)
const existingAddress = await locationAddressRepo.findOne(addressId)
if (!existingAddress) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`StockLocation address with id ${addressId} was not found`
)
}
const toSave = locationAddressRepo.merge(existingAddress, address)
const { metadata } = address
if (metadata) {
toSave.metadata = setMetadata(toSave, metadata)
}
return await locationAddressRepo.save(toSave)
}
/**
* Deletes a stock location.
* @param {string} id - The ID of the stock location to delete.
* @returns {Promise<void>} - An empty promise.
*/
async delete(id: string): Promise<void> {
const manager = this.getManager()
const locationRepo = manager.getRepository(StockLocation)
await locationRepo.softRemove({ id })
await this.eventBusService_.emit(StockLocationService.Events.DELETED, {
id,
})
}
}