From d680c7ee4c74f166ba26002746ef62e92f4b6d41 Mon Sep 17 00:00:00 2001 From: Stevche Radevski Date: Tue, 14 May 2024 13:21:30 +0200 Subject: [PATCH] Remove v1-related code from medusa app (#7326) * chore: Remove unused validations and utilities * chore: Remove all resources that are not being loaded * chore: Remove unused dependencies, typeorm related code and fix tests * chore: Use createAdminUser in all module tests --- .../api/__tests__/admin/product.js | 2 +- integration-tests/helpers/admin-seeder.js | 3 - .../admin/email-password-provider.spec.ts | 7 +- .../cart/store/add-promotions-to-cart.spec.ts | 7 +- .../cart/store/cart.workflows.spec.ts | 7 +- .../store/remove-promotions-from-cart.spec.ts | 7 +- .../customer/store/create-customer.spec.ts | 7 +- .../admin/add-price-list-price-batch.spec.ts | 4 +- .../delete-price-list-prices-by-product.ts | 4 +- .../delete-price-list-prices-by-variant.ts | 4 +- .../admin/delete-price-list-prices.ts | 4 +- .../price-lists/store/get-product.ts | 4 +- .../modules/__tests__/pricing/get-product.ts | 4 +- .../admin/create-product-variant.spec.ts | 4 +- .../product/admin/export-products.spec.ts | 7 +- .../product/admin/import-products.spec.ts | 7 +- .../modules/__tests__/product/admin/index.ts | 7 +- .../admin/update-product-variant.spec.ts | 25 +- .../product/admin/update-product.spec.ts | 4 +- .../src/medusa-test-runner-utils/use-db.js | 30 +- packages/medusa/package.json | 14 +- .../admin/inventory-items/validators.ts | 9 +- .../admin/product-categories/validators.ts | 32 +- .../store/product-categories/validators.ts | 22 +- .../api-v2/utils/common-validators/common.ts | 8 +- .../src/commands/utils/get-migrations.js | 153 +--- packages/medusa/src/helpers/test-request.js | 209 ----- packages/medusa/src/index.js | 6 - .../transaction-base-service.spec.ts | 34 - packages/medusa/src/interfaces/index.ts | 3 - .../src/interfaces/models/base-entity.ts | 20 - .../models/soft-deletable-entity.ts | 8 - .../interfaces/transaction-base-service.ts | 152 ---- .../src/loaders/__tests__/models.spec.ts | 47 -- .../src/loaders/__tests__/plugins.spec.ts | 304 -------- .../__tests__/register-plugin-models.spec.ts | 36 - .../jobs/__fixtures__/jobs/every-hour.ts | 11 - .../jobs/__fixtures__/jobs/every-minute.ts | 11 - .../loaders/helpers/jobs/__mocks__/index.ts | 16 - .../helpers/jobs/__tests__/index.spec.ts | 49 -- .../medusa/src/loaders/helpers/jobs/index.ts | 174 ----- .../src/loaders/helpers/resolve-plugins.ts | 2 +- .../routing/__fixtures__/server/index.js | 8 - .../src/loaders/helpers/subscribers/index.ts | 4 +- .../src/loaders/load-medusa-project-apis.ts | 15 +- packages/medusa/src/loaders/medusa-app.ts | 1 - packages/medusa/src/loaders/models.ts | 87 --- packages/medusa/src/loaders/plugins.ts | 705 ----------------- packages/medusa/src/loaders/repositories.ts | 32 - packages/medusa/src/loaders/search-index.ts | 35 - packages/medusa/src/loaders/services.ts | 35 - packages/medusa/src/loaders/strategies.ts | 58 -- .../1611063162649-initial_schema.ts | 382 ---------- .../1611063174563-countries_currencies.ts | 44 -- .../src/migrations/1612284947120-claims.ts | 213 ------ .../src/migrations/1612353094577-indexes.ts | 191 ----- .../migrations/1613146953072-notifications.ts | 49 -- ...613146953073-product_type_category_tags.ts | 76 -- .../migrations/1613384784316-draft_orders.ts | 50 -- .../1613656135167-tracking_links.ts | 16 - .../migrations/1614684597235-cart_context.ts | 13 - .../migrations/1615891636559-return_reason.ts | 33 - .../1615970124120-discount_usage_count.ts | 17 - .../1617002207608-discount_usage.ts | 41 - .../1619108646647-nullable_password.ts | 15 - .../1623231564533-no_notification.ts | 25 - .../1624287602631-gc_remove_unique_order.ts | 19 - ...325746-soft_deleting_unique_constraints.ts | 42 - ...513367-ensure_cancellation_fields_exist.ts | 48 -- ...27995307200-add_discountable_to_product.ts | 14 - .../1630505790603-allow_backorder_swaps.ts | 24 - ...04895519-rank_column_with_default_value.ts | 23 - .../1631261634964-enforce_uniqueness.ts | 41 - ...31696624528-valid_duration_for_discount.ts | 14 - .../1631800727788-nested_return_reasons.ts | 20 - .../1631864388026-status_on_product.ts | 28 - .../src/migrations/1632220294687-add_notes.ts | 23 - ...te_date_on_shipping_option_requirements.ts | 18 - .../1633512755401-extended_user_api.ts | 58 -- ...33614437919-add_custom_shipping_options.ts | 34 - ...38543550000-order_tax_rate_to_real_type.ts | 23 - .../1638952072999-external_id_order.ts | 19 - .../1641636508055-new_tax_system.ts | 178 ----- .../1644943746861-customer_groups.ts | 44 -- .../1646324713514-discount_conditions.ts | 245 ------ ...0108-update_money_amount_add_price_list.ts | 38 - ...1648600574750-add_line_item_adjustments.ts | 39 - .../1648641130007-tax_line_constraints.ts | 23 - .../1649775522087-add_batch_job_model.ts | 42 - .../migrations/1656949291839-sales_channel.ts | 74 -- ...7098186554-taxed_gift_card_transactions.ts | 25 - .../1657267320181-extended_batch_job.ts | 38 - .../1659501357661-tax_inclusive_pricing.ts | 46 -- ...-payment_session_uniq_cartId_providerId.ts | 13 - .../1661345741249-multi_payment_cart.ts | 25 - ...swap_fulfillment_status_requires_action.ts | 33 - .../migrations/1663059812399-order_editing.ts | 49 -- ...12400-linte-item-original-item-relation.ts | 46 -- .../1664880666982-payment-collection.ts | 124 --- .../1666173221888-add_analytics_config.ts | 24 - .../1667815005070-publishable_api_key.ts | 19 - ...280562-update_customer_email_constraint.ts | 25 - ...670855241304-add-tax-rate-to-gift-cards.ts | 17 - .../1671711415179-multi_location.ts | 51 -- .../1672906846559-product-category.ts | 38 - ...2906846560-payment-session-is-initiated.ts | 24 - .../1673003729870-staged_job_options.ts | 15 - .../1673550502785-unique_pay_sess_cart_id.ts | 16 - .../1674455083104-product_category_product.ts | 45 -- ...675689306130-multi_location_soft_delete.ts | 51 -- .../1677234878504-product_category_rank.ts | 26 - .../1678093365811-ensure_required_quantity.ts | 31 - ...8093365812-line-item-adjustments-amount.ts | 15 - ...79950221063-category-remove-soft-delete.ts | 20 - .../1679950645253-category-create-indexes.ts | 22 - ...50645254-product-domain-impoved-indexes.ts | 39 - ...679950645254-product-search-gin-indexes.ts | 33 - ...680714052628-add_sales_channel_metadata.ts | 22 - ...272-add-description-to-product-category.ts | 15 - ...e-item-tax-adjustment-on-cascade-delete.ts | 37 - ...3273-add-table-product-shipping-profile.ts | 49 -- ...73273-drop-product-id-fk-sales-channels.ts | 19 - ...7773273-drop-variant-id-fk-money-amount.ts | 21 - ...692870898423-update_return_reason_index.ts | 21 - .../1692870898424-line-item-product-id.ts | 21 - ...timestemps-to-product-shipping-profiles.ts | 21 - ...y_amount_constraints_for_pricing_module.ts | 51 -- ...1694602553610-drop-fks-isolated-product.ts | 34 - ...98056997411-product-sales-channels-link.ts | 35 - ...198-drop-non-null-constraint-price-list.ts | 17 - ...794649-add-metadata-to-product-category.ts | 17 - ...1701860329931-order-sales-channels-link.ts | 42 - ...811-publishable-key-sales-channels-link.ts | 29 - ...477798-alter-customer-unique-constraint.ts | 37 - packages/medusa/src/models/idempotency-key.ts | 122 --- packages/medusa/src/models/index.ts | 2 - packages/medusa/src/models/staged-job.ts | 56 -- packages/medusa/src/modules-config.ts | 8 - .../medusa/src/repositories/__mocks__/cart.js | 461 ----------- .../src/repositories/__mocks__/customer.js | 52 -- .../src/repositories/__mocks__/discount.js | 153 ---- .../src/repositories/__mocks__/document.js | 15 - .../__mocks__/dynamic-discount-code.js | 25 - .../repositories/__mocks__/money-amount.js | 31 - .../src/repositories/__mocks__/order.js | 514 ------------- .../src/repositories/__mocks__/price-list.js | 22 - .../__mocks__/product-category.ts | 134 ---- .../repositories/__mocks__/product-variant.js | 107 --- .../src/repositories/__mocks__/product.js | 117 --- .../src/repositories/__mocks__/region.js | 66 -- .../repositories/__mocks__/shipping-option.js | 61 -- .../__mocks__/shipping-profile.js | 52 -- .../src/repositories/__mocks__/store.js | 17 - .../medusa/src/repositories/__mocks__/user.js | 31 - .../src/repositories/idempotency-key.ts | 5 - .../medusa/src/repositories/staged-job.ts | 22 - .../src/scripts/create-default-rule-types.ts | 28 - packages/medusa/src/scripts/db-config.ts | 10 - .../src/scripts/migrate-to-pricing-module.ts | 218 ------ .../utils/create-default-rule-types.ts | 31 - ...migrate-money-amounts-to-pricing-module.ts | 87 --- .../src/services/__mocks__/event-bus.js | 13 - .../src/services/__mocks__/idempotency-key.js | 42 - .../src/services/__mocks__/middleware.js | 12 - .../src/services/__tests__/job-scheduler.js | 123 --- .../src/services/__tests__/middleware.js | 79 -- packages/medusa/src/services/event-bus.ts | 241 ------ .../medusa/src/services/idempotency-key.ts | 221 ------ packages/medusa/src/services/index.ts | 5 - packages/medusa/src/services/job-scheduler.ts | 141 ---- packages/medusa/src/services/middleware.ts | 128 ---- packages/medusa/src/services/staged-job.ts | 62 -- packages/medusa/src/subscribers/batch-job.ts | 87 --- packages/medusa/src/subscribers/cart.ts | 52 -- .../medusa/src/subscribers/notification.js | 15 - packages/medusa/src/subscribers/order.js | 67 -- .../medusa/src/subscribers/payment-webhook.ts | 3 +- packages/medusa/src/subscribers/product.ts | 122 --- .../medusa/src/subscribers/search-indexing.ts | 83 -- packages/medusa/src/types/analytics-config.ts | 9 - packages/medusa/src/types/batch-job.ts | 77 -- packages/medusa/src/types/common.ts | 436 +---------- packages/medusa/src/types/idempotency-key.ts | 12 - packages/medusa/src/types/scheduled-jobs.ts | 22 - .../src/types/validators/exactly-one.ts | 31 - .../src/types/validators/operator-map.ts | 67 -- packages/medusa/src/types/validators/xor.ts | 21 - .../src/utils/__tests__/build-query.spec.ts | 318 -------- .../__tests__/calculate-price-tax-amount.ts | 45 -- .../csv-cell-content-formatter.spec.ts | 59 -- .../src/utils/__tests__/generate-entity-id.ts | 26 - .../src/utils/__tests__/has-changes.spec.ts | 59 -- packages/medusa/src/utils/build-query.ts | 243 ------ .../src/utils/calculate-price-tax-amount.ts | 21 - packages/medusa/src/utils/countries.ts | 2 - .../src/utils/csv-cell-content-formatter.ts | 24 - packages/medusa/src/utils/currencies.ts | 2 - packages/medusa/src/utils/db-aware-column.ts | 26 - .../src/utils/feature-flag-decorators.ts | 87 --- .../medusa/src/utils/generate-entity-id.ts | 16 - packages/medusa/src/utils/get-query-config.ts | 20 +- packages/medusa/src/utils/has-changes.ts | 26 - .../medusa/src/utils/idempotency/index.ts | 2 - .../initialize-idempotency-request.ts | 26 - .../utils/idempotency/run-idempotency-step.ts | 44 -- packages/medusa/src/utils/index.ts | 9 - packages/medusa/src/utils/is-email.ts | 20 - .../medusa/src/utils/manual-auto-increment.ts | 5 - .../__tests__/transform-query.spec.ts | 716 ------------------ .../medusa/src/utils/middlewares/index.ts | 4 - .../src/utils/middlewares/normalized-query.ts | 24 - .../src/utils/middlewares/transform-body.ts | 20 - .../middlewares/transform-includes-options.ts | 57 -- .../src/utils/middlewares/transform-query.ts | 140 ---- .../src/utils/omit-relation-if-exists.ts | 15 - .../src/utils/remote-query-fetch-data.ts | 2 - packages/medusa/src/utils/repository.ts | 381 ---------- .../medusa/src/utils/transformers/tree.ts | 47 -- packages/medusa/src/utils/validate-id.ts | 41 - packages/medusa/src/utils/validator.ts | 73 -- .../src/utils/validators/date-transform.ts | 9 - .../src/utils/validators/greater-than.ts | 34 - .../medusa/src/utils/validators/is-boolean.ts | 14 - .../medusa/src/utils/validators/is-type.ts | 120 --- .../src/utils/validators/iso8601-duration.ts | 26 - yarn.lock | 53 +- 226 files changed, 110 insertions(+), 13506 deletions(-) delete mode 100644 packages/medusa/src/helpers/test-request.js delete mode 100644 packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts delete mode 100644 packages/medusa/src/interfaces/index.ts delete mode 100644 packages/medusa/src/interfaces/models/base-entity.ts delete mode 100644 packages/medusa/src/interfaces/models/soft-deletable-entity.ts delete mode 100644 packages/medusa/src/interfaces/transaction-base-service.ts delete mode 100644 packages/medusa/src/loaders/__tests__/models.spec.ts delete mode 100644 packages/medusa/src/loaders/__tests__/plugins.spec.ts delete mode 100644 packages/medusa/src/loaders/__tests__/register-plugin-models.spec.ts delete mode 100644 packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-hour.ts delete mode 100644 packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-minute.ts delete mode 100644 packages/medusa/src/loaders/helpers/jobs/__mocks__/index.ts delete mode 100644 packages/medusa/src/loaders/helpers/jobs/__tests__/index.spec.ts delete mode 100644 packages/medusa/src/loaders/helpers/jobs/index.ts delete mode 100644 packages/medusa/src/loaders/models.ts delete mode 100644 packages/medusa/src/loaders/plugins.ts delete mode 100644 packages/medusa/src/loaders/repositories.ts delete mode 100644 packages/medusa/src/loaders/search-index.ts delete mode 100644 packages/medusa/src/loaders/services.ts delete mode 100644 packages/medusa/src/loaders/strategies.ts delete mode 100644 packages/medusa/src/migrations/1611063162649-initial_schema.ts delete mode 100644 packages/medusa/src/migrations/1611063174563-countries_currencies.ts delete mode 100644 packages/medusa/src/migrations/1612284947120-claims.ts delete mode 100644 packages/medusa/src/migrations/1612353094577-indexes.ts delete mode 100644 packages/medusa/src/migrations/1613146953072-notifications.ts delete mode 100644 packages/medusa/src/migrations/1613146953073-product_type_category_tags.ts delete mode 100644 packages/medusa/src/migrations/1613384784316-draft_orders.ts delete mode 100644 packages/medusa/src/migrations/1613656135167-tracking_links.ts delete mode 100644 packages/medusa/src/migrations/1614684597235-cart_context.ts delete mode 100644 packages/medusa/src/migrations/1615891636559-return_reason.ts delete mode 100644 packages/medusa/src/migrations/1615970124120-discount_usage_count.ts delete mode 100644 packages/medusa/src/migrations/1617002207608-discount_usage.ts delete mode 100644 packages/medusa/src/migrations/1619108646647-nullable_password.ts delete mode 100644 packages/medusa/src/migrations/1623231564533-no_notification.ts delete mode 100644 packages/medusa/src/migrations/1624287602631-gc_remove_unique_order.ts delete mode 100644 packages/medusa/src/migrations/1624610325746-soft_deleting_unique_constraints.ts delete mode 100644 packages/medusa/src/migrations/1625560513367-ensure_cancellation_fields_exist.ts delete mode 100644 packages/medusa/src/migrations/1627995307200-add_discountable_to_product.ts delete mode 100644 packages/medusa/src/migrations/1630505790603-allow_backorder_swaps.ts delete mode 100644 packages/medusa/src/migrations/1631104895519-rank_column_with_default_value.ts delete mode 100644 packages/medusa/src/migrations/1631261634964-enforce_uniqueness.ts delete mode 100644 packages/medusa/src/migrations/1631696624528-valid_duration_for_discount.ts delete mode 100644 packages/medusa/src/migrations/1631800727788-nested_return_reasons.ts delete mode 100644 packages/medusa/src/migrations/1631864388026-status_on_product.ts delete mode 100644 packages/medusa/src/migrations/1632220294687-add_notes.ts delete mode 100644 packages/medusa/src/migrations/1632828114899-delete_date_on_shipping_option_requirements.ts delete mode 100644 packages/medusa/src/migrations/1633512755401-extended_user_api.ts delete mode 100644 packages/medusa/src/migrations/1633614437919-add_custom_shipping_options.ts delete mode 100644 packages/medusa/src/migrations/1638543550000-order_tax_rate_to_real_type.ts delete mode 100644 packages/medusa/src/migrations/1638952072999-external_id_order.ts delete mode 100644 packages/medusa/src/migrations/1641636508055-new_tax_system.ts delete mode 100644 packages/medusa/src/migrations/1644943746861-customer_groups.ts delete mode 100644 packages/medusa/src/migrations/1646324713514-discount_conditions.ts delete mode 100644 packages/medusa/src/migrations/1646915480108-update_money_amount_add_price_list.ts delete mode 100644 packages/medusa/src/migrations/1648600574750-add_line_item_adjustments.ts delete mode 100644 packages/medusa/src/migrations/1648641130007-tax_line_constraints.ts delete mode 100644 packages/medusa/src/migrations/1649775522087-add_batch_job_model.ts delete mode 100644 packages/medusa/src/migrations/1656949291839-sales_channel.ts delete mode 100644 packages/medusa/src/migrations/1657098186554-taxed_gift_card_transactions.ts delete mode 100644 packages/medusa/src/migrations/1657267320181-extended_batch_job.ts delete mode 100644 packages/medusa/src/migrations/1659501357661-tax_inclusive_pricing.ts delete mode 100644 packages/medusa/src/migrations/1660040729000-payment_session_uniq_cartId_providerId.ts delete mode 100644 packages/medusa/src/migrations/1661345741249-multi_payment_cart.ts delete mode 100644 packages/medusa/src/migrations/1661863940645-swap_fulfillment_status_requires_action.ts delete mode 100644 packages/medusa/src/migrations/1663059812399-order_editing.ts delete mode 100644 packages/medusa/src/migrations/1663059812400-linte-item-original-item-relation.ts delete mode 100644 packages/medusa/src/migrations/1664880666982-payment-collection.ts delete mode 100644 packages/medusa/src/migrations/1666173221888-add_analytics_config.ts delete mode 100644 packages/medusa/src/migrations/1667815005070-publishable_api_key.ts delete mode 100644 packages/medusa/src/migrations/1669032280562-update_customer_email_constraint.ts delete mode 100644 packages/medusa/src/migrations/1670855241304-add-tax-rate-to-gift-cards.ts delete mode 100644 packages/medusa/src/migrations/1671711415179-multi_location.ts delete mode 100644 packages/medusa/src/migrations/1672906846559-product-category.ts delete mode 100644 packages/medusa/src/migrations/1672906846560-payment-session-is-initiated.ts delete mode 100644 packages/medusa/src/migrations/1673003729870-staged_job_options.ts delete mode 100644 packages/medusa/src/migrations/1673550502785-unique_pay_sess_cart_id.ts delete mode 100644 packages/medusa/src/migrations/1674455083104-product_category_product.ts delete mode 100644 packages/medusa/src/migrations/1675689306130-multi_location_soft_delete.ts delete mode 100644 packages/medusa/src/migrations/1677234878504-product_category_rank.ts delete mode 100644 packages/medusa/src/migrations/1678093365811-ensure_required_quantity.ts delete mode 100644 packages/medusa/src/migrations/1678093365812-line-item-adjustments-amount.ts delete mode 100644 packages/medusa/src/migrations/1679950221063-category-remove-soft-delete.ts delete mode 100644 packages/medusa/src/migrations/1679950645253-category-create-indexes.ts delete mode 100644 packages/medusa/src/migrations/1679950645254-product-domain-impoved-indexes.ts delete mode 100644 packages/medusa/src/migrations/1679950645254-product-search-gin-indexes.ts delete mode 100644 packages/medusa/src/migrations/1680714052628-add_sales_channel_metadata.ts delete mode 100644 packages/medusa/src/migrations/1680857773272-add-description-to-product-category.ts delete mode 100644 packages/medusa/src/migrations/1680857773272-line-item-tax-adjustment-on-cascade-delete.ts delete mode 100644 packages/medusa/src/migrations/1680857773273-add-table-product-shipping-profile.ts delete mode 100644 packages/medusa/src/migrations/1680857773273-drop-product-id-fk-sales-channels.ts delete mode 100644 packages/medusa/src/migrations/1680857773273-drop-variant-id-fk-money-amount.ts delete mode 100644 packages/medusa/src/migrations/1692870898423-update_return_reason_index.ts delete mode 100644 packages/medusa/src/migrations/1692870898424-line-item-product-id.ts delete mode 100644 packages/medusa/src/migrations/1692870898425-add-timestemps-to-product-shipping-profiles.ts delete mode 100644 packages/medusa/src/migrations/1692953518123-drop_money_amount_constraints_for_pricing_module.ts delete mode 100644 packages/medusa/src/migrations/1694602553610-drop-fks-isolated-product.ts delete mode 100644 packages/medusa/src/migrations/1698056997411-product-sales-channels-link.ts delete mode 100644 packages/medusa/src/migrations/1699371074198-drop-non-null-constraint-price-list.ts delete mode 100644 packages/medusa/src/migrations/1699564794649-add-metadata-to-product-category.ts delete mode 100644 packages/medusa/src/migrations/1701860329931-order-sales-channels-link.ts delete mode 100644 packages/medusa/src/migrations/1701894188811-publishable-key-sales-channels-link.ts delete mode 100644 packages/medusa/src/migrations/1709888477798-alter-customer-unique-constraint.ts delete mode 100644 packages/medusa/src/models/idempotency-key.ts delete mode 100644 packages/medusa/src/models/index.ts delete mode 100644 packages/medusa/src/models/staged-job.ts delete mode 100644 packages/medusa/src/modules-config.ts delete mode 100644 packages/medusa/src/repositories/__mocks__/cart.js delete mode 100644 packages/medusa/src/repositories/__mocks__/customer.js delete mode 100644 packages/medusa/src/repositories/__mocks__/discount.js delete mode 100644 packages/medusa/src/repositories/__mocks__/document.js delete mode 100644 packages/medusa/src/repositories/__mocks__/dynamic-discount-code.js delete mode 100644 packages/medusa/src/repositories/__mocks__/money-amount.js delete mode 100644 packages/medusa/src/repositories/__mocks__/order.js delete mode 100644 packages/medusa/src/repositories/__mocks__/price-list.js delete mode 100644 packages/medusa/src/repositories/__mocks__/product-category.ts delete mode 100644 packages/medusa/src/repositories/__mocks__/product-variant.js delete mode 100644 packages/medusa/src/repositories/__mocks__/product.js delete mode 100644 packages/medusa/src/repositories/__mocks__/region.js delete mode 100644 packages/medusa/src/repositories/__mocks__/shipping-option.js delete mode 100644 packages/medusa/src/repositories/__mocks__/shipping-profile.js delete mode 100644 packages/medusa/src/repositories/__mocks__/store.js delete mode 100644 packages/medusa/src/repositories/__mocks__/user.js delete mode 100644 packages/medusa/src/repositories/idempotency-key.ts delete mode 100644 packages/medusa/src/repositories/staged-job.ts delete mode 100644 packages/medusa/src/scripts/create-default-rule-types.ts delete mode 100644 packages/medusa/src/scripts/db-config.ts delete mode 100644 packages/medusa/src/scripts/migrate-to-pricing-module.ts delete mode 100644 packages/medusa/src/scripts/utils/create-default-rule-types.ts delete mode 100644 packages/medusa/src/scripts/utils/migrate-money-amounts-to-pricing-module.ts delete mode 100644 packages/medusa/src/services/__mocks__/event-bus.js delete mode 100644 packages/medusa/src/services/__mocks__/idempotency-key.js delete mode 100644 packages/medusa/src/services/__mocks__/middleware.js delete mode 100644 packages/medusa/src/services/__tests__/job-scheduler.js delete mode 100644 packages/medusa/src/services/__tests__/middleware.js delete mode 100644 packages/medusa/src/services/event-bus.ts delete mode 100644 packages/medusa/src/services/idempotency-key.ts delete mode 100644 packages/medusa/src/services/index.ts delete mode 100644 packages/medusa/src/services/job-scheduler.ts delete mode 100644 packages/medusa/src/services/middleware.ts delete mode 100644 packages/medusa/src/services/staged-job.ts delete mode 100644 packages/medusa/src/subscribers/batch-job.ts delete mode 100644 packages/medusa/src/subscribers/cart.ts delete mode 100644 packages/medusa/src/subscribers/notification.js delete mode 100644 packages/medusa/src/subscribers/order.js delete mode 100644 packages/medusa/src/subscribers/product.ts delete mode 100644 packages/medusa/src/subscribers/search-indexing.ts delete mode 100644 packages/medusa/src/types/analytics-config.ts delete mode 100644 packages/medusa/src/types/batch-job.ts delete mode 100644 packages/medusa/src/types/idempotency-key.ts delete mode 100644 packages/medusa/src/types/scheduled-jobs.ts delete mode 100644 packages/medusa/src/types/validators/exactly-one.ts delete mode 100644 packages/medusa/src/types/validators/operator-map.ts delete mode 100644 packages/medusa/src/types/validators/xor.ts delete mode 100644 packages/medusa/src/utils/__tests__/build-query.spec.ts delete mode 100644 packages/medusa/src/utils/__tests__/calculate-price-tax-amount.ts delete mode 100644 packages/medusa/src/utils/__tests__/csv-cell-content-formatter.spec.ts delete mode 100644 packages/medusa/src/utils/__tests__/generate-entity-id.ts delete mode 100644 packages/medusa/src/utils/__tests__/has-changes.spec.ts delete mode 100644 packages/medusa/src/utils/build-query.ts delete mode 100644 packages/medusa/src/utils/calculate-price-tax-amount.ts delete mode 100644 packages/medusa/src/utils/countries.ts delete mode 100644 packages/medusa/src/utils/csv-cell-content-formatter.ts delete mode 100644 packages/medusa/src/utils/currencies.ts delete mode 100644 packages/medusa/src/utils/db-aware-column.ts delete mode 100644 packages/medusa/src/utils/feature-flag-decorators.ts delete mode 100644 packages/medusa/src/utils/generate-entity-id.ts delete mode 100644 packages/medusa/src/utils/has-changes.ts delete mode 100644 packages/medusa/src/utils/idempotency/index.ts delete mode 100644 packages/medusa/src/utils/idempotency/initialize-idempotency-request.ts delete mode 100644 packages/medusa/src/utils/idempotency/run-idempotency-step.ts delete mode 100644 packages/medusa/src/utils/is-email.ts delete mode 100644 packages/medusa/src/utils/manual-auto-increment.ts delete mode 100644 packages/medusa/src/utils/middlewares/__tests__/transform-query.spec.ts delete mode 100644 packages/medusa/src/utils/middlewares/normalized-query.ts delete mode 100644 packages/medusa/src/utils/middlewares/transform-body.ts delete mode 100644 packages/medusa/src/utils/middlewares/transform-includes-options.ts delete mode 100644 packages/medusa/src/utils/middlewares/transform-query.ts delete mode 100644 packages/medusa/src/utils/omit-relation-if-exists.ts delete mode 100644 packages/medusa/src/utils/repository.ts delete mode 100644 packages/medusa/src/utils/transformers/tree.ts delete mode 100644 packages/medusa/src/utils/validate-id.ts delete mode 100644 packages/medusa/src/utils/validator.ts delete mode 100644 packages/medusa/src/utils/validators/date-transform.ts delete mode 100644 packages/medusa/src/utils/validators/greater-than.ts delete mode 100644 packages/medusa/src/utils/validators/is-boolean.ts delete mode 100644 packages/medusa/src/utils/validators/is-type.ts delete mode 100644 packages/medusa/src/utils/validators/iso8601-duration.ts diff --git a/integration-tests/api/__tests__/admin/product.js b/integration-tests/api/__tests__/admin/product.js index fc6c23ab03..68294d1367 100644 --- a/integration-tests/api/__tests__/admin/product.js +++ b/integration-tests/api/__tests__/admin/product.js @@ -73,7 +73,7 @@ const getProductFixture = (overrides) => ({ }) medusaIntegrationTestRunner({ - env: { MEDUSA_FF_PRODUCT_CATEGORIES: true }, + env: { MEDUSA_FF_PRODUCT_CATEGORIES: true, MEDUSA_FF_MEDUSA_V2: true }, testSuite: ({ dbConnection, getContainer, api }) => { let baseProduct let proposedProduct diff --git a/integration-tests/helpers/admin-seeder.js b/integration-tests/helpers/admin-seeder.js index d583fed89d..a6c3b0f92c 100644 --- a/integration-tests/helpers/admin-seeder.js +++ b/integration-tests/helpers/admin-seeder.js @@ -9,9 +9,6 @@ module.exports = async (dataSource, data = {}) => { const user = await manager.insert("user", { id: "admin_user", email: "admin@medusa.js", - api_token: "test_token", - role: "admin", - password_hash, ...data, }) diff --git a/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts b/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts index 4624459ca9..227875a4ad 100644 --- a/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts +++ b/integration-tests/modules/__tests__/auth/admin/email-password-provider.spec.ts @@ -1,8 +1,11 @@ import { ModuleRegistrationName } from "@medusajs/modules-sdk" import { IAuthModuleService, ICustomerModuleService } from "@medusajs/types" import Scrypt from "scrypt-kdf" -import adminSeeder from "../../../../helpers/admin-seeder" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -23,7 +26,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) }) const password = "supersecret" diff --git a/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts b/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts index dc8ddb215f..74416bd649 100644 --- a/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/add-promotions-to-cart.spec.ts @@ -6,8 +6,11 @@ import { } from "@medusajs/modules-sdk" import { ICartModuleService, IPromotionModuleService } from "@medusajs/types" import { PromotionType } from "@medusajs/utils" -import adminSeeder from "../../../../helpers/admin-seeder" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -32,7 +35,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) }) describe("POST /store/carts/:id/promotions", () => { diff --git a/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts b/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts index f5f845b98b..05b8bd93c9 100644 --- a/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/cart.workflows.spec.ts @@ -28,7 +28,10 @@ import { } from "@medusajs/types" import { ContainerRegistrationKeys, RuleOperator } from "@medusajs/utils" import { medusaIntegrationTestRunner } from "medusa-test-utils" -import adminSeeder from "../../../../helpers/admin-seeder" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" jest.setTimeout(200000) @@ -84,7 +87,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) // Here, so we don't have to create a region for each test defaultRegion = await regionModuleService.create({ diff --git a/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts b/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts index 212eaa7522..4d5ae7ebc7 100644 --- a/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts +++ b/integration-tests/modules/__tests__/cart/store/remove-promotions-from-cart.spec.ts @@ -6,8 +6,11 @@ import { } from "@medusajs/modules-sdk" import { ICartModuleService, IPromotionModuleService } from "@medusajs/types" import { PromotionType } from "@medusajs/utils" -import adminSeeder from "../../../../helpers/admin-seeder" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -32,7 +35,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) }) describe("DELETE /store/carts/:id/promotions", () => { diff --git a/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts b/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts index d47dfa265e..398c160822 100644 --- a/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts +++ b/integration-tests/modules/__tests__/customer/store/create-customer.spec.ts @@ -1,9 +1,12 @@ import { IAuthModuleService, ICustomerModuleService } from "@medusajs/types" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import adminSeeder from "../../../../helpers/admin-seeder" import jwt from "jsonwebtoken" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -24,7 +27,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) }) it("should create a customer", async () => { diff --git a/integration-tests/modules/__tests__/price-lists/admin/add-price-list-price-batch.spec.ts b/integration-tests/modules/__tests__/price-lists/admin/add-price-list-price-batch.spec.ts index a8e997b98b..58eed4ffa7 100644 --- a/integration-tests/modules/__tests__/price-lists/admin/add-price-list-price-batch.spec.ts +++ b/integration-tests/modules/__tests__/price-lists/admin/add-price-list-price-batch.spec.ts @@ -8,10 +8,10 @@ import { PriceListStatus, PriceListType, } from "@medusajs/types" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -40,7 +40,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-product.ts b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-product.ts index 1f0afebb40..f3cc69f3fd 100644 --- a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-product.ts +++ b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-product.ts @@ -5,9 +5,9 @@ import { import { IPricingModuleService } from "@medusajs/types" import { medusaIntegrationTestRunner } from "medusa-test-utils" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -38,7 +38,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-variant.ts b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-variant.ts index 965e4bff16..6e1c563380 100644 --- a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-variant.ts +++ b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices-by-variant.ts @@ -5,9 +5,9 @@ import { import { IPricingModuleService } from "@medusajs/types" import { medusaIntegrationTestRunner } from "medusa-test-utils" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -36,7 +36,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices.ts b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices.ts index de1dcc974c..0cba13f972 100644 --- a/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices.ts +++ b/integration-tests/modules/__tests__/price-lists/admin/delete-price-list-prices.ts @@ -5,9 +5,9 @@ import { import { IPricingModuleService } from "@medusajs/types" import { medusaIntegrationTestRunner } from "medusa-test-utils" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -36,7 +36,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/price-lists/store/get-product.ts b/integration-tests/modules/__tests__/price-lists/store/get-product.ts index c20dbc589b..5deccc4620 100644 --- a/integration-tests/modules/__tests__/price-lists/store/get-product.ts +++ b/integration-tests/modules/__tests__/price-lists/store/get-product.ts @@ -10,10 +10,10 @@ import { PriceListStatus, PriceListType, } from "@medusajs/types" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -43,7 +43,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/pricing/get-product.ts b/integration-tests/modules/__tests__/pricing/get-product.ts index 9bb318505b..db66c274b6 100644 --- a/integration-tests/modules/__tests__/pricing/get-product.ts +++ b/integration-tests/modules/__tests__/pricing/get-product.ts @@ -1,9 +1,9 @@ import { simpleCartFactory, simpleRegionFactory } from "../../../factories" import { ModuleRegistrationName } from "@medusajs/modules-sdk" -import adminSeeder from "../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../helpers/create-default-rule-types" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { createAdminUser } from "../../../helpers/create-admin-user" jest.setTimeout(5000000) @@ -34,7 +34,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { await createDefaultRuleTypes(medusaContainer) - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, medusaContainer) await simpleRegionFactory(dbConnection, { id: "region-1", currency_code: "usd", diff --git a/integration-tests/modules/__tests__/product/admin/create-product-variant.spec.ts b/integration-tests/modules/__tests__/product/admin/create-product-variant.spec.ts index 2cd1a4dbe8..98d5cd7db0 100644 --- a/integration-tests/modules/__tests__/product/admin/create-product-variant.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/create-product-variant.spec.ts @@ -4,9 +4,9 @@ import { simpleProductFactory, simpleRegionFactory, } from "../../../../factories" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { medusaIntegrationTestRunner } from "medusa-test-utils" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -33,7 +33,7 @@ medusaIntegrationTestRunner({ }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/product/admin/export-products.spec.ts b/integration-tests/modules/__tests__/product/admin/export-products.spec.ts index 7080ea0c3e..ea37a80908 100644 --- a/integration-tests/modules/__tests__/product/admin/export-products.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/export-products.spec.ts @@ -5,9 +5,12 @@ import { useApi } from "../../../../environment-helpers/use-api" import { getContainer } from "../../../../environment-helpers/use-container" import { initDb, useDb } from "../../../../environment-helpers/use-db" import { simpleSalesChannelFactory } from "../../../../factories" -import adminSeeder from "../../../../helpers/admin-seeder" import productSeeder from "../../../../helpers/product-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" const setupServer = require("../../../../environment-helpers/setup-server") const userSeeder = require("../../../../helpers/user-seeder") @@ -64,7 +67,7 @@ describe.skip("Batch job of product-export type", () => { const container = getContainer() await createDefaultRuleTypes(container) await productSeeder(dbConnection) - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, container) await userSeeder(dbConnection) await simpleSalesChannelFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/product/admin/import-products.spec.ts b/integration-tests/modules/__tests__/product/admin/import-products.spec.ts index cba5e13a9d..9d55da2c1b 100644 --- a/integration-tests/modules/__tests__/product/admin/import-products.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/import-products.spec.ts @@ -7,9 +7,12 @@ import { getContainer } from "../../../../environment-helpers/use-container" import { initDb, useDb } from "../../../../environment-helpers/use-db" import { simpleProductFactory } from "../../../../factories" import { simpleProductCollectionFactory } from "../../../../factories/simple-product-collection-factory" -import adminSeeder from "../../../../helpers/admin-seeder" import batchJobSeeder from "../../../../helpers/batch-job-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" +import { + adminHeaders, + createAdminUser, +} from "../../../../helpers/create-admin-user" const setupServer = require("../../../../environment-helpers/setup-server") const userSeeder = require("../../../../helpers/user-seeder") @@ -98,7 +101,7 @@ describe.skip("Product import batch job", () => { const container = getContainer() await createDefaultRuleTypes(container) await batchJobSeeder(dbConnection) - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, container) await userSeeder(dbConnection) await simpleProductCollectionFactory(dbConnection, [ { diff --git a/integration-tests/modules/__tests__/product/admin/index.ts b/integration-tests/modules/__tests__/product/admin/index.ts index d033e24ec5..592556aebc 100644 --- a/integration-tests/modules/__tests__/product/admin/index.ts +++ b/integration-tests/modules/__tests__/product/admin/index.ts @@ -3,8 +3,6 @@ import { startBootstrapApp } from "../../../../environment-helpers/bootstrap-app import { useApi } from "../../../../environment-helpers/use-api" import { initDb, useDb } from "../../../../environment-helpers/use-db" -import adminSeeder from "../../../../helpers/admin-seeder" - import { Modules, ModulesDefinition } from "@medusajs/modules-sdk" import { MedusaV2Flag } from "@medusajs/utils" import { AxiosInstance } from "axios" @@ -14,6 +12,7 @@ import { simpleSalesChannelFactory, } from "../../../../factories" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -67,7 +66,7 @@ describe.skip("/admin/products", () => { describe("POST /admin/products", () => { beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, medusaContainer) await createDefaultRuleTypes(medusaContainer) await simpleSalesChannelFactory(dbConnection, { @@ -442,7 +441,7 @@ describe.skip("/admin/products", () => { beforeEach(async () => { await productSeeder(dbConnection) - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, medusaContainer) await createDefaultRuleTypes(medusaContainer) await simpleSalesChannelFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/product/admin/update-product-variant.spec.ts b/integration-tests/modules/__tests__/product/admin/update-product-variant.spec.ts index 70827bb4ce..0e5b6dcbd0 100644 --- a/integration-tests/modules/__tests__/product/admin/update-product-variant.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/update-product-variant.spec.ts @@ -1,16 +1,17 @@ -import {initDb, useDb} from "../../../../environment-helpers/use-db" -import {simpleProductFactory, simpleRegionFactory,} from "../../../../factories" - -import {AxiosInstance} from "axios" -import adminSeeder from "../../../../helpers/admin-seeder" +import { initDb, useDb } from "../../../../environment-helpers/use-db" import { - createDefaultRuleTypes -} from "../../../helpers/create-default-rule-types" -import {createVariantPriceSet} from "../../../helpers/create-variant-price-set" -import {getContainer} from "../../../../environment-helpers/use-container" + simpleProductFactory, + simpleRegionFactory, +} from "../../../../factories" + +import { AxiosInstance } from "axios" +import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" +import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" +import { getContainer } from "../../../../environment-helpers/use-container" import path from "path" -import {startBootstrapApp} from "../../../../environment-helpers/bootstrap-app" -import {useApi} from "../../../../environment-helpers/use-api" +import { startBootstrapApp } from "../../../../environment-helpers/bootstrap-app" +import { useApi } from "../../../../environment-helpers/use-api" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -49,7 +50,7 @@ describe.skip("POST /admin/products/:id/variants/:id", () => { }) beforeEach(async () => { - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await simpleRegionFactory(dbConnection, { diff --git a/integration-tests/modules/__tests__/product/admin/update-product.spec.ts b/integration-tests/modules/__tests__/product/admin/update-product.spec.ts index 8d86155a13..527dba1298 100644 --- a/integration-tests/modules/__tests__/product/admin/update-product.spec.ts +++ b/integration-tests/modules/__tests__/product/admin/update-product.spec.ts @@ -7,9 +7,9 @@ import { Region } from "@medusajs/medusa" import { AxiosInstance } from "axios" import path from "path" import { startBootstrapApp } from "../../../../environment-helpers/bootstrap-app" -import adminSeeder from "../../../../helpers/admin-seeder" import { createDefaultRuleTypes } from "../../../helpers/create-default-rule-types" import { createVariantPriceSet } from "../../../helpers/create-variant-price-set" +import { createAdminUser } from "../../../../helpers/create-admin-user" jest.setTimeout(50000) @@ -49,7 +49,7 @@ describe.skip("POST /admin/products/:id", () => { beforeEach(async () => { const manager = dbConnection.manager - await adminSeeder(dbConnection) + await createAdminUser(dbConnection, adminHeaders, appContainer) await createDefaultRuleTypes(appContainer) await manager.insert(Region, { diff --git a/packages/core/medusa-test-utils/src/medusa-test-runner-utils/use-db.js b/packages/core/medusa-test-utils/src/medusa-test-runner-utils/use-db.js index 78970c33e1..6e8824ec1e 100644 --- a/packages/core/medusa-test-utils/src/medusa-test-runner-utils/use-db.js +++ b/packages/core/medusa-test-utils/src/medusa-test-runner-utils/use-db.js @@ -1,6 +1,5 @@ const path = require("path") -const { getConfigFile } = require("medusa-core-utils") const { asValue } = require("awilix") const { isObject, @@ -33,44 +32,19 @@ module.exports = { require("@medusajs/medusa/dist/loaders/feature-flags").default const featureFlagRouter = featureFlagsLoader(configModule) - const modelsLoader = require("@medusajs/medusa/dist/loaders/models").default - const entities = modelsLoader({}, { register: false }) - - // get migrations with enabled featureflags - const migrationDir = path.resolve( - path.join( - cwd, - `../../`, - `node_modules`, - `@medusajs`, - `medusa`, - `dist`, - `migrations`, - `*.js` - ) - ) const { - getEnabledMigrations, getModuleSharedResources, } = require("@medusajs/medusa/dist/commands/utils/get-migrations") const { migrations: moduleMigrations, models: moduleModels } = getModuleSharedResources(configModule, featureFlagRouter) - const enabledMigrations = getEnabledMigrations([migrationDir], (flag) => - featureFlagRouter.isFeatureEnabled(flag) - ) - - const enabledEntities = entities.filter( - (e) => typeof e.isFeatureEnabled === "undefined" || e.isFeatureEnabled() - ) - const dbDataSource = new DataSource({ type: "postgres", url: dbUrl || configModule.projectConfig.database_url, - entities: enabledEntities.concat(moduleModels), - migrations: enabledMigrations.concat(moduleMigrations), + entities: moduleModels, + migrations: moduleMigrations, extra: database_extra ?? {}, //name: "integration-tests", schema: dbSchema, diff --git a/packages/medusa/package.json b/packages/medusa/package.json index beb28e1d21..ff770bfc78 100644 --- a/packages/medusa/package.json +++ b/packages/medusa/package.json @@ -38,7 +38,6 @@ "rimraf": "^5.0.1", "supertest": "^4.0.2", "ts-jest": "^25.5.1", - "typeorm": "^0.3.16", "typescript": "^4.4.4" }, "scripts": { @@ -49,8 +48,7 @@ "test": "jest --silent --bail --maxWorkers=50% --forceExit" }, "peerDependencies": { - "medusa-interfaces": "^1.3.7", - "typeorm": "^0.3.16" + "medusa-interfaces": "^1.3.7" }, "dependencies": { "@medusajs/core-flows": "^0.0.9", @@ -63,16 +61,12 @@ "awilix": "^8.0.0", "body-parser": "^1.19.0", "boxen": "^5.0.1", - "bullmq": "^5.4.2", "chokidar": "^3.4.2", - "class-transformer": "^0.5.1", - "class-validator": "^0.14.0", "compression": "^1.7.4", "connect-redis": "^5.0.0", "cookie-parser": "^1.4.6", "core-js": "^3.6.5", "cors": "^2.8.5", - "cross-spawn": "^7.0.3", "dotenv": "^16.4.5", "express": "^4.18.2", "express-session": "^1.17.3", @@ -80,7 +74,6 @@ "glob": "^7.1.6", "ioredis": "^5.2.5", "ioredis-mock": "8.4.0", - "iso8601-duration": "^1.3.0", "jsonwebtoken": "^9.0.0", "lodash": "^4.17.21", "medusa-core-utils": "^1.2.2", @@ -88,21 +81,16 @@ "morgan": "^1.9.1", "multer": "^1.4.5-lts.1", "node-schedule": "^2.1.1", - "papaparse": "5.3.2", "passport": "^0.6.0", "passport-custom": "^1.1.1", "passport-jwt": "^4.0.1", "passport-local": "^1.0.0", "pg": "^8.11.2", "qs": "^6.11.2", - "randomatic": "^3.1.1", "reflect-metadata": "^0.1.13", "regenerator-runtime": "^0.13.11", "request-ip": "^3.3.0", - "scrypt-kdf": "^2.0.1", - "ulid": "^2.3.0", "uuid": "^9.0.0", - "winston": "^3.8.2", "zod": "3.22.4" }, "gitHead": "cd1f5afa5aa8c0b15ea957008ee19f1d695cbd2e" diff --git a/packages/medusa/src/api-v2/admin/inventory-items/validators.ts b/packages/medusa/src/api-v2/admin/inventory-items/validators.ts index 92a01029e3..0419193b8a 100644 --- a/packages/medusa/src/api-v2/admin/inventory-items/validators.ts +++ b/packages/medusa/src/api-v2/admin/inventory-items/validators.ts @@ -4,7 +4,7 @@ import { createOperatorMap, createSelectParams, } from "../../utils/validators" -import { optionalBooleanMapper } from "../../../utils/validators/is-boolean" +import { OptionalBooleanValidator } from "../../utils/common-validators" export type AdminGetInventoryItemParamsType = z.infer< typeof AdminGetInventoryItemParams @@ -27,12 +27,7 @@ export const AdminGetInventoryItemsParams = createFindParams({ mid_code: z.union([z.string(), z.array(z.string())]).optional(), hs_code: z.union([z.string(), z.array(z.string())]).optional(), material: z.union([z.string(), z.array(z.string())]).optional(), - requires_shipping: z - .preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ) - .optional(), + requires_shipping: OptionalBooleanValidator, weight: createOperatorMap(z.number(), parseFloat).optional(), length: createOperatorMap(z.number(), parseFloat).optional(), height: createOperatorMap(z.number(), parseFloat).optional(), diff --git a/packages/medusa/src/api-v2/admin/product-categories/validators.ts b/packages/medusa/src/api-v2/admin/product-categories/validators.ts index fe7fccdb03..652a429d81 100644 --- a/packages/medusa/src/api-v2/admin/product-categories/validators.ts +++ b/packages/medusa/src/api-v2/admin/product-categories/validators.ts @@ -1,24 +1,18 @@ import { z } from "zod" -import { optionalBooleanMapper } from "../../../utils/validators/is-boolean" import { createFindParams, createOperatorMap, createSelectParams, } from "../../utils/validators" +import { OptionalBooleanValidator } from "../../utils/common-validators" export type AdminProductCategoryParamsType = z.infer< typeof AdminProductCategoryParams > export const AdminProductCategoryParams = createSelectParams().merge( z.object({ - include_ancestors_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - include_descendants_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), + include_ancestors_tree: OptionalBooleanValidator, + include_descendants_tree: OptionalBooleanValidator, }) ) @@ -35,22 +29,10 @@ export const AdminProductCategoriesParams = createFindParams({ description: z.union([z.string(), z.array(z.string())]).optional(), handle: z.union([z.string(), z.array(z.string())]).optional(), parent_category_id: z.union([z.string(), z.array(z.string())]).optional(), - include_ancestors_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - include_descendants_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - is_internal: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - is_active: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), + include_ancestors_tree: OptionalBooleanValidator, + include_descendants_tree: OptionalBooleanValidator, + is_internal: OptionalBooleanValidator, + is_active: OptionalBooleanValidator, created_at: createOperatorMap().optional(), updated_at: createOperatorMap().optional(), deleted_at: createOperatorMap().optional(), diff --git a/packages/medusa/src/api-v2/store/product-categories/validators.ts b/packages/medusa/src/api-v2/store/product-categories/validators.ts index bb8283774f..d3a8cf0a57 100644 --- a/packages/medusa/src/api-v2/store/product-categories/validators.ts +++ b/packages/medusa/src/api-v2/store/product-categories/validators.ts @@ -1,24 +1,18 @@ import { z } from "zod" -import { optionalBooleanMapper } from "../../../utils/validators/is-boolean" import { createFindParams, createOperatorMap, createSelectParams, } from "../../utils/validators" +import { OptionalBooleanValidator } from "../../utils/common-validators" export type StoreProductCategoryParamsType = z.infer< typeof StoreProductCategoryParams > export const StoreProductCategoryParams = createSelectParams().merge( z.object({ - include_ancestors_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - include_descendants_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), + include_ancestors_tree: OptionalBooleanValidator, + include_descendants_tree: OptionalBooleanValidator, }) ) @@ -35,14 +29,8 @@ export const StoreProductCategoriesParams = createFindParams({ description: z.union([z.string(), z.array(z.string())]).optional(), handle: z.union([z.string(), z.array(z.string())]).optional(), parent_category_id: z.union([z.string(), z.array(z.string())]).optional(), - include_ancestors_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), - include_descendants_tree: z.preprocess( - (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), - z.boolean().optional() - ), + include_ancestors_tree: OptionalBooleanValidator, + include_descendants_tree: OptionalBooleanValidator, created_at: createOperatorMap().optional(), updated_at: createOperatorMap().optional(), deleted_at: createOperatorMap().optional(), diff --git a/packages/medusa/src/api-v2/utils/common-validators/common.ts b/packages/medusa/src/api-v2/utils/common-validators/common.ts index 7018683d2d..f8506390e9 100644 --- a/packages/medusa/src/api-v2/utils/common-validators/common.ts +++ b/packages/medusa/src/api-v2/utils/common-validators/common.ts @@ -1,5 +1,4 @@ import { z } from "zod" -import { optionalBooleanMapper } from "../../../utils/validators/is-boolean" export const AddressPayload = z .object({ @@ -26,6 +25,13 @@ export const BigNumberInput = z.union([ }), ]) +const optionalBooleanMapper = new Map([ + ["undefined", undefined], + ["null", null], + ["true", true], + ["false", false], +]) + export const OptionalBooleanValidator = z.preprocess( (val: any) => optionalBooleanMapper.get(val?.toLowerCase()), z.boolean().optional() diff --git a/packages/medusa/src/commands/utils/get-migrations.js b/packages/medusa/src/commands/utils/get-migrations.js index ee9898f2f1..34d1c11648 100644 --- a/packages/medusa/src/commands/utils/get-migrations.js +++ b/packages/medusa/src/commands/utils/get-migrations.js @@ -1,98 +1,6 @@ import { MedusaModule, registerMedusaModule } from "@medusajs/modules-sdk" -import fs from "fs" -import { sync as existsSync } from "fs-exists-cached" import glob from "glob" -import { isString } from "lodash" -import { - createRequireFromPath, - getConfigFile, - isDefined, -} from "medusa-core-utils" -import path from "path" -import { handleConfigError } from "../../loaders/config" -import { MEDUSA_PROJECT_NAME } from "../../loaders/plugins" - -function createFileContentHash(path, files) { - return path + files -} - -// TODO: Create unique id for each plugin -function createPluginId(name) { - return name -} - -/** - * Finds the correct path for the plugin. If it is a local plugin it will be - * found in the plugins folder. Otherwise we will look for the plugin in the - * installed npm packages. - * @param {string} pluginName - the name of the plugin to find. Should match - * the name of the folder where the plugin is contained. - * @return {object} the plugin details - */ -function resolvePlugin(pluginName) { - // Only find plugins when we're not given an absolute path - if (!existsSync(pluginName)) { - // Find the plugin in the local plugins folder - const resolvedPath = path.resolve(`./plugins/${pluginName}`) - - if (existsSync(resolvedPath)) { - if (existsSync(`${resolvedPath}/package.json`)) { - const packageJSON = JSON.parse( - fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) - ) - const name = packageJSON.name || pluginName - // warnOnIncompatiblePeerDependency(name, packageJSON) - - return { - resolve: resolvedPath, - name, - id: createPluginId(name), - options: {}, - version: - packageJSON.version || createFileContentHash(resolvedPath, `**`), - } - } else { - // Make package.json a requirement for local plugins too - throw new Error(`Plugin ${pluginName} requires a package.json file`) - } - } - } - - const rootDir = path.resolve(".") - - /** - * Here we have an absolute path to an internal plugin, or a name of a module - * which should be located in node_modules. - */ - try { - const requireSource = - rootDir !== null - ? createRequireFromPath(`${rootDir}/:internal:`) - : require - - // If the path is absolute, resolve the directory of the internal plugin, - // otherwise resolve the directory containing the package.json - const resolvedPath = path.dirname( - requireSource.resolve(`${pluginName}/package.json`) - ) - - const packageJSON = JSON.parse( - fs.readFileSync(`${resolvedPath}/package.json`, `utf-8`) - ) - // warnOnIncompatiblePeerDependency(packageJSON.name, packageJSON) - - return { - resolve: resolvedPath, - id: createPluginId(packageJSON.name), - name: packageJSON.name, - version: packageJSON.version, - } - } catch (err) { - throw new Error( - `Unable to find plugin "${pluginName}". Perhaps you need to install its package?` - ) - } -} +import { isDefined } from "medusa-core-utils" export function getInternalModules(configModule) { const modules = [] @@ -129,65 +37,6 @@ export function getInternalModules(configModule) { return modules } -export default (directory, featureFlagRouter) => { - const { configModule, error } = getConfigFile(directory, `medusa-config`) - - if (error) { - handleConfigError(error) - } - - const { plugins } = configModule - - const resolved = plugins.map((plugin) => { - if (isString(plugin)) { - return resolvePlugin(plugin) - } - - const details = resolvePlugin(plugin.resolve) - details.options = plugin.options - - return details - }) - - // Resolve user's project as a plugin for loading purposes - resolved.push({ - resolve: `${directory}/dist`, - name: MEDUSA_PROJECT_NAME, - id: createPluginId(MEDUSA_PROJECT_NAME), - options: {}, - version: createFileContentHash(process.cwd(), `**`), - }) - - const migrationDirs = [] - const corePackageMigrations = path.resolve( - path.join(__dirname, "..", "..", "migrations") - ) - - migrationDirs.push(path.join(corePackageMigrations, "*.js")) - - for (const p of resolved) { - const exists = existsSync(`${p.resolve}/migrations`) - if (exists) { - migrationDirs.push(`${p.resolve}/migrations/*.js`) - continue - } - const distExists = existsSync(`${p.resolve}/dist/migrations`) - if (distExists) { - migrationDirs.push(`${p.resolve}/dist/migrations/*.js`) - } - } - - const isFeatureFlagEnabled = (flag) => - featureFlagRouter.isFeatureEnabled(flag) - - const coreMigrations = getEnabledMigrations( - migrationDirs, - isFeatureFlagEnabled - ) - - return { coreMigrations } -} - export const getEnabledMigrations = (migrationDirs, isFlagEnabled) => { const allMigrations = migrationDirs.flatMap((dir) => { return glob.sync(dir) diff --git a/packages/medusa/src/helpers/test-request.js b/packages/medusa/src/helpers/test-request.js deleted file mode 100644 index df87929a0b..0000000000 --- a/packages/medusa/src/helpers/test-request.js +++ /dev/null @@ -1,209 +0,0 @@ -import { - moduleHelper, - moduleLoader, - ModulesDefinition, - registerMedusaModule, -} from "@medusajs/modules-sdk" -import { asValue, createContainer } from "awilix" -import express from "express" -import jwt from "jsonwebtoken" -import { MockManager } from "medusa-test-utils" -import querystring from "querystring" -import "reflect-metadata" -import supertest from "supertest" -import apiLoader from "../loaders/api" -import featureFlagLoader, { featureFlagRouter } from "../loaders/feature-flags" -import models from "../loaders/models" -import passportLoader from "../loaders/passport" -import repositories from "../loaders/repositories" -import servicesLoader from "../loaders/services" -import strategiesLoader from "../loaders/strategies" - -const adminSessionOpts = { - cookieName: "session", - secret: "test", -} -export { adminSessionOpts, clientSessionOpts } - -const clientSessionOpts = { - cookieName: "session", - secret: "test", -} - -const moduleResolutions = {} -Object.entries(ModulesDefinition).forEach(([moduleKey, module]) => { - moduleResolutions[moduleKey] = registerMedusaModule( - moduleKey, - module.defaultModuleDeclaration, - undefined, - module - )[moduleKey] -}) - -const config = { - projectConfig: { - jwt_secret: "supersecret", - cookie_secret: "superSecret", - admin_cors: "", - store_cors: "", - }, -} - -const testApp = express() - -function asArray(resolvers) { - return { - resolve: (container) => - resolvers.map((resolver) => container.build(resolver)), - } -} - -const container = createContainer() - -// TODO: remove once the util is merged in master -container.registerAdd = function (name, registration) { - const storeKey = name + "_STORE" - - if (this.registrations[storeKey] === undefined) { - this.register(storeKey, asValue([])) - } - const store = this.resolve(storeKey) - - if (this.registrations[name] === undefined) { - this.register(name, asArray(store)) - } - store.unshift(registration) - - return this -}.bind(container) - -container.register("featureFlagRouter", asValue(featureFlagRouter)) -container.register("modulesHelper", asValue(moduleHelper)) -container.register("configModule", asValue(config)) -container.register({ - logger: asValue({ - error: () => {}, - }), - manager: asValue(MockManager), -}) - -testApp.set("trust proxy", 1) -testApp.use((req, res, next) => { - req.session = {} - const data = req.get("Cookie") - if (data) { - req.session = { - ...req.session, - ...JSON.parse(data), - } - } - next() -}) - -let supertestRequest -let resolveIsInit -const isInit = new Promise((resolve) => { - resolveIsInit = resolve -}) - -async function init() { - featureFlagLoader(config) - models({ container, configModule: config, isTest: true }) - repositories({ container, isTest: true }) - servicesLoader({ container, configModule: config }) - strategiesLoader({ container, configModule: config }) - await passportLoader({ app: testApp, container, configModule: config }) - await moduleLoader({ container, moduleResolutions }) - - testApp.use((req, res, next) => { - req.scope = container.createScope() - next() - }) - - await apiLoader({ container, app: testApp, configModule: config }) - - supertestRequest = supertest(testApp) - resolveIsInit(true) -} - -init() - -export async function request(method, url, opts = {}) { - await isInit - - const { payload, query, headers = {}, flags = [] } = opts - - flags.forEach((flag) => { - featureFlagRouter.setFlag(flag.key, true) - }) - - const queryParams = query && querystring.stringify(query) - const req = supertestRequest[method.toLowerCase()]( - `${url}${queryParams ? "?" + queryParams : ""}` - ) - headers.Cookie = headers.Cookie || "" - if (opts.adminSession) { - const token = jwt.sign( - { - user_id: opts.adminSession.userId || opts.adminSession.jwt?.userId, - domain: "admin", - }, - config.projectConfig.jwt_secret - ) - - headers.Authorization = `Bearer ${token}` - } - if (opts.clientSession) { - const token = jwt.sign( - { - customer_id: - opts.clientSession.customer_id || opts.clientSession.jwt?.customer_id, - domain: "store", - }, - config.projectConfig.jwt_secret - ) - - headers.Authorization = `Bearer ${token}` - } - - for (const name in headers) { - if ({}.hasOwnProperty.call(headers, name)) { - req.set(name, headers[name]) - } - } - - if (payload && !req.get("content-type")) { - req.set("Content-Type", "application/json") - } - - if (!req.get("accept")) { - req.set("Accept", "application/json") - } - - req.set("Host", "localhost") - - let res - try { - res = await req.send(JSON.stringify(payload)) - } catch (e) { - if (e.response) { - res = e.response - } else { - throw e - } - } - - // let c = - // res.headers["set-cookie"] && cookie.parse(res.headers["set-cookie"][0]) - // res.adminSession = - // c && - // c[adminSessionOpts.cookieName] && - // sessions.util.decode(adminSessionOpts, c[adminSessionOpts.cookieName]) - // .content - // res.clientSession = - // c && - // c[clientSessionOpts.cookieName] && - // sessions.util.decode(clientSessionOpts, c[clientSessionOpts.cookieName]) - // .content - return res -} diff --git a/packages/medusa/src/index.js b/packages/medusa/src/index.js index 1b3ccf1eed..47ea6d70f7 100644 --- a/packages/medusa/src/index.js +++ b/packages/medusa/src/index.js @@ -1,12 +1,6 @@ -export * from "./interfaces" -export * from "./models" -export * from "./modules-config" -export * from "./services" -export * from "./types/batch-job" export * from "./types/common" export * from "./types/global" export * from "./types/middlewares" export * from "./types/routing" -export * from "./types/scheduled-jobs" export * from "./types/subscribers" export * from "./utils" diff --git a/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts b/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts deleted file mode 100644 index 0fdffc9fd3..0000000000 --- a/packages/medusa/src/interfaces/__tests__/transaction-base-service.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { MockManager } from "medusa-test-utils" -import { TransactionBaseService } from "../transaction-base-service" - -describe("TransactionBaseService", () => { - it("should cloned the child class withTransaction", () => { - class Child extends TransactionBaseService { - constructor(protected readonly container) { - super(container); - this.container = container - } - - message() { - return `child class message method called with title ${this.container.title}` - } - - getTransactionManager() { - return this.transactionManager_ - } - } - - const child = new Child({ title: 'title' }) - - expect(child.message()).toBe(`child class message method called with title title`) - expect(child.getTransactionManager()).toBeFalsy() - - const fakeManager = MockManager - fakeManager.testProp = 'testProp' - const child2 = child.withTransaction(fakeManager) - - expect(child2.message()).toBe(`child class message method called with title title`) - expect(child2.getTransactionManager()).toBeTruthy() - expect((child2.getTransactionManager() as any)?.testProp).toBe('testProp') - }) -}) \ No newline at end of file diff --git a/packages/medusa/src/interfaces/index.ts b/packages/medusa/src/interfaces/index.ts deleted file mode 100644 index 1351f8d00d..0000000000 --- a/packages/medusa/src/interfaces/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./models/base-entity" -export * from "./models/soft-deletable-entity" -export * from "./transaction-base-service" diff --git a/packages/medusa/src/interfaces/models/base-entity.ts b/packages/medusa/src/interfaces/models/base-entity.ts deleted file mode 100644 index 423aabd9b8..0000000000 --- a/packages/medusa/src/interfaces/models/base-entity.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - CreateDateColumn, - PrimaryColumn, - UpdateDateColumn, -} from "typeorm" -import { resolveDbType } from "../../utils/db-aware-column" - -/** - * Base abstract entity for all entities - */ -export abstract class BaseEntity { - @PrimaryColumn() - id: string - - @CreateDateColumn({ type: resolveDbType("timestamptz") }) - created_at: Date - - @UpdateDateColumn({ type: resolveDbType("timestamptz") }) - updated_at: Date -} diff --git a/packages/medusa/src/interfaces/models/soft-deletable-entity.ts b/packages/medusa/src/interfaces/models/soft-deletable-entity.ts deleted file mode 100644 index 33e9f8ad38..0000000000 --- a/packages/medusa/src/interfaces/models/soft-deletable-entity.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { BaseEntity } from "./base-entity" -import { DeleteDateColumn } from "typeorm" -import { resolveDbType } from "../../utils/db-aware-column" - -export abstract class SoftDeletableEntity extends BaseEntity { - @DeleteDateColumn({ type: resolveDbType("timestamptz") }) - deleted_at: Date | null -} diff --git a/packages/medusa/src/interfaces/transaction-base-service.ts b/packages/medusa/src/interfaces/transaction-base-service.ts deleted file mode 100644 index 3130eddd53..0000000000 --- a/packages/medusa/src/interfaces/transaction-base-service.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { EntityManager } from "typeorm" -import { IsolationLevel } from "typeorm/driver/types/IsolationLevel" - -export abstract class TransactionBaseService { - protected manager_: EntityManager - protected transactionManager_: EntityManager | undefined - - protected get activeManager_(): EntityManager { - return this.transactionManager_ ?? this.manager_ - } - - protected constructor( - protected readonly __container__: any, - protected readonly __configModule__?: Record, - protected readonly __moduleDeclaration__?: Record - ) { - this.manager_ = __container__?.manager - } - - withTransaction(transactionManager?: EntityManager): this { - if (!transactionManager) { - return this - } - - const cloned = new (this.constructor as any)( - this.__container__, - this.__configModule__, - this.__moduleDeclaration__ - ) - - cloned.manager_ = transactionManager - cloned.transactionManager_ = transactionManager - - return cloned - } - - protected shouldRetryTransaction_( - err: { code: string } | Record - ): boolean { - if (!(err as { code: string })?.code) { - return false - } - const code = (err as { code: string })?.code - return code === "40001" || code === "40P01" - } - - /** - * Wraps some work within a transactional block. If the service already has - * a transaction manager attached this will be reused, otherwise a new - * transaction manager is created. - * @param work - the transactional work to be done - * @param isolationOrErrorHandler - the isolation level to be used for the work. - * @param maybeErrorHandlerOrDontFail Potential error handler - * @return the result of the transactional work - */ - protected async atomicPhase_( - work: (transactionManager: EntityManager) => Promise, - isolationOrErrorHandler?: - | IsolationLevel - | ((error: TError) => Promise), - maybeErrorHandlerOrDontFail?: ( - error: TError - ) => Promise - ): Promise { - let errorHandler = maybeErrorHandlerOrDontFail - let isolation: - | IsolationLevel - | ((error: TError) => Promise) - | undefined - | null = isolationOrErrorHandler - let dontFail = false - if (typeof isolationOrErrorHandler === "function") { - isolation = null - errorHandler = isolationOrErrorHandler - dontFail = !!maybeErrorHandlerOrDontFail - } - - if (this.transactionManager_) { - const doWork = async (m: EntityManager): Promise => { - this.manager_ = m - this.transactionManager_ = m - try { - return await work(m) - } catch (error) { - if (errorHandler) { - const queryRunner = this.transactionManager_.queryRunner - if (queryRunner && queryRunner.isTransactionActive) { - await queryRunner.rollbackTransaction() - } - - await errorHandler(error) - } - throw error - } - } - - return await doWork(this.transactionManager_) - } else { - const temp = this.manager_ - const doWork = async (m: EntityManager): Promise => { - this.manager_ = m - this.transactionManager_ = m - try { - const result = await work(m) - this.manager_ = temp - this.transactionManager_ = undefined - return result - } catch (error) { - this.manager_ = temp - this.transactionManager_ = undefined - throw error - } - } - - if (isolation && this.manager_) { - let result - try { - result = await this.manager_.transaction( - isolation as IsolationLevel, - async (m) => doWork(m) - ) - return result - } catch (error) { - if (this.shouldRetryTransaction_(error)) { - return this.manager_.transaction( - isolation as IsolationLevel, - async (m): Promise => doWork(m) - ) - } else { - if (errorHandler) { - await errorHandler(error) - } - throw error - } - } - } - - try { - return await this.manager_.transaction(async (m) => doWork(m)) - } catch (error) { - if (errorHandler) { - const result = await errorHandler(error) - if (dontFail) { - return result as TResult - } - } - - throw error - } - } - } -} diff --git a/packages/medusa/src/loaders/__tests__/models.spec.ts b/packages/medusa/src/loaders/__tests__/models.spec.ts deleted file mode 100644 index 045b0cc8ce..0000000000 --- a/packages/medusa/src/loaders/__tests__/models.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { asValue } from "awilix" -import { createMedusaContainer } from "medusa-core-utils" -import path from "path" - -import modelsLoader from "../models" - -describe.skip("models loader", () => { - const container = createMedusaContainer() - container.register("db_entities", asValue([])) - let models - let error - - beforeAll(async () => { - try { - models = await modelsLoader({ - container, - isTest: true, - coreTestPathGlob: "../models/{product,product-variant}.ts", - rootDirectory: path.join(__dirname, "__fixtures__/customizations"), - extensionPathGlob: "models/{product,product-variant}.ts", - }) - } catch (e) { - error = e - } - }) - - it("error should be falsy & register 2 models", () => { - expect(error).toBeFalsy() - expect(models).toHaveLength(2) - }) - - it("ensure that the product model is an extended model", () => { - const productModel = models.find((model) => model.name === "Product") - - expect(new productModel().custom_attribute).toEqual("test") - }) - - it("ensure that the extended product model is registered in db_entities", () => { - const entities = container.resolve("db_entities_STORE") - const productModelResolver = entities.find( - (entity) => entity.resolve().name === "Product" - ) - const productModel = productModelResolver.resolve() - - expect(new productModel().custom_attribute).toEqual("test") - }) -}) diff --git a/packages/medusa/src/loaders/__tests__/plugins.spec.ts b/packages/medusa/src/loaders/__tests__/plugins.spec.ts deleted file mode 100644 index 4d7b93972d..0000000000 --- a/packages/medusa/src/loaders/__tests__/plugins.spec.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { - asValue, - AwilixContainer, - ClassOrFunctionReturning, - Resolver, -} from "awilix" -import { mkdirSync, rmSync, writeFileSync } from "fs" -import { createMedusaContainer } from "medusa-core-utils" -import { resolve } from "path" -import { DataSource, EntityManager } from "typeorm" -import Logger from "../logger" -import { - MEDUSA_PROJECT_NAME, - registerServices, - registerStrategies, -} from "../plugins" - -// ***** TEMPLATES ***** -const buildServiceTemplate = (name: string): string => { - return ` - import { BaseService } from "medusa-interfaces" - export default class ${name}Service extends BaseService {} - ` -} -const buildTransactionBaseServiceServiceTemplate = (name: string) => { - return ` - import { TransactionBaseService } from "${resolve( - __dirname, - "../../interfaces" - )}" - export default class ${name}Service extends TransactionBaseService {} - ` -} - -/*const buildBatchJobStrategyTemplate = (name: string, type: string): string => { - return ` - import { AbstractBatchJobStrategy } from "../../../../interfaces/batch-job-strategy" - - class ${name}BatchStrategy extends AbstractBatchJobStrategy { - static identifier = '${name}-identifier'; - static batchType = '${type}'; - - manager_ - transactionManager_ - - validateContext(context) { - throw new Error("Method not implemented.") - } - processJob(batchJobId) { - throw new Error("Method not implemented.") - } - completeJob(batchJobId) { - throw new Error("Method not implemented.") - } - validateFile(fileLocation) { - throw new Error("Method not implemented.") - } - async buildTemplate() { - throw new Error("Method not implemented.") - } - } - - export default ${name}BatchStrategy - ` -} - -const buildPriceSelectionStrategyTemplate = (name: string): string => { - return ` - import { AbstractPriceSelectionStrategy } from "../../../../interfaces/price-selection-strategy" - - class ${name}PriceSelectionStrategy extends AbstractPriceSelectionStrategy { - withTransaction() { - throw new Error("Method not implemented."); - } - calculateVariantPrice(variant_id, context) { - throw new Error("Method not implemented."); - } - } - - export default ${name}PriceSelectionStrategy - ` -} - -const buildTaxCalcStrategyTemplate = (name: string): string => { - return ` - import { AbstractTaxCalculationStrategy } from "../../../../interfaces/tax-calculation-strategy" - class ${name}TaxCalculationStrategy extends AbstractTaxCalculationStrategy { - calculate(items, taxLines, calculationContext) { - throw new Error("Method not implemented.") - } - } - - export default ${name}TaxCalculationStrategy - ` -}*/ - -// ***** UTILS ***** - -const distTestTargetDirectorPath = resolve(__dirname, "__pluginsLoaderTest__") - -const getFolderTestTargetDirectoryPath = (folderName: string): string => { - return resolve(distTestTargetDirectorPath, folderName) -} - -function asArray( - resolvers: (ClassOrFunctionReturning | Resolver)[] -): { resolve: (container: AwilixContainer) => unknown[] } { - return { - resolve: (container: AwilixContainer): unknown[] => - resolvers.map((resolver) => container.build(resolver)), - } -} - -// ***** TESTS ***** - -describe.skip("plugins loader", () => { - const container = createMedusaContainer() - - container.register("logger", asValue(Logger)) - container.register("manager", asValue(new EntityManager({} as DataSource))) - - const pluginsDetails = { - resolve: resolve(__dirname, "__pluginsLoaderTest__"), - name: MEDUSA_PROJECT_NAME, - id: "fakeId", - options: {}, - version: '"fakeVersion', - } - let err - - afterAll(() => { - rmSync(distTestTargetDirectorPath, { recursive: true, force: true }) - jest.clearAllMocks() - }) - - describe("registerStrategies", function () { - beforeAll(async () => { - mkdirSync(getFolderTestTargetDirectoryPath("strategies"), { - mode: "777", - recursive: true, - }) - /*writeFileSync( - resolve( - getFolderTestTargetDirectoryPath("strategies"), - "test-batch-1.js" - ), - buildBatchJobStrategyTemplate("testBatch1", "type-1") - ) - writeFileSync( - resolve( - getFolderTestTargetDirectoryPath("strategies"), - "test-price-selection.js" - ), - buildPriceSelectionStrategyTemplate("test") - ) - writeFileSync( - resolve( - getFolderTestTargetDirectoryPath("strategies"), - "test-batch-2.js" - ), - buildBatchJobStrategyTemplate("testBatch2", "type-1") - ) - writeFileSync( - resolve( - getFolderTestTargetDirectoryPath("strategies"), - "test-batch-3.js" - ), - buildBatchJobStrategyTemplate("testBatch3", "type-2") - ) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("strategies"), "test-tax.js"), - buildTaxCalcStrategyTemplate("test") - )*/ - - try { - await registerStrategies(pluginsDetails, container) - } catch (e) { - err = e - } - }) - - afterAll(() => { - jest.clearAllMocks() - }) - - it("err should be falsy", () => { - expect(err).toBeFalsy() - }) - - it.skip("registers price selection strategy", () => { - const priceSelectionStrategy = container.resolve( - "priceSelectionStrategy" - ) as (...args: unknown[]) => any - - expect(priceSelectionStrategy).toBeTruthy() - expect(priceSelectionStrategy.constructor.name).toBe( - "testPriceSelectionStrategy" - ) - }) - - it.skip("registers tax calculation strategy", () => { - const taxCalculationStrategy = container.resolve( - "taxCalculationStrategy" - ) as (...args: unknown[]) => any - - expect(taxCalculationStrategy).toBeTruthy() - expect(taxCalculationStrategy.constructor.name).toBe( - "testTaxCalculationStrategy" - ) - }) - - it.skip("registers batch job strategies as single array", () => { - const batchJobStrategies = container.resolve("batchJobStrategies") as ( - ...args: unknown[] - ) => any - - expect(batchJobStrategies).toBeTruthy() - expect(Array.isArray(batchJobStrategies)).toBeTruthy() - expect(batchJobStrategies.length).toBe(3) - }) - - it.skip("registers batch job strategies by type and only keep the last", () => { - const batchJobStrategy = container.resolve("batchType_type-1") as ( - ...args: unknown[] - ) => any - - expect(batchJobStrategy).toBeTruthy() - expect(batchJobStrategy.constructor.name).toBe("testBatch2BatchStrategy") - expect((batchJobStrategy.constructor as any).batchType).toBe("type-1") - expect((batchJobStrategy.constructor as any).identifier).toBe( - "testBatch2-identifier" - ) - }) - - it.skip("registers batch job strategies by identifier", () => { - const batchJobStrategy = container.resolve( - "batch_testBatch3-identifier" - ) as (...args: unknown[]) => any - - expect(batchJobStrategy).toBeTruthy() - expect(Array.isArray(batchJobStrategy)).toBeFalsy() - expect(batchJobStrategy.constructor.name).toBe("testBatch3BatchStrategy") - }) - }) - - describe("registerServices", function () { - beforeAll(() => { - container.register("logger", asValue(Logger)) - mkdirSync(getFolderTestTargetDirectoryPath("services"), { - mode: "777", - recursive: true, - }) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("services"), "test.js"), - buildServiceTemplate("test") - ) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("services"), "test2.js"), - buildServiceTemplate("test2") - ) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("services"), "test3.js"), - buildTransactionBaseServiceServiceTemplate("test3") - ) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("services"), "test2.js.map"), - "map:file" - ) - writeFileSync( - resolve(getFolderTestTargetDirectoryPath("services"), "test2.d.ts"), - "export interface Test {}" - ) - }) - - afterAll(() => { - jest.clearAllMocks() - }) - - it("should load the services from the services directory but only js files", async () => { - let err - try { - await registerServices(pluginsDetails, container) - } catch (e) { - err = e - } - - expect(err).toBeFalsy() - - const testService: (...args: unknown[]) => any = - container.resolve("testService") - const test2Service: (...args: unknown[]) => any = - container.resolve("test2Service") - const test3Service: (...args: unknown[]) => any = - container.resolve("test3Service") - - expect(testService).toBeTruthy() - expect(testService.constructor.name).toBe("testService") - expect(test2Service).toBeTruthy() - expect(test2Service.constructor.name).toBe("test2Service") - expect(test3Service).toBeTruthy() - expect(test3Service.constructor.name).toBe("test3Service") - }) - }) -}) diff --git a/packages/medusa/src/loaders/__tests__/register-plugin-models.spec.ts b/packages/medusa/src/loaders/__tests__/register-plugin-models.spec.ts deleted file mode 100644 index 382a41c437..0000000000 --- a/packages/medusa/src/loaders/__tests__/register-plugin-models.spec.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { asValue } from "awilix" -import { createMedusaContainer } from "medusa-core-utils" -import path from "path" - -import { registerPluginModels } from "../plugins" -import configModule from './__fixtures__/customizations/medusa-config' - -describe.skip("plugin models loader", () => { - const container = createMedusaContainer() - container.register("db_entities", asValue([])) - - let models - let error - - beforeAll(async () => { - try { - await registerPluginModels({ - configModule: configModule, - container, - rootDirectory: path.join(__dirname, '__fixtures__/customizations'), - extensionDirectoryPath: './', - pathGlob: "/models/*.ts", - }) - } catch (e) { - error = e - } - }) - - it("ensure that the product model is registered from the user's respository", () => { - const entities = container.resolve("db_entities_STORE") - const productModelResolver = entities.find(entity => entity.resolve().name === 'Product') - const productModel = productModelResolver.resolve() - - expect((new productModel()).custom_attribute).toEqual("test") - }) -}) diff --git a/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-hour.ts b/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-hour.ts deleted file mode 100644 index 67211910fa..0000000000 --- a/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-hour.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ScheduledJobArgs } from "../../../../../types/scheduled-jobs" - -export default async function ({ container, pluginOptions }: ScheduledJobArgs) { - // noop - return {} -} - -export const config = { - name: "every-hour", - schedule: "0 * * * *", -} diff --git a/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-minute.ts b/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-minute.ts deleted file mode 100644 index 5f0958f5b0..0000000000 --- a/packages/medusa/src/loaders/helpers/jobs/__fixtures__/jobs/every-minute.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ScheduledJobArgs } from "../../../../../types/scheduled-jobs" - -export default async function ({ container, pluginOptions }: ScheduledJobArgs) { - // noop - return {} -} - -export const config = { - name: "every-minute", - schedule: "* * * * *", -} diff --git a/packages/medusa/src/loaders/helpers/jobs/__mocks__/index.ts b/packages/medusa/src/loaders/helpers/jobs/__mocks__/index.ts deleted file mode 100644 index 23565d82ca..0000000000 --- a/packages/medusa/src/loaders/helpers/jobs/__mocks__/index.ts +++ /dev/null @@ -1,16 +0,0 @@ -export const jobSchedulerServiceMock = { - create: jest.fn().mockImplementation((...args) => { - return Promise.resolve(args) - }), -} - -export const containerMock = { - // mock .resolve method so if its called with "jobSchedulerService" it returns the mock - resolve: jest.fn().mockImplementation((name: string) => { - if (name === "jobSchedulerService") { - return jobSchedulerServiceMock - } else { - return {} - } - }), -} diff --git a/packages/medusa/src/loaders/helpers/jobs/__tests__/index.spec.ts b/packages/medusa/src/loaders/helpers/jobs/__tests__/index.spec.ts deleted file mode 100644 index 33304a08d8..0000000000 --- a/packages/medusa/src/loaders/helpers/jobs/__tests__/index.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { MedusaContainer } from "@medusajs/types" -import { join } from "path" -import { containerMock, jobSchedulerServiceMock } from "../__mocks__" -import ScheduledJobsLoader from "../index" - -describe("ScheduledJobsLoader", () => { - const rootDir = join(__dirname, "../__fixtures__", "jobs") - - const pluginOptions = { - important_data: { - enabled: true, - }, - } - - beforeAll(async () => { - jest.clearAllMocks() - - await new ScheduledJobsLoader( - rootDir, - containerMock as unknown as MedusaContainer, - pluginOptions - ).load() - }) - - it("should register every job in '/jobs'", async () => { - // As '/jobs' contains 2 jobs, we expect the create method to be called twice - expect(jobSchedulerServiceMock.create).toHaveBeenCalledTimes(2) - }) - - it("should register every job with the correct props", async () => { - // Registering every-hour.ts - expect(jobSchedulerServiceMock.create).toHaveBeenCalledWith( - "every-hour", - undefined, - "0 * * * *", - expect.any(Function), - { keepExisting: false } - ) - - // Registering every-minute.ts - expect(jobSchedulerServiceMock.create).toHaveBeenCalledWith( - "every-minute", - undefined, - "* * * * *", - expect.any(Function), - { keepExisting: false } - ) - }) -}) diff --git a/packages/medusa/src/loaders/helpers/jobs/index.ts b/packages/medusa/src/loaders/helpers/jobs/index.ts deleted file mode 100644 index b49cf7bf7b..0000000000 --- a/packages/medusa/src/loaders/helpers/jobs/index.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { MedusaContainer } from "@medusajs/types" -import { readdir } from "fs/promises" -import { join } from "path" -import JobSchedulerService from "../../../services/job-scheduler" -import { - ScheduledJobArgs, - ScheduledJobConfig, -} from "../../../types/scheduled-jobs" -import logger from "../../logger" - -type ScheduledJobHandler = (args: ScheduledJobArgs) => Promise - -type ScheduledJobModule = { - config: ScheduledJobConfig - handler: ScheduledJobHandler -} - -export default class ScheduledJobsLoader { - protected container_: MedusaContainer - protected pluginOptions_: Record - protected rootDir_: string - protected excludes: RegExp[] = [ - /\.DS_Store/, - /(\.ts\.map|\.js\.map|\.d\.ts)/, - /^_[^/\\]*(\.[^/\\]+)?$/, - ] - - protected jobDescriptors_: Map = new Map() - - constructor( - rootDir: string, - container: MedusaContainer, - options: Record = {} - ) { - this.rootDir_ = rootDir - this.pluginOptions_ = options - this.container_ = container - } - - private validateJob( - job: any, - path: string - ): job is { - default: ScheduledJobHandler - config: ScheduledJobConfig - } { - const handler = job.default - - if (!handler || typeof handler !== "function") { - logger.warn(`The job in ${path} is not a function.`) - return false - } - - const config = job.config - - if (!config) { - logger.warn(`The job in ${path} is missing a config.`) - return false - } - - if (!config.schedule) { - logger.warn(`The job in ${path} is missing a schedule.`) - return false - } - - if (!config.name) { - logger.warn(`The job in ${path} is missing a name.`) - return false - } - - if (config.data && typeof config.data !== "object") { - logger.warn(`The job data in ${path} is not an object.`) - return false - } - - return true - } - - private async createDescriptor(absolutePath: string, entry: string) { - return await import(absolutePath).then((module_) => { - const isValid = this.validateJob(module_, absolutePath) - - if (!isValid) { - return - } - - this.jobDescriptors_.set(absolutePath, { - config: module_.config, - handler: module_.default, - }) - }) - } - - private async createMap(dirPath: string) { - await Promise.all( - await readdir(dirPath, { withFileTypes: true }).then(async (entries) => { - return entries - .filter((entry) => { - if ( - this.excludes.length && - this.excludes.some((exclude) => exclude.test(entry.name)) - ) { - return false - } - - return true - }) - .map(async (entry) => { - const fullPath = join(dirPath, entry.name) - - if (entry.isDirectory()) { - return this.createMap(fullPath) - } - - return await this.createDescriptor(fullPath, entry.name) - }) - }) - ) - } - - private async createScheduledJobs() { - const jobs = Array.from(this.jobDescriptors_.values()) - - if (!jobs.length) { - return - } - - const jobSchedulerService: JobSchedulerService = this.container_.resolve( - "jobSchedulerService" - ) - - for (const job of jobs) { - try { - const { name, data, schedule } = job.config - - const handler = async () => { - await job.handler({ - container: this.container_, - data, - pluginOptions: this.pluginOptions_, - }) - } - - await jobSchedulerService.create(name, data, schedule, handler, { - keepExisting: false, // For now, we do not support changing this flag - }) - } catch (err) { - logger.error( - `An error occurred while registering job ${job.config.name}`, - err - ) - } - } - } - - async load(): Promise { - let hasJobsDir = false - - try { - await readdir(this.rootDir_) - hasJobsDir = true - } catch (_err) { - hasJobsDir = false - } - - if (!hasJobsDir) { - return - } - - await this.createMap(this.rootDir_) - - await this.createScheduledJobs() - } -} diff --git a/packages/medusa/src/loaders/helpers/resolve-plugins.ts b/packages/medusa/src/loaders/helpers/resolve-plugins.ts index 2fe17ff9ac..9c2ad317ad 100644 --- a/packages/medusa/src/loaders/helpers/resolve-plugins.ts +++ b/packages/medusa/src/loaders/helpers/resolve-plugins.ts @@ -4,8 +4,8 @@ import fs from "fs" import { sync as existsSync } from "fs-exists-cached" import { createRequireFromPath } from "medusa-core-utils" import path from "path" -import { MEDUSA_PROJECT_NAME } from "../plugins" +export const MEDUSA_PROJECT_NAME = "project-plugin" function createPluginId(name: string): string { return name } diff --git a/packages/medusa/src/loaders/helpers/routing/__fixtures__/server/index.js b/packages/medusa/src/loaders/helpers/routing/__fixtures__/server/index.js index 11a46788bc..921c191277 100644 --- a/packages/medusa/src/loaders/helpers/routing/__fixtures__/server/index.js +++ b/packages/medusa/src/loaders/helpers/routing/__fixtures__/server/index.js @@ -12,11 +12,7 @@ import querystring from "querystring" import supertest from "supertest" import apiLoader from "../../../../api" import featureFlagLoader, { featureFlagRouter } from "../../../../feature-flags" -import modelsLoader from "../../../../models" import passportLoader from "../../../../passport" -import repositoriesLoader from "../../../../repositories" -import servicesLoader from "../../../../services" -import strategiesLoader from "../../../../strategies" import RoutesLoader from "../.." import { config } from "../mocks" @@ -88,10 +84,6 @@ export const createServer = async (rootDir) => { }) featureFlagLoader(config) - modelsLoader({ container, isTest: true }) - repositoriesLoader({ container, isTest: true }) - servicesLoader({ container, configModule: config }) - strategiesLoader({ container, configModule: config }) await passportLoader({ app: app, container, configModule: config }) await moduleLoader({ container, moduleResolutions }) diff --git a/packages/medusa/src/loaders/helpers/subscribers/index.ts b/packages/medusa/src/loaders/helpers/subscribers/index.ts index d9b3268783..cc74e51416 100644 --- a/packages/medusa/src/loaders/helpers/subscribers/index.ts +++ b/packages/medusa/src/loaders/helpers/subscribers/index.ts @@ -4,9 +4,9 @@ import { kebabCase } from "@medusajs/utils" import { readdir } from "fs/promises" import { extname, join, sep } from "path" -import { EventBusService } from "../../../services" import { SubscriberArgs, SubscriberConfig } from "../../../types/subscribers" import logger from "../../logger" +import { IEventBusModuleService } from "@medusajs/types" type SubscriberHandler = (args: SubscriberArgs) => Promise @@ -185,7 +185,7 @@ export class SubscriberLoader { config: SubscriberConfig handler: SubscriberHandler }) { - const eventBusService: EventBusService = this.container_.resolve( + const eventBusService: IEventBusModuleService = this.container_.resolve( ModuleRegistrationName.EVENT_BUS ) diff --git a/packages/medusa/src/loaders/load-medusa-project-apis.ts b/packages/medusa/src/loaders/load-medusa-project-apis.ts index ff7ee6a27a..52f9e7dec3 100644 --- a/packages/medusa/src/loaders/load-medusa-project-apis.ts +++ b/packages/medusa/src/loaders/load-medusa-project-apis.ts @@ -5,7 +5,6 @@ import { trackInstallation } from "medusa-telemetry" import { EOL } from "os" import path from "path" import { ConfigModule, Logger, MedusaContainer } from "../types/global" -import ScheduledJobsLoader from "./helpers/jobs" import { getResolvedPlugins } from "./helpers/resolve-plugins" import { RoutesLoader } from "./helpers/routing" import { SubscriberLoader } from "./helpers/subscribers" @@ -65,7 +64,8 @@ export default async ({ if (configModule.projectConfig.redis_url) { await Promise.all( resolved.map(async (pluginDetails) => { - await registerScheduledJobs(pluginDetails, container) + // await registerScheduledJobs(pluginDetails, container) + // TODO: Decide how scheduled jobs will be loaded and handled }) ) } else { @@ -101,17 +101,6 @@ async function runLoaders( ) } -async function registerScheduledJobs( - pluginDetails: PluginDetails, - container: MedusaContainer -): Promise { - await new ScheduledJobsLoader( - path.join(pluginDetails.resolve, "jobs"), - container, - pluginDetails.options - ).load() -} - /** * Registers the plugin's api routes. */ diff --git a/packages/medusa/src/loaders/medusa-app.ts b/packages/medusa/src/loaders/medusa-app.ts index 117a81a608..ba51dca3de 100644 --- a/packages/medusa/src/loaders/medusa-app.ts +++ b/packages/medusa/src/loaders/medusa-app.ts @@ -16,7 +16,6 @@ import { } from "@medusajs/types" import { ContainerRegistrationKeys, - FlagRouter, isObject, upperCaseFirst, } from "@medusajs/utils" diff --git a/packages/medusa/src/loaders/models.ts b/packages/medusa/src/loaders/models.ts deleted file mode 100644 index 8d7ac29087..0000000000 --- a/packages/medusa/src/loaders/models.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { - formatRegistrationName, - formatRegistrationNameWithoutNamespace, -} from "../utils/format-registration-name" -import { getModelExtensionsMap } from "./helpers/get-model-extension-map" -import glob from "glob" -import path from "path" -import { ClassConstructor, MedusaContainer } from "../types/global" -import { EntitySchema } from "typeorm" -import { asClass, asValue } from "awilix" - -type ModelLoaderParams = { - container: MedusaContainer - isTest?: boolean - rootDirectory?: string - corePathGlob?: string - coreTestPathGlob?: string - extensionPathGlob?: string -} -/** - * Registers all models in the model directory - */ -export default ( - { - container, - isTest, - rootDirectory, - corePathGlob = "../models/*.js", - coreTestPathGlob = "../models/*.ts", - extensionPathGlob = "dist/models/*.js", - }: ModelLoaderParams, - config = { register: true } -) => { - const coreModelsGlob = isTest ? coreTestPathGlob : corePathGlob - const coreModelsFullGlob = path.join(__dirname, coreModelsGlob) - const models: (ClassConstructor | EntitySchema)[] = [] - - const coreModels = glob.sync(coreModelsFullGlob, { - cwd: __dirname, - ignore: ["index.js", "index.ts", "index.js.map"], - }) - - const modelExtensionsMap = getModelExtensionsMap({ - directory: rootDirectory, - pathGlob: extensionPathGlob, - config, - }) - - coreModels.forEach((modelPath) => { - const loaded = require(modelPath) as - | ClassConstructor - | EntitySchema - - if (loaded) { - Object.entries(loaded).map( - ([, val]: [string, ClassConstructor | EntitySchema]) => { - if (typeof val === "function" || val instanceof EntitySchema) { - if (config.register) { - const name = formatRegistrationName(modelPath) - const mappedExtensionModel = modelExtensionsMap.get(name) - - // If an extension file is found, override it with that instead - if (mappedExtensionModel) { - const coreModel = require(modelPath) - const modelName = - formatRegistrationNameWithoutNamespace(modelPath) - - coreModel[modelName] = mappedExtensionModel - val = mappedExtensionModel - } - - container.register({ - [name]: asClass(val as ClassConstructor), - }) - - container.registerAdd("db_entities", asValue(val)) - } - - models.push(val) - } - } - ) - } - }) - - return models -} diff --git a/packages/medusa/src/loaders/plugins.ts b/packages/medusa/src/loaders/plugins.ts deleted file mode 100644 index b655fddc2a..0000000000 --- a/packages/medusa/src/loaders/plugins.ts +++ /dev/null @@ -1,705 +0,0 @@ -import { - AbstractSearchService, - promiseAll, - upperCaseFirst, -} from "@medusajs/utils" -import { aliasTo, asFunction, asValue, Lifetime } from "awilix" -import { Express } from "express" -import glob from "glob" -import { OauthService } from "medusa-interfaces" -import { trackInstallation } from "medusa-telemetry" -import { EOL } from "os" -import path from "path" -import { EntitySchema } from "typeorm" -import { MiddlewareService } from "../services" -import { - ClassConstructor, - ConfigModule, - Logger, - MedusaContainer, -} from "../types/global" -import { - formatRegistrationName, - formatRegistrationNameWithoutNamespace, -} from "../utils/format-registration-name" -import { getModelExtensionsMap } from "./helpers/get-model-extension-map" -import ScheduledJobsLoader from "./helpers/jobs" -import { getResolvedPlugins } from "./helpers/resolve-plugins" -import { RoutesLoader } from "./helpers/routing" -import { SubscriberLoader } from "./helpers/subscribers" -import logger from "./logger" - -type Options = { - rootDirectory: string - container: MedusaContainer - configModule: ConfigModule - app: Express - activityId: string -} - -type PluginDetails = { - resolve: string - name: string - id: string - options: Record - version: string -} - -export const isSearchEngineInstalledResolutionKey = "isSearchEngineInstalled" - -export const MEDUSA_PROJECT_NAME = "project-plugin" - -/** - * Registers all services in the services directory - */ -export default async ({ - rootDirectory, - container, - app, - configModule, - activityId, -}: Options): Promise => { - const resolved = getResolvedPlugins(rootDirectory, configModule) || [] - - await promiseAll( - resolved.map( - async (pluginDetails) => await runSetupFunctions(pluginDetails) - ) - ) - - await promiseAll( - resolved.map(async (pluginDetails) => { - registerRepositories(pluginDetails, container) - await registerServices(pluginDetails, container) - await registerMedusaApi(pluginDetails, container) - await registerApi( - pluginDetails, - app, - rootDirectory, - container, - configModule, - activityId - ) - registerCoreRouters(pluginDetails, container) - await registerSubscribers(pluginDetails, container, activityId) - await registerWorkflows(pluginDetails) - }) - ) - - await promiseAll( - resolved.map(async (pluginDetails) => runLoaders(pluginDetails, container)) - ) - - if (configModule.projectConfig.redis_url) { - await Promise.all( - resolved.map(async (pluginDetails) => { - await registerScheduledJobs(pluginDetails, container) - }) - ) - } else { - logger.warn( - "You don't have Redis configured. Scheduled jobs will not be enabled." - ) - } - - resolved.forEach((plugin) => trackInstallation(plugin.name, "plugin")) -} - -export async function registerPluginModels({ - rootDirectory, - container, - configModule, - extensionDirectoryPath = "dist", - pathGlob = "/models/*.js", -}: { - rootDirectory: string - container: MedusaContainer - configModule: ConfigModule - extensionDirectoryPath?: string - pathGlob?: string -}): Promise { - const resolved = - getResolvedPlugins(rootDirectory, configModule, extensionDirectoryPath) || - [] - - await promiseAll( - resolved.map(async (pluginDetails) => { - registerModels(pluginDetails, container, rootDirectory, pathGlob) - }) - ) -} - -async function runLoaders( - pluginDetails: PluginDetails, - container: MedusaContainer -): Promise { - const loaderFiles = glob.sync( - `${pluginDetails.resolve}/loaders/[!__]*.js`, - {} - ) - await promiseAll( - loaderFiles.map(async (loader) => { - try { - const module = require(loader).default - if (typeof module === "function") { - await module(container, pluginDetails.options) - } - } catch (err) { - const logger = container.resolve("logger") - logger.warn(`Running loader failed: ${err.message}`) - return Promise.resolve() - } - }) - ) -} - -async function registerScheduledJobs( - pluginDetails: PluginDetails, - container: MedusaContainer -): Promise { - await new ScheduledJobsLoader( - path.join(pluginDetails.resolve, "jobs"), - container, - pluginDetails.options - ).load() -} - -async function registerMedusaApi( - pluginDetails: PluginDetails, - container: MedusaContainer -): Promise { - registerMedusaMiddleware(pluginDetails, container) - registerStrategies(pluginDetails, container) -} - -export function registerStrategies( - pluginDetails: PluginDetails, - container: MedusaContainer -): void { - const files = glob.sync(`${pluginDetails.resolve}/strategies/[!__]*.js`, { - ignore: ["**/__fixtures__/**", "**/index.js", "**/index.ts"], - }) - const registeredServices = {} - - files.map((file) => { - const module = require(file).default - - switch (true) { - /* case AbstractTaxCalculationStrategy.isTaxCalculationStrategy( - module.prototype - ): { - if (!("taxCalculationStrategy" in registeredServices)) { - container.register({ - taxCalculationStrategy: asFunction( - (cradle) => new module(cradle, pluginDetails.options) - ).singleton(), - }) - registeredServices["taxCalculationStrategy"] = file - } else { - logger.warn( - `Cannot register ${file}. A tax calculation strategy is already registered` - ) - } - break - }*/ - - /* case AbstractCartCompletionStrategy.isCartCompletionStrategy( - module.prototype - ): { - if (!("cartCompletionStrategy" in registeredServices)) { - container.register({ - cartCompletionStrategy: asFunction( - (cradle) => new module(cradle, pluginDetails.options) - ).singleton(), - }) - registeredServices["cartCompletionStrategy"] = file - } else { - logger.warn( - `Cannot register ${file}. A cart completion strategy is already registered` - ) - } - break - }*/ - - /* case AbstractBatchJobStrategy.isBatchJobStrategy(module.prototype): { - container.registerAdd( - "batchJobStrategies", - asFunction((cradle) => new module(cradle, pluginDetails.options)) - ) - - const name = formatRegistrationName(file) - container.register({ - [name]: asFunction( - (cradle) => new module(cradle, pluginDetails.options) - ).singleton(), - [`batch_${module.identifier}`]: aliasTo(name), - [`batchType_${module.batchType}`]: aliasTo(name), - }) - break - }*/ - - /* case AbstractPriceSelectionStrategy.isPriceSelectionStrategy( - module.prototype - ): { - if (!("priceSelectionStrategy" in registeredServices)) { - container.register({ - priceSelectionStrategy: asFunction( - (cradle) => new module(cradle, pluginDetails.options) - ).singleton(), - }) - - registeredServices["priceSelectionStrategy"] = file - } else { - logger.warn( - `Cannot register ${file}. A price selection strategy is already registered` - ) - } - break - }*/ - - default: - logger.warn( - `${file} did not export a class that implements a strategy interface. Your Medusa server will still work, but if you have written custom strategy logic it will not be used. Make sure to implement the proper interface.` - ) - } - }) -} - -function registerMedusaMiddleware( - pluginDetails: PluginDetails, - container: MedusaContainer -): void { - let module - try { - module = require(`${pluginDetails.resolve}/api/medusa-middleware`).default - } catch (err) { - return - } - - const middlewareService = - container.resolve("middlewareService") - if (module.postAuthentication) { - middlewareService.addPostAuthentication( - module.postAuthentication, - pluginDetails.options - ) - } - - if (module.preAuthentication) { - middlewareService.addPreAuthentication( - module.preAuthentication, - pluginDetails.options - ) - } - - if (module.preCartCreation) { - middlewareService.addPreCartCreation(module.preCartCreation) - } -} - -function registerCoreRouters( - pluginDetails: PluginDetails, - container: MedusaContainer -): void { - const middlewareService = - container.resolve("middlewareService") - const { resolve } = pluginDetails - const adminFiles = glob.sync(`${resolve}/api/admin/[!__]*.js`, {}) - const storeFiles = glob.sync(`${resolve}/api/store/[!__]*.js`, {}) - - adminFiles.forEach((fn) => { - const descriptor = fn.split(".")[0] - const splat = descriptor.split("/") - const path = `${splat[splat.length - 2]}/${splat[splat.length - 1]}` - const loaded = require(fn).default - - if (loaded && typeof loaded === "function") { - middlewareService.addRouter(path, loaded()) - } - }) - - storeFiles.forEach((fn) => { - const descriptor = fn.split(".")[0] - const splat = descriptor.split("/") - const path = `${splat[splat.length - 2]}/${splat[splat.length - 1]}` - const loaded = require(fn).default - - if (loaded && typeof loaded === "function") { - middlewareService.addRouter(path, loaded()) - } - }) -} - -/** - * Registers the plugin's api routes. - */ -async function registerApi( - pluginDetails: PluginDetails, - app: Express, - rootDirectory = "", - container: MedusaContainer, - configmodule: ConfigModule, - activityId: string -): Promise { - const logger = container.resolve("logger") - const projectName = - pluginDetails.name === MEDUSA_PROJECT_NAME - ? "your Medusa project" - : `${pluginDetails.name}` - - logger.progress(activityId, `Registering custom endpoints for ${projectName}`) - - try { - /** - * Register the plugin's API routes using the file based routing. - */ - await new RoutesLoader({ - app, - rootDir: path.join(pluginDetails.resolve, "api"), - activityId: activityId, - configModule: configmodule, - }).load() - } catch (err) { - logger.warn( - `An error occurred while registering API Routes in ${projectName}${ - err.stack ? EOL + err.stack : "" - }` - ) - } - - try { - /** - * For backwards compatibility we also support loading routes from - * `/api/index` if the file exists. - */ - let apiFolderExists = true - - try { - require.resolve(`${pluginDetails.resolve}/api`) - } catch (e) { - apiFolderExists = false - } - - if (apiFolderExists) { - const routes = require(`${pluginDetails.resolve}/api`).default - if (routes) { - app.use("/", routes(rootDirectory, pluginDetails.options)) - } - } - } catch (err) { - if (err.code !== "MODULE_NOT_FOUND") { - logger.warn( - `An error occurred while registering endpoints in ${projectName}` - ) - - if (err.stack) { - logger.warn(`${err.stack}`) - } - } - } - - return app -} - -/** - * Registers a service at the right location in our container. - * PaymentService instances are added to the paymentProviders array in the - * container. Names are camelCase formatted and namespaced by the folder i.e: - * services/example-payments -> examplePaymentsService - * @param {object} pluginDetails - the plugin details including plugin options, - * version, id, resolved path, etc. See resolvePlugin - * @param {object} container - the container where the services will be - * registered - * @return {void} - */ -export async function registerServices( - pluginDetails: PluginDetails, - container: MedusaContainer -): Promise { - const files = glob.sync(`${pluginDetails.resolve}/services/[!__]*.js`, {}) - await promiseAll( - files.map(async (fn) => { - const loaded = require(fn).default - const name = formatRegistrationName(fn) - - if (typeof loaded !== "function") { - throw new Error( - `Cannot register ${name}. Make sure to default export a service class in ${fn}` - ) - } - - const context = { container, pluginDetails, registrationName: name } - - if (OauthService.isOauthService(loaded.prototype)) { - const appDetails = loaded.getAppDetails(pluginDetails.options) - - const oauthService = - container.resolve("oauthService") - await oauthService.registerOauthApp(appDetails) - - const name = appDetails.application_name - container.register({ - [`${name}Oauth`]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - } - ), - }) - } /* else if ( - AbstractNotificationService.isNotificationService(loaded.prototype) - ) { - container.registerAdd( - "notificationProviders", - asFunction((cradle) => new loaded(cradle, pluginDetails.options), { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - }) - ) - - // Add the service directly to the container in order to make simple - // resolution if we already know which notification provider we need to use - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - } - ), - [`noti_${loaded.identifier}`]: aliasTo(name), - }) - }*/ /* else if (AbstractFileService.isFileService(loaded.prototype)) { - // Add the service directly to the container in order to make simple - // resolution if we already know which file storage provider we need to use - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - } - ), - [`fileService`]: aliasTo(name), - }) - }*/ else if (AbstractSearchService.isSearchService(loaded.prototype)) { - // Add the service directly to the container in order to make simple - // resolution if we already know which search provider we need to use - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - } - ), - [`searchService`]: aliasTo(name), - }) - - container.register(isSearchEngineInstalledResolutionKey, asValue(true)) - } /* else if (AbstractTaxService.isTaxService(loaded.prototype)) { - container.registerAdd( - "taxProviders", - asFunction((cradle) => new loaded(cradle, pluginDetails.options), { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - }) - ) - - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SINGLETON, - } - ), - [`tp_${loaded.identifier}`]: aliasTo(name), - }) - }*/ else { - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, pluginDetails.options), - { - lifetime: loaded.LIFE_TIME || Lifetime.SCOPED, - } - ), - }) - } - }) - ) -} - -/** - * Registers a plugin's subscribers at the right location in our container. - * Subscribers are registered directly in the container. - * @param {object} pluginDetails - the plugin details including plugin options, - * version, id, resolved path, etc. See resolvePlugin - * @param {object} container - the container where the services will be - * registered - * @return {void} - */ -async function registerSubscribers( - pluginDetails: PluginDetails, - container: MedusaContainer, - activityId: string -): Promise { - const loadedFiles = await new SubscriberLoader( - path.join(pluginDetails.resolve, "subscribers"), - container, - pluginDetails.options, - activityId - ).load() - - /** - * Exclude any files that have already been loaded by the subscriber loader - */ - const normalizedLoadedFiles = - loadedFiles?.map((file) => file.replace(/\\/g, "/")) ?? [] - - const files = glob.sync(`${pluginDetails.resolve}/subscribers/*.js`, {}) - files - .filter((file) => !normalizedLoadedFiles.includes(file)) - .forEach((fn) => { - const loaded = require(fn).default - - container.build( - asFunction( - (cradle) => new loaded(cradle, pluginDetails.options) - ).singleton() - ) - }) -} - -/** - * Registers a plugin's repositories at the right location in our container. - * repositories are registered directly in the container. - * @param {object} pluginDetails - the plugin details including plugin options, - * version, id, resolved path, etc. See resolvePlugin - * @param {object} container - the container where the services will be - * registered - * @return {void} - */ -function registerRepositories( - pluginDetails: PluginDetails, - container: MedusaContainer -): void { - const files = glob.sync(`${pluginDetails.resolve}/repositories/*.js`, {}) - files.forEach((fn) => { - const loaded = require(fn) - - Object.entries(loaded).map(([, val]: [string, any]) => { - if (typeof loaded === "object") { - const name = formatRegistrationName(fn) - container.register({ - [name]: asValue(val), - }) - } - }) - }) -} - -/** - * import files from the workflows directory to run the registration of the wofklows - * @param pluginDetails - */ -async function registerWorkflows(pluginDetails: PluginDetails): Promise { - const files = glob.sync(`${pluginDetails.resolve}/workflows/*.js`, {}) - await Promise.all(files.map(async (file) => import(file))) -} - -/** - * Registers a plugin's models at the right location in our container. Models - * must inherit from BaseModel. Models are registered directly in the container. - * Names are camelCase formatted and namespaced by the folder i.e: - * models/example-person -> examplePersonModel - * @param {object} pluginDetails - the plugin details including plugin options, - * version, id, resolved path, etc. See resolvePlugin - * @param {object} container - the container where the services will be - * registered - * @param rootDirectory - * @param pathGlob - * @return {void} - */ -function registerModels( - pluginDetails: PluginDetails, - container: MedusaContainer, - rootDirectory: string, - pathGlob = "/models/*.js" -): void { - const pluginFullPathGlob = path.join(pluginDetails.resolve, pathGlob) - - const modelExtensionsMap = getModelExtensionsMap({ - directory: pluginDetails.resolve, - pathGlob: pathGlob, - config: { register: true }, - }) - - const pluginModels = glob.sync(pluginFullPathGlob, { - ignore: ["index.js", "index.js.map"], - }) - - const coreModelsFullGlob = path.join(__dirname, "../models/*.js") - const coreModels = glob.sync(coreModelsFullGlob, { - cwd: __dirname, - ignore: ["index.js", "index.ts", "index.js.map"], - }) - - // Apply the extended models to the core models first to ensure that - // when relationships are created, the extended models are used - coreModels.forEach((modelPath) => { - const loaded = require(modelPath) as - | ClassConstructor - | EntitySchema - - if (loaded) { - const name = formatRegistrationName(modelPath) - const mappedExtensionModel = modelExtensionsMap.get(name) - if (mappedExtensionModel) { - const modelName = upperCaseFirst( - formatRegistrationNameWithoutNamespace(modelPath) - ) - - loaded[modelName] = mappedExtensionModel - } - } - }) - - pluginModels.forEach((coreOrPluginModelPath) => { - const loaded = require(coreOrPluginModelPath) as - | ClassConstructor - | EntitySchema - - if (loaded) { - Object.entries(loaded).map( - ([, val]: [string, ClassConstructor | EntitySchema]) => { - if (typeof val === "function" || val instanceof EntitySchema) { - const name = formatRegistrationName(coreOrPluginModelPath) - - container.register({ - [name]: asValue(val), - }) - - container.registerAdd("db_entities", asValue(val)) - } - } - ) - } - }) -} - -/** - * Runs all setup functions in a plugin. Setup functions are run before anything from the plugin is - * registered to the container. This is useful for running custom build logic, fetching remote - * configurations, etc. - * @param pluginDetails The plugin details including plugin options, version, id, resolved path, etc. - */ -async function runSetupFunctions(pluginDetails: PluginDetails): Promise { - const files = glob.sync(`${pluginDetails.resolve}/setup/*.js`, {}) - await promiseAll( - files.map(async (fn) => { - const loaded = require(fn).default - try { - await loaded() - } catch (err) { - throw new Error( - `A setup function from ${pluginDetails.name} failed. ${err}` - ) - } - }) - ) -} diff --git a/packages/medusa/src/loaders/repositories.ts b/packages/medusa/src/loaders/repositories.ts deleted file mode 100644 index df38c9f8b7..0000000000 --- a/packages/medusa/src/loaders/repositories.ts +++ /dev/null @@ -1,32 +0,0 @@ -import glob from "glob" -import path from "path" - -import formatRegistrationName from "../utils/format-registration-name" -import { MedusaContainer } from "../types/global" -import { asValue } from "awilix" - -/** - * Registers all models in the model directory - */ -export default ({ - container, - isTest, -}: { - container: MedusaContainer - isTest?: boolean -}): void => { - const corePath = isTest ? "../repositories/*.ts" : "../repositories/*.js" - const coreFull = path.join(__dirname, corePath) - - const core = glob.sync(coreFull, { cwd: __dirname }) - core.forEach((fn) => { - const loaded = require(fn).default - - if (typeof loaded === "object") { - const name = formatRegistrationName(fn) - container.register({ - [name]: asValue(loaded), - }) - } - }) -} diff --git a/packages/medusa/src/loaders/search-index.ts b/packages/medusa/src/loaders/search-index.ts deleted file mode 100644 index d70da272f6..0000000000 --- a/packages/medusa/src/loaders/search-index.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { EventBusService } from "../services" -import { Logger, MedusaContainer } from "../types/global" - -export const SEARCH_INDEX_EVENT = "SEARCH_INDEX_EVENT" - -async function loadProductsIntoSearchEngine( - container: MedusaContainer -): Promise { - const logger: Logger = container.resolve("logger") - const eventBusService: EventBusService = container.resolve("eventBusService") - void eventBusService.emit(SEARCH_INDEX_EVENT, {}).catch((err) => { - logger.error(err) - logger.error( - "Something went wrong while emitting the search indexing event." - ) - }) -} - -export default async ({ - container, -}: { - container: MedusaContainer -}): Promise => { - // const searchService = - // container.resolve("searchService") - // const logger = container.resolve("logger") - // if (searchService.isDefault) { - // logger.warn( - // "No search engine provider was found: make sure to include a search plugin to enable searching" - // ) - // return - // } - - await loadProductsIntoSearchEngine(container) -} diff --git a/packages/medusa/src/loaders/services.ts b/packages/medusa/src/loaders/services.ts deleted file mode 100644 index 857953b660..0000000000 --- a/packages/medusa/src/loaders/services.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { asFunction } from "awilix" -import glob from "glob" -import { isDefined } from "medusa-core-utils" -import path from "path" -import { ConfigModule, MedusaContainer } from "../types/global" -import formatRegistrationName from "../utils/format-registration-name" - -type Options = { - container: MedusaContainer - configModule: ConfigModule - isTest?: boolean -} - -/** - * Registers all services in the services directory - */ -export default ({ container, configModule, isTest }: Options): void => { - const useMock = isDefined(isTest) ? isTest : process.env.NODE_ENV === "test" - - const corePath = useMock ? "../services/__mocks__/*.js" : "../services/*.js" - const coreFull = path.join(__dirname, corePath) - - const core = glob.sync(coreFull, { cwd: __dirname }) - core.forEach((fn) => { - const loaded = require(fn).default - if (loaded) { - const name = formatRegistrationName(fn) - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, configModule) - ).singleton(), - }) - } - }) -} diff --git a/packages/medusa/src/loaders/strategies.ts b/packages/medusa/src/loaders/strategies.ts deleted file mode 100644 index ec5af1250a..0000000000 --- a/packages/medusa/src/loaders/strategies.ts +++ /dev/null @@ -1,58 +0,0 @@ -import glob from "glob" -import path from "path" -import { aliasTo, asFunction } from "awilix" - -import formatRegistrationName from "../utils/format-registration-name" -import { MedusaContainer } from "../types/global" -import { isDefined } from "medusa-core-utils" -/*import { AbstractBatchJobStrategy } from "../interfaces"*/ - -type LoaderOptions = { - container: MedusaContainer - configModule: object - isTest?: boolean -} - -/** - * Registers all strategies in the strategies directory - * @returns void - */ -export default ({ container, configModule, isTest }: LoaderOptions): void => { - const useMock = isDefined(isTest) ? isTest : process.env.NODE_ENV === "test" - - const corePath = useMock - ? "../strategies/__mocks__/[!__]*.js" - : "../strategies/**/[!__]*.js" - - const coreFull = path.join(__dirname, corePath) - - const ignore = [ - "**/__fixtures__/**", - "**/index.js", - "**/index.ts", - "**/utils.js", - "**/utils.ts", - "**/types.js", - "**/types.ts", - "**/types/**", - ] - if (!useMock) { - ignore.push("**/__tests__/**", "**/__mocks__/**") - } - - const core = glob.sync(coreFull, { - cwd: __dirname, - ignore, - }) - - core.forEach((fn) => { - const loaded = require(fn).default - const name = formatRegistrationName(fn) - - container.register({ - [name]: asFunction( - (cradle) => new loaded(cradle, configModule) - ).singleton(), - }) - }) -} diff --git a/packages/medusa/src/migrations/1611063162649-initial_schema.ts b/packages/medusa/src/migrations/1611063162649-initial_schema.ts deleted file mode 100644 index 55be851445..0000000000 --- a/packages/medusa/src/migrations/1611063162649-initial_schema.ts +++ /dev/null @@ -1,382 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class initialSchema1611063162649 implements MigrationInterface { - name = 'initialSchema1611063162649' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TABLE "fulfillment_provider" ("id" character varying NOT NULL, "is_installed" boolean NOT NULL DEFAULT true, CONSTRAINT "PK_beb35a6de60a6c4f91d5ae57e44" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "fulfillment_item" ("fulfillment_id" character varying NOT NULL, "item_id" character varying NOT NULL, "quantity" integer NOT NULL, CONSTRAINT "PK_bc3e8a388de75db146a249922e0" PRIMARY KEY ("fulfillment_id", "item_id"))`); - await queryRunner.query(`CREATE TABLE "fulfillment" ("id" character varying NOT NULL, "swap_id" character varying, "order_id" character varying, "tracking_numbers" jsonb NOT NULL DEFAULT '[]', "data" jsonb NOT NULL, "shipped_at" TIMESTAMP WITH TIME ZONE, "canceled_at" TIMESTAMP WITH TIME ZONE, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "idempotency_key" character varying, "provider_id" character varying, CONSTRAINT "PK_50c102da132afffae660585981f" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "return_item" ("return_id" character varying NOT NULL, "item_id" character varying NOT NULL, "quantity" integer NOT NULL, "is_requested" boolean NOT NULL DEFAULT true, "requested_quantity" integer, "received_quantity" integer, "metadata" jsonb, CONSTRAINT "PK_46409dc1dd5f38509b9000c3069" PRIMARY KEY ("return_id", "item_id"))`); - await queryRunner.query(`CREATE TABLE "currency" ("code" character varying NOT NULL, "symbol" character varying NOT NULL, "symbol_native" character varying NOT NULL, "name" character varying NOT NULL, CONSTRAINT "PK_723472e41cae44beb0763f4039c" PRIMARY KEY ("code"))`); - await queryRunner.query(`CREATE TABLE "country" ("id" SERIAL NOT NULL, "iso_2" character varying NOT NULL, "iso_3" character varying NOT NULL, "num_code" integer NOT NULL, "name" character varying NOT NULL, "display_name" character varying NOT NULL, "region_id" character varying, CONSTRAINT "PK_bf6e37c231c4f4ea56dcd887269" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_e78901b1131eaf8203d9b1cb5f" ON "country" ("iso_2") `); - await queryRunner.query(`CREATE TABLE "payment_provider" ("id" character varying NOT NULL, "is_installed" boolean NOT NULL DEFAULT true, CONSTRAINT "PK_ea94f42b6c88e9191c3649d7522" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "region" ("id" character varying NOT NULL, "name" character varying NOT NULL, "currency_code" character varying NOT NULL, "tax_rate" numeric NOT NULL, "tax_code" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_5f48ffc3af96bc486f5f3f3a6da" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "image" ("id" character varying NOT NULL, "url" 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, "metadata" jsonb, CONSTRAINT "PK_d6db1ab4ee9ad9dbe86c64e4cc3" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "money_amount" ("id" character varying NOT NULL, "currency_code" character varying NOT NULL, "amount" integer NOT NULL, "sale_amount" integer DEFAULT null, "variant_id" character varying, "region_id" character varying, "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, CONSTRAINT "PK_022e49a7e21a8dfb820f788778a" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "product_variant" ("id" character varying NOT NULL, "title" character varying NOT NULL, "product_id" character varying NOT NULL, "sku" character varying, "barcode" character varying, "ean" character varying, "upc" character varying, "inventory_quantity" integer NOT NULL, "allow_backorder" boolean NOT NULL DEFAULT false, "manage_inventory" boolean NOT NULL DEFAULT true, "hs_code" character varying, "origin_country" character varying, "mid_code" character varying, "material" character varying, "weight" integer, "length" integer, "height" integer, "width" integer, "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, "metadata" jsonb, CONSTRAINT "PK_1ab69c9935c61f7c70791ae0a9f" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_f4dc2c0888b66d547c175f090e" ON "product_variant" ("sku") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_9db95c4b71f632fc93ecbc3d8b" ON "product_variant" ("barcode") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_7124082c8846a06a857cca386c" ON "product_variant" ("ean") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_a0a3f124dc5b167622217fee02" ON "product_variant" ("upc") `); - await queryRunner.query(`CREATE TABLE "product_option_value" ("id" character varying NOT NULL, "value" character varying NOT NULL, "option_id" character varying NOT NULL, "variant_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, "metadata" jsonb, CONSTRAINT "PK_2ab71ed3b21be5800905c621535" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE INDEX "IDX_cdf4388f294b30a25c627d69fe" ON "product_option_value" ("option_id") `); - await queryRunner.query(`CREATE TABLE "product_option" ("id" character varying NOT NULL, "title" 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, "metadata" jsonb, "product_id" character varying, CONSTRAINT "PK_4cf3c467e9bc764bdd32c4cd938" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "shipping_option_requirement_type_enum" AS ENUM('min_subtotal', 'max_subtotal')`); - await queryRunner.query(`CREATE TABLE "shipping_option_requirement" ("id" character varying NOT NULL, "shipping_option_id" character varying NOT NULL, "type" "shipping_option_requirement_type_enum" NOT NULL, "amount" integer NOT NULL, CONSTRAINT "PK_a0ff15442606d9f783602cb23a7" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "shipping_option_price_type_enum" AS ENUM('flat_rate', 'calculated')`); - await queryRunner.query(`CREATE TABLE "shipping_option" ("id" character varying NOT NULL, "name" character varying NOT NULL, "region_id" character varying NOT NULL, "profile_id" character varying NOT NULL, "provider_id" character varying NOT NULL, "price_type" "shipping_option_price_type_enum" NOT NULL, "amount" integer, "is_return" boolean NOT NULL DEFAULT false, "data" jsonb 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, "metadata" jsonb, CONSTRAINT "CHK_7a367f5901ae0a5b0df75aee38" CHECK ("amount" >= 0), CONSTRAINT "PK_2e56fddaa65f3a26d402e5d786e" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "shipping_profile_type_enum" AS ENUM('default', 'gift_card', 'custom')`); - await queryRunner.query(`CREATE TABLE "shipping_profile" ("id" character varying NOT NULL, "name" character varying NOT NULL, "type" "shipping_profile_type_enum" 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, "metadata" jsonb, CONSTRAINT "PK_c8120e4543a5a3a121f2968a1ec" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "product" ("id" character varying NOT NULL, "title" character varying NOT NULL, "subtitle" character varying, "description" character varying, "tags" character varying, "handle" character varying, "is_giftcard" boolean NOT NULL DEFAULT false, "thumbnail" character varying, "profile_id" character varying NOT NULL, "weight" integer, "length" integer, "height" integer, "width" integer, "hs_code" character varying, "origin_country" character varying, "mid_code" character varying, "material" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_bebc9158e480b949565b4dc7a82" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_db7355f7bd36c547c8a4f539e5" ON "product" ("handle") `); - await queryRunner.query(`CREATE TYPE "discount_rule_type_enum" AS ENUM('fixed', 'percentage', 'free_shipping')`); - await queryRunner.query(`CREATE TYPE "discount_rule_allocation_enum" AS ENUM('total', 'item')`); - await queryRunner.query(`CREATE TABLE "discount_rule" ("id" character varying NOT NULL, "description" character varying NOT NULL, "type" "discount_rule_type_enum" NOT NULL, "value" integer NOT NULL, "allocation" "discount_rule_allocation_enum", "usage_limit" integer, "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, "metadata" jsonb, CONSTRAINT "PK_ac2c280de3701b2d66f6817f760" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "discount" ("id" character varying NOT NULL, "code" character varying NOT NULL, "is_dynamic" boolean NOT NULL, "rule_id" character varying, "is_disabled" boolean NOT NULL, "parent_discount_id" character varying, "starts_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, "ends_at" TIMESTAMP WITH TIME ZONE, "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, "metadata" jsonb, CONSTRAINT "PK_d05d8712e429673e459e7f1cddb" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_087926f6fec32903be3c8eedfa" ON "discount" ("code") `); - await queryRunner.query(`CREATE TYPE "payment_session_status_enum" AS ENUM('authorized', 'pending', 'requires_more', 'error', 'canceled')`); - await queryRunner.query(`CREATE TABLE "payment_session" ("id" character varying NOT NULL, "cart_id" character varying NOT NULL, "provider_id" character varying NOT NULL, "is_selected" boolean, "status" "payment_session_status_enum" NOT NULL, "data" jsonb NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "idempotency_key" character varying, CONSTRAINT "OneSelected" UNIQUE ("cart_id", "is_selected"), CONSTRAINT "PK_a1a91b20f7f3b1e5afb5485cbcd" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "payment" ("id" character varying NOT NULL, "swap_id" character varying, "cart_id" character varying, "order_id" character varying, "amount" integer NOT NULL, "currency_code" character varying NOT NULL, "amount_refunded" integer NOT NULL DEFAULT '0', "provider_id" character varying NOT NULL, "data" jsonb NOT NULL, "captured_at" TIMESTAMP WITH TIME ZONE, "canceled_at" TIMESTAMP WITH TIME ZONE, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_c17aff091441b7c25ec3d68d36" UNIQUE ("swap_id"), CONSTRAINT "REL_4665f17abc1e81dd58330e5854" UNIQUE ("cart_id"), CONSTRAINT "PK_fcaec7df5adf9cac408c686b2ab" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "gift_card" ("id" character varying NOT NULL, "code" character varying NOT NULL, "value" integer NOT NULL, "balance" integer NOT NULL, "region_id" character varying NOT NULL, "order_id" character varying, "is_disabled" boolean NOT NULL DEFAULT false, "ends_at" TIMESTAMP WITH TIME ZONE, "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, "metadata" jsonb, CONSTRAINT "REL_dfc1f02bb0552e79076aa58dbb" UNIQUE ("order_id"), CONSTRAINT "PK_af4e338d2d41035042843ad641f" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_53cb5605fa42e82b4d47b47bda" ON "gift_card" ("code") `); - await queryRunner.query(`CREATE TYPE "cart_type_enum" AS ENUM('default', 'swap', 'payment_link')`); - await queryRunner.query(`CREATE TABLE "cart" ("id" character varying NOT NULL, "email" character varying, "billing_address_id" character varying, "shipping_address_id" character varying, "region_id" character varying NOT NULL, "customer_id" character varying, "payment_id" character varying, "type" "cart_type_enum" NOT NULL DEFAULT 'default', "completed_at" TIMESTAMP WITH TIME ZONE, "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, "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_9d1a161434c610aae7c3df2dc7" UNIQUE ("payment_id"), CONSTRAINT "PK_c524ec48751b9b5bcfbf6e59be7" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "shipping_method" ("id" character varying NOT NULL, "shipping_option_id" character varying NOT NULL, "order_id" character varying, "cart_id" character varying, "swap_id" character varying, "return_id" character varying, "price" integer NOT NULL, "data" jsonb NOT NULL, CONSTRAINT "REL_1d9ad62038998c3a85c77a53cf" UNIQUE ("return_id"), CONSTRAINT "CHK_64c6812fe7815be30d688df513" CHECK ("price" >= 0), CONSTRAINT "CHK_3c00b878c1426d119cd70aa065" CHECK ("order_id" IS NOT NULL OR "cart_id" IS NOT NULL OR "swap_id" IS NOT NULL OR "return_id" IS NOT NULL), CONSTRAINT "PK_b9b0adfad3c6b99229c1e7d4865" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE INDEX "IDX_fc963e94854bff2714ca84cd19" ON "shipping_method" ("shipping_option_id") `); - await queryRunner.query(`CREATE INDEX "IDX_5267705a43d547e232535b656c" ON "shipping_method" ("order_id") `); - await queryRunner.query(`CREATE INDEX "IDX_d92993a7d554d84571f4eea1d1" ON "shipping_method" ("cart_id") `); - await queryRunner.query(`CREATE INDEX "IDX_fb94fa8d5ca940daa2a58139f8" ON "shipping_method" ("swap_id") `); - await queryRunner.query(`CREATE INDEX "IDX_1d9ad62038998c3a85c77a53cf" ON "shipping_method" ("return_id") `); - await queryRunner.query(`CREATE TYPE "return_status_enum" AS ENUM('requested', 'received', 'requires_action')`); - await queryRunner.query(`CREATE TABLE "return" ("id" character varying NOT NULL, "status" "return_status_enum" NOT NULL DEFAULT 'requested', "swap_id" character varying, "order_id" character varying, "shipping_data" jsonb, "refund_amount" integer NOT NULL, "received_at" TIMESTAMP WITH TIME ZONE, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_bad82d7bff2b08b87094bfac3d" UNIQUE ("swap_id"), CONSTRAINT "PK_c8ad68d13e76d75d803b5aeebc4" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "swap_fulfillment_status_enum" AS ENUM('not_fulfilled', 'fulfilled', 'shipped', 'canceled', 'requires_action')`); - await queryRunner.query(`CREATE TYPE "swap_payment_status_enum" AS ENUM('not_paid', 'awaiting', 'captured', 'canceled', 'difference_refunded', 'partially_refunded', 'refunded', 'requires_action')`); - await queryRunner.query(`CREATE TABLE "swap" ("id" character varying NOT NULL, "fulfillment_status" "swap_fulfillment_status_enum" NOT NULL, "payment_status" "swap_payment_status_enum" NOT NULL, "order_id" character varying NOT NULL, "difference_due" integer, "shipping_address_id" character varying, "cart_id" character varying, "confirmed_at" TIMESTAMP WITH TIME ZONE, "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, "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_402e8182bc553e082f6380020b" UNIQUE ("cart_id"), CONSTRAINT "PK_4a10d0f359339acef77e7f986d9" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "line_item" ("id" character varying NOT NULL, "cart_id" character varying, "order_id" character varying, "swap_id" character varying, "title" character varying NOT NULL, "description" character varying, "thumbnail" character varying, "is_giftcard" boolean NOT NULL DEFAULT false, "should_merge" boolean NOT NULL DEFAULT true, "allow_discounts" boolean NOT NULL DEFAULT true, "has_shipping" boolean, "unit_price" integer NOT NULL, "variant_id" character varying, "quantity" integer NOT NULL, "fulfilled_quantity" integer, "returned_quantity" integer, "shipped_quantity" integer, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "CHK_64eef00a5064887634f1680866" CHECK ("quantity" > 0), CONSTRAINT "CHK_91f40396d847f6ecfd9f752bf8" CHECK ("returned_quantity" <= "quantity"), CONSTRAINT "CHK_0cd85e15610d11b553d5e8fda6" CHECK ("shipped_quantity" <= "fulfilled_quantity"), CONSTRAINT "CHK_c61716c68f5ad5de2834c827d3" CHECK ("fulfilled_quantity" <= "quantity"), CONSTRAINT "PK_cce6b13e67fa506d1d9618ac68b" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE INDEX "IDX_27283ee631862266d0f1c68064" ON "line_item" ("cart_id") `); - await queryRunner.query(`CREATE INDEX "IDX_43a2b24495fe1d9fc2a9c835bc" ON "line_item" ("order_id") `); - await queryRunner.query(`CREATE INDEX "IDX_3fa354d8d1233ff81097b2fcb6" ON "line_item" ("swap_id") `); - await queryRunner.query(`CREATE INDEX "IDX_5371cbaa3be5200f373d24e3d5" ON "line_item" ("variant_id") `); - await queryRunner.query(`CREATE TABLE "gift_card_transaction" ("id" character varying NOT NULL, "gift_card_id" character varying NOT NULL, "order_id" character varying NOT NULL, "amount" integer NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "gcuniq" UNIQUE ("gift_card_id", "order_id"), CONSTRAINT "PK_cfb5b4ba5447a507aef87d73fe7" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "refund_reason_enum" AS ENUM('discount', 'return', 'swap', 'other')`); - await queryRunner.query(`CREATE TABLE "refund" ("id" character varying NOT NULL, "order_id" character varying NOT NULL, "amount" integer NOT NULL, "note" character varying, "reason" "refund_reason_enum" NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "PK_f1cefa2e60d99b206c46c1116e5" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TYPE "order_status_enum" AS ENUM('pending', 'completed', 'archived', 'canceled', 'requires_action')`); - await queryRunner.query(`CREATE TYPE "order_fulfillment_status_enum" AS ENUM('not_fulfilled', 'partially_fulfilled', 'fulfilled', 'partially_shipped', 'shipped', 'partially_returned', 'returned', 'canceled', 'requires_action')`); - await queryRunner.query(`CREATE TYPE "order_payment_status_enum" AS ENUM('not_paid', 'awaiting', 'captured', 'partially_refunded', 'refunded', 'canceled', 'requires_action')`); - await queryRunner.query(`CREATE TABLE "order" ("id" character varying NOT NULL, "status" "order_status_enum" NOT NULL DEFAULT 'pending', "fulfillment_status" "order_fulfillment_status_enum" NOT NULL DEFAULT 'not_fulfilled', "payment_status" "order_payment_status_enum" NOT NULL DEFAULT 'not_paid', "display_id" SERIAL NOT NULL, "cart_id" character varying, "customer_id" character varying NOT NULL, "email" character varying NOT NULL, "billing_address_id" character varying, "shipping_address_id" character varying, "region_id" character varying NOT NULL, "currency_code" character varying NOT NULL, "tax_rate" integer NOT NULL, "canceled_at" TIMESTAMP WITH TIME ZONE, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_c99a206eb11ad45f6b7f04f2dc" UNIQUE ("cart_id"), CONSTRAINT "PK_1031171c13130102495201e3e20" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "customer" ("id" character varying NOT NULL, "email" character varying NOT NULL, "first_name" character varying, "last_name" character varying, "billing_address_id" character varying, "password_hash" character varying, "phone" character varying, "has_account" boolean NOT NULL DEFAULT false, "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, "metadata" jsonb, CONSTRAINT "REL_8abe81b9aac151ae60bf507ad1" UNIQUE ("billing_address_id"), CONSTRAINT "PK_a7a13f4cacb744524e44dfdad32" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_fdb2f3ad8115da4c7718109a6e" ON "customer" ("email") `); - await queryRunner.query(`CREATE TABLE "address" ("id" character varying NOT NULL, "customer_id" character varying, "company" character varying, "first_name" character varying, "last_name" character varying, "address_1" character varying, "address_2" character varying, "city" character varying, "country_code" character varying, "province" character varying, "postal_code" character varying, "phone" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_d92de1f82754668b5f5f5dd4fd5" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "idempotency_key" ("id" character varying NOT NULL, "idempotency_key" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "locked_at" TIMESTAMP WITH TIME ZONE, "request_method" character varying, "request_params" jsonb, "request_path" character varying, "response_code" integer, "response_body" jsonb, "recovery_point" character varying NOT NULL DEFAULT 'started', CONSTRAINT "PK_213f125e14469be304f9ff1d452" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_a421bf4588d0004a9b0c0fe84f" ON "idempotency_key" ("idempotency_key") `); - await queryRunner.query(`CREATE TABLE "oauth" ("id" character varying NOT NULL, "display_name" character varying NOT NULL, "application_name" character varying NOT NULL, "install_url" character varying, "uninstall_url" character varying, "data" jsonb, CONSTRAINT "PK_a957b894e50eb16b969c0640a8d" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_c49c061b1a686843c5d673506f" ON "oauth" ("application_name") `); - await queryRunner.query(`CREATE TABLE "staged_job" ("id" character varying NOT NULL, "event_name" character varying NOT NULL, "data" jsonb NOT NULL, CONSTRAINT "PK_9a28fb48c46c5509faf43ac8c8d" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "store" ("id" character varying NOT NULL, "name" character varying NOT NULL DEFAULT 'Medusa Store', "default_currency_code" character varying NOT NULL DEFAULT 'usd', "swap_link_template" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_f3172007d4de5ae8e7692759d79" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "user" ("id" character varying NOT NULL, "email" character varying NOT NULL, "first_name" character varying, "last_name" character varying, "password_hash" character varying NOT NULL, "api_token" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_cace4a159ff9f2512dd42373760" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_e12875dfb3b1d92d7d7c5377e2" ON "user" ("email") `); - await queryRunner.query(`CREATE TABLE "region_payment_providers" ("region_id" character varying NOT NULL, "provider_id" character varying NOT NULL, CONSTRAINT "PK_9fa1e69914d3dd752de6b1da407" PRIMARY KEY ("region_id", "provider_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_8aaa78ba90d3802edac317df86" ON "region_payment_providers" ("region_id") `); - await queryRunner.query(`CREATE INDEX "IDX_3a6947180aeec283cd92c59ebb" ON "region_payment_providers" ("provider_id") `); - await queryRunner.query(`CREATE TABLE "region_fulfillment_providers" ("region_id" character varying NOT NULL, "provider_id" character varying NOT NULL, CONSTRAINT "PK_5b7d928a1fb50d6803868cfab3a" PRIMARY KEY ("region_id", "provider_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_c556e14eff4d6f03db593df955" ON "region_fulfillment_providers" ("region_id") `); - await queryRunner.query(`CREATE INDEX "IDX_37f361c38a18d12a3fa3158d0c" ON "region_fulfillment_providers" ("provider_id") `); - await queryRunner.query(`CREATE TABLE "product_images" ("product_id" character varying NOT NULL, "image_id" character varying NOT NULL, CONSTRAINT "PK_10de97980da2e939c4c0e8423f2" PRIMARY KEY ("product_id", "image_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_4f166bb8c2bfcef2498d97b406" ON "product_images" ("product_id") `); - await queryRunner.query(`CREATE INDEX "IDX_2212515ba306c79f42c46a99db" ON "product_images" ("image_id") `); - await queryRunner.query(`CREATE TABLE "discount_rule_products" ("discount_rule_id" character varying NOT NULL, "product_id" character varying NOT NULL, CONSTRAINT "PK_351c8c92f5d27283c445cd022ee" PRIMARY KEY ("discount_rule_id", "product_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_4e0739e5f0244c08d41174ca08" ON "discount_rule_products" ("discount_rule_id") `); - await queryRunner.query(`CREATE INDEX "IDX_be66106a673b88a81c603abe7e" ON "discount_rule_products" ("product_id") `); - await queryRunner.query(`CREATE TABLE "discount_regions" ("discount_id" character varying NOT NULL, "region_id" character varying NOT NULL, CONSTRAINT "PK_15974566a8b6e04a7c754e85b75" PRIMARY KEY ("discount_id", "region_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_f4194aa81073f3fab8aa86906f" ON "discount_regions" ("discount_id") `); - await queryRunner.query(`CREATE INDEX "IDX_a21a7ffbe420d492eb46c305fe" ON "discount_regions" ("region_id") `); - await queryRunner.query(`CREATE TABLE "cart_discounts" ("cart_id" character varying NOT NULL, "discount_id" character varying NOT NULL, CONSTRAINT "PK_10bd412c9071ccc0cf555afd9bb" PRIMARY KEY ("cart_id", "discount_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_6680319ebe1f46d18f106191d5" ON "cart_discounts" ("cart_id") `); - await queryRunner.query(`CREATE INDEX "IDX_8df75ef4f35f217768dc113545" ON "cart_discounts" ("discount_id") `); - await queryRunner.query(`CREATE TABLE "cart_gift_cards" ("cart_id" character varying NOT NULL, "gift_card_id" character varying NOT NULL, CONSTRAINT "PK_2389be82bf0ef3635e2014c9ef1" PRIMARY KEY ("cart_id", "gift_card_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_d38047a90f3d42f0be7909e8ae" ON "cart_gift_cards" ("cart_id") `); - await queryRunner.query(`CREATE INDEX "IDX_0fb38b6d167793192bc126d835" ON "cart_gift_cards" ("gift_card_id") `); - await queryRunner.query(`CREATE TABLE "order_discounts" ("order_id" character varying NOT NULL, "discount_id" character varying NOT NULL, CONSTRAINT "PK_a7418714ffceebc125bf6d8fcfe" PRIMARY KEY ("order_id", "discount_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_e7b488cebe333f449398769b2c" ON "order_discounts" ("order_id") `); - await queryRunner.query(`CREATE INDEX "IDX_0fc1ec4e3db9001ad60c19daf1" ON "order_discounts" ("discount_id") `); - await queryRunner.query(`CREATE TABLE "order_gift_cards" ("order_id" character varying NOT NULL, "gift_card_id" character varying NOT NULL, CONSTRAINT "PK_49a8ec66a6625d7c2e3526e05b4" PRIMARY KEY ("order_id", "gift_card_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_e62ff11e4730bb3adfead979ee" ON "order_gift_cards" ("order_id") `); - await queryRunner.query(`CREATE INDEX "IDX_f2bb9f71e95b315eb24b2b84cb" ON "order_gift_cards" ("gift_card_id") `); - await queryRunner.query(`CREATE TABLE "store_currencies" ("store_id" character varying NOT NULL, "currency_code" character varying NOT NULL, CONSTRAINT "PK_0f2bff3bccc785c320a4df836de" PRIMARY KEY ("store_id", "currency_code"))`); - await queryRunner.query(`CREATE INDEX "IDX_b4f4b63d1736689b7008980394" ON "store_currencies" ("store_id") `); - await queryRunner.query(`CREATE INDEX "IDX_82a6bbb0b527c20a0002ddcbd6" ON "store_currencies" ("currency_code") `); - await queryRunner.query(`ALTER TABLE "fulfillment_item" ADD CONSTRAINT "FK_a033f83cc6bd7701a5687ab4b38" FOREIGN KEY ("fulfillment_id") REFERENCES "fulfillment"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "fulfillment_item" ADD CONSTRAINT "FK_e13ff60e74206b747a1896212d1" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "fulfillment" ADD CONSTRAINT "FK_a52e234f729db789cf473297a5c" FOREIGN KEY ("swap_id") REFERENCES "swap"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "fulfillment" ADD CONSTRAINT "FK_f129acc85e346a10eed12b86fca" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "fulfillment" ADD CONSTRAINT "FK_beb35a6de60a6c4f91d5ae57e44" FOREIGN KEY ("provider_id") REFERENCES "fulfillment_provider"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "return_item" ADD CONSTRAINT "FK_7edab75b4fc88ea6d4f2574f087" FOREIGN KEY ("return_id") REFERENCES "return"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "return_item" ADD CONSTRAINT "FK_87774591f44564effd8039d7162" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "country" ADD CONSTRAINT "FK_b1aac8314662fa6b25569a575bb" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "region" ADD CONSTRAINT "FK_3bdd5896ec93be2f1c62a3309a5" FOREIGN KEY ("currency_code") REFERENCES "currency"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_e15811f81339e4bd8c440aebe1c" FOREIGN KEY ("currency_code") REFERENCES "currency"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_b433e27b7a83e6d12ab26b15b03" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_variant" ADD CONSTRAINT "FK_ca67dd080aac5ecf99609960cd2" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_option_value" ADD CONSTRAINT "FK_cdf4388f294b30a25c627d69fe9" FOREIGN KEY ("option_id") REFERENCES "product_option"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_option_value" ADD CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_option" ADD CONSTRAINT "FK_e634fca34f6b594b87fdbee95f6" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_option_requirement" ADD CONSTRAINT "FK_012a62ba743e427b5ebe9dee18e" FOREIGN KEY ("shipping_option_id") REFERENCES "shipping_option"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_option" ADD CONSTRAINT "FK_5c58105f1752fca0f4ce69f4663" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_option" ADD CONSTRAINT "FK_c951439af4c98bf2bd7fb8726cd" FOREIGN KEY ("profile_id") REFERENCES "shipping_profile"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_option" ADD CONSTRAINT "FK_a0e206bfaed3cb63c1860917347" FOREIGN KEY ("provider_id") REFERENCES "fulfillment_provider"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product" ADD CONSTRAINT "FK_80823b7ae866dc5acae2dac6d2c" FOREIGN KEY ("profile_id") REFERENCES "shipping_profile"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount" ADD CONSTRAINT "FK_ac2c280de3701b2d66f6817f760" FOREIGN KEY ("rule_id") REFERENCES "discount_rule"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount" ADD CONSTRAINT "FK_2250c5d9e975987ab212f61a663" FOREIGN KEY ("parent_discount_id") REFERENCES "discount"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "payment_session" ADD CONSTRAINT "FK_d25ba0787e1510ddc5d442ebcfa" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "payment" ADD CONSTRAINT "FK_c17aff091441b7c25ec3d68d36c" FOREIGN KEY ("swap_id") REFERENCES "swap"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "payment" ADD CONSTRAINT "FK_4665f17abc1e81dd58330e58542" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "payment" ADD CONSTRAINT "FK_f5221735ace059250daac9d9803" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "payment" ADD CONSTRAINT "FK_f41553459a4b1491c9893ebc921" FOREIGN KEY ("currency_code") REFERENCES "currency"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "gift_card" ADD CONSTRAINT "FK_b6bcf8c3903097b84e85154eed3" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "gift_card" ADD CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart" ADD CONSTRAINT "FK_6b9c66b5e36f7c827dfaa092f94" FOREIGN KEY ("billing_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart" ADD CONSTRAINT "FK_ced15a9a695d2b5db9dabce763d" FOREIGN KEY ("shipping_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart" ADD CONSTRAINT "FK_484c329f4783be4e18e5e2ff090" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart" ADD CONSTRAINT "FK_242205c81c1152fab1b6e848470" FOREIGN KEY ("customer_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart" ADD CONSTRAINT "FK_9d1a161434c610aae7c3df2dc7e" FOREIGN KEY ("payment_id") REFERENCES "payment"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_5267705a43d547e232535b656c2" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_d92993a7d554d84571f4eea1d13" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_fb94fa8d5ca940daa2a58139f86" FOREIGN KEY ("swap_id") REFERENCES "swap"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_1d9ad62038998c3a85c77a53cfb" FOREIGN KEY ("return_id") REFERENCES "return"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_fc963e94854bff2714ca84cd193" FOREIGN KEY ("shipping_option_id") REFERENCES "shipping_option"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "return" ADD CONSTRAINT "FK_bad82d7bff2b08b87094bfac3d6" FOREIGN KEY ("swap_id") REFERENCES "swap"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "return" ADD CONSTRAINT "FK_d4bd17f918fc6c332b74a368c36" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "swap" ADD CONSTRAINT "FK_52dd74e8c989aa5665ad2852b8b" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "swap" ADD CONSTRAINT "FK_f5189d38b3d3bd496618bf54c57" FOREIGN KEY ("shipping_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "swap" ADD CONSTRAINT "FK_402e8182bc553e082f6380020b4" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "line_item" ADD CONSTRAINT "FK_27283ee631862266d0f1c680646" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "line_item" ADD CONSTRAINT "FK_43a2b24495fe1d9fc2a9c835bc7" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "line_item" ADD CONSTRAINT "FK_3fa354d8d1233ff81097b2fcb6b" FOREIGN KEY ("swap_id") REFERENCES "swap"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "line_item" ADD CONSTRAINT "FK_5371cbaa3be5200f373d24e3d5b" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "gift_card_transaction" ADD CONSTRAINT "FK_3ff5597f1d7e02bba41541846f4" FOREIGN KEY ("gift_card_id") REFERENCES "gift_card"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "gift_card_transaction" ADD CONSTRAINT "FK_d7d441b81012f87d4265fa57d24" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "refund" ADD CONSTRAINT "FK_eec9d9af4ca098e19ea6b499eaa" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_c99a206eb11ad45f6b7f04f2dcc" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_cd7812c96209c5bdd48a6b858b0" FOREIGN KEY ("customer_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_5568d3b9ce9f7abeeb37511ecf2" FOREIGN KEY ("billing_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_19b0c6293443d1b464f604c3316" FOREIGN KEY ("shipping_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_e1fcce2b18dbcdbe0a5ba9a68b8" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_717a141f96b76d794d409f38129" FOREIGN KEY ("currency_code") REFERENCES "currency"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "customer" ADD CONSTRAINT "FK_8abe81b9aac151ae60bf507ad15" FOREIGN KEY ("billing_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "address" ADD CONSTRAINT "FK_9c9614b2f9d01665800ea8dbff7" FOREIGN KEY ("customer_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "address" ADD CONSTRAINT "FK_6df8c6bf969a51d24c1980c4ff4" FOREIGN KEY ("country_code") REFERENCES "country"("iso_2") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "store" ADD CONSTRAINT "FK_55beebaa09e947cccca554af222" FOREIGN KEY ("default_currency_code") REFERENCES "currency"("code") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "region_payment_providers" ADD CONSTRAINT "FK_8aaa78ba90d3802edac317df869" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "region_payment_providers" ADD CONSTRAINT "FK_3a6947180aeec283cd92c59ebb0" FOREIGN KEY ("provider_id") REFERENCES "payment_provider"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "region_fulfillment_providers" ADD CONSTRAINT "FK_c556e14eff4d6f03db593df955e" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "region_fulfillment_providers" ADD CONSTRAINT "FK_37f361c38a18d12a3fa3158d0cf" FOREIGN KEY ("provider_id") REFERENCES "fulfillment_provider"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_images" ADD CONSTRAINT "FK_4f166bb8c2bfcef2498d97b4068" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "product_images" ADD CONSTRAINT "FK_2212515ba306c79f42c46a99db7" FOREIGN KEY ("image_id") REFERENCES "image"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount_rule_products" ADD CONSTRAINT "FK_4e0739e5f0244c08d41174ca08a" FOREIGN KEY ("discount_rule_id") REFERENCES "discount_rule"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount_rule_products" ADD CONSTRAINT "FK_be66106a673b88a81c603abe7eb" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount_regions" ADD CONSTRAINT "FK_f4194aa81073f3fab8aa86906ff" FOREIGN KEY ("discount_id") REFERENCES "discount"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "discount_regions" ADD CONSTRAINT "FK_a21a7ffbe420d492eb46c305fec" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart_discounts" ADD CONSTRAINT "FK_6680319ebe1f46d18f106191d59" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart_discounts" ADD CONSTRAINT "FK_8df75ef4f35f217768dc1135458" FOREIGN KEY ("discount_id") REFERENCES "discount"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart_gift_cards" ADD CONSTRAINT "FK_d38047a90f3d42f0be7909e8aea" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "cart_gift_cards" ADD CONSTRAINT "FK_0fb38b6d167793192bc126d835e" FOREIGN KEY ("gift_card_id") REFERENCES "gift_card"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order_discounts" ADD CONSTRAINT "FK_e7b488cebe333f449398769b2cc" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order_discounts" ADD CONSTRAINT "FK_0fc1ec4e3db9001ad60c19daf16" FOREIGN KEY ("discount_id") REFERENCES "discount"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order_gift_cards" ADD CONSTRAINT "FK_e62ff11e4730bb3adfead979ee2" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order_gift_cards" ADD CONSTRAINT "FK_f2bb9f71e95b315eb24b2b84cb3" FOREIGN KEY ("gift_card_id") REFERENCES "gift_card"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "store_currencies" ADD CONSTRAINT "FK_b4f4b63d1736689b7008980394c" FOREIGN KEY ("store_id") REFERENCES "store"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "store_currencies" ADD CONSTRAINT "FK_82a6bbb0b527c20a0002ddcbd60" FOREIGN KEY ("currency_code") REFERENCES "currency"("code") ON DELETE CASCADE ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "store_currencies" DROP CONSTRAINT "FK_82a6bbb0b527c20a0002ddcbd60"`); - await queryRunner.query(`ALTER TABLE "store_currencies" DROP CONSTRAINT "FK_b4f4b63d1736689b7008980394c"`); - await queryRunner.query(`ALTER TABLE "order_gift_cards" DROP CONSTRAINT "FK_f2bb9f71e95b315eb24b2b84cb3"`); - await queryRunner.query(`ALTER TABLE "order_gift_cards" DROP CONSTRAINT "FK_e62ff11e4730bb3adfead979ee2"`); - await queryRunner.query(`ALTER TABLE "order_discounts" DROP CONSTRAINT "FK_0fc1ec4e3db9001ad60c19daf16"`); - await queryRunner.query(`ALTER TABLE "order_discounts" DROP CONSTRAINT "FK_e7b488cebe333f449398769b2cc"`); - await queryRunner.query(`ALTER TABLE "cart_gift_cards" DROP CONSTRAINT "FK_0fb38b6d167793192bc126d835e"`); - await queryRunner.query(`ALTER TABLE "cart_gift_cards" DROP CONSTRAINT "FK_d38047a90f3d42f0be7909e8aea"`); - await queryRunner.query(`ALTER TABLE "cart_discounts" DROP CONSTRAINT "FK_8df75ef4f35f217768dc1135458"`); - await queryRunner.query(`ALTER TABLE "cart_discounts" DROP CONSTRAINT "FK_6680319ebe1f46d18f106191d59"`); - await queryRunner.query(`ALTER TABLE "discount_regions" DROP CONSTRAINT "FK_a21a7ffbe420d492eb46c305fec"`); - await queryRunner.query(`ALTER TABLE "discount_regions" DROP CONSTRAINT "FK_f4194aa81073f3fab8aa86906ff"`); - await queryRunner.query(`ALTER TABLE "discount_rule_products" DROP CONSTRAINT "FK_be66106a673b88a81c603abe7eb"`); - await queryRunner.query(`ALTER TABLE "discount_rule_products" DROP CONSTRAINT "FK_4e0739e5f0244c08d41174ca08a"`); - await queryRunner.query(`ALTER TABLE "product_images" DROP CONSTRAINT "FK_2212515ba306c79f42c46a99db7"`); - await queryRunner.query(`ALTER TABLE "product_images" DROP CONSTRAINT "FK_4f166bb8c2bfcef2498d97b4068"`); - await queryRunner.query(`ALTER TABLE "region_fulfillment_providers" DROP CONSTRAINT "FK_37f361c38a18d12a3fa3158d0cf"`); - await queryRunner.query(`ALTER TABLE "region_fulfillment_providers" DROP CONSTRAINT "FK_c556e14eff4d6f03db593df955e"`); - await queryRunner.query(`ALTER TABLE "region_payment_providers" DROP CONSTRAINT "FK_3a6947180aeec283cd92c59ebb0"`); - await queryRunner.query(`ALTER TABLE "region_payment_providers" DROP CONSTRAINT "FK_8aaa78ba90d3802edac317df869"`); - await queryRunner.query(`ALTER TABLE "store" DROP CONSTRAINT "FK_55beebaa09e947cccca554af222"`); - await queryRunner.query(`ALTER TABLE "address" DROP CONSTRAINT "FK_6df8c6bf969a51d24c1980c4ff4"`); - await queryRunner.query(`ALTER TABLE "address" DROP CONSTRAINT "FK_9c9614b2f9d01665800ea8dbff7"`); - await queryRunner.query(`ALTER TABLE "customer" DROP CONSTRAINT "FK_8abe81b9aac151ae60bf507ad15"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_717a141f96b76d794d409f38129"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_e1fcce2b18dbcdbe0a5ba9a68b8"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_19b0c6293443d1b464f604c3316"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_5568d3b9ce9f7abeeb37511ecf2"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_cd7812c96209c5bdd48a6b858b0"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_c99a206eb11ad45f6b7f04f2dcc"`); - await queryRunner.query(`ALTER TABLE "refund" DROP CONSTRAINT "FK_eec9d9af4ca098e19ea6b499eaa"`); - await queryRunner.query(`ALTER TABLE "gift_card_transaction" DROP CONSTRAINT "FK_d7d441b81012f87d4265fa57d24"`); - await queryRunner.query(`ALTER TABLE "gift_card_transaction" DROP CONSTRAINT "FK_3ff5597f1d7e02bba41541846f4"`); - await queryRunner.query(`ALTER TABLE "line_item" DROP CONSTRAINT "FK_5371cbaa3be5200f373d24e3d5b"`); - await queryRunner.query(`ALTER TABLE "line_item" DROP CONSTRAINT "FK_3fa354d8d1233ff81097b2fcb6b"`); - await queryRunner.query(`ALTER TABLE "line_item" DROP CONSTRAINT "FK_43a2b24495fe1d9fc2a9c835bc7"`); - await queryRunner.query(`ALTER TABLE "line_item" DROP CONSTRAINT "FK_27283ee631862266d0f1c680646"`); - await queryRunner.query(`ALTER TABLE "swap" DROP CONSTRAINT "FK_402e8182bc553e082f6380020b4"`); - await queryRunner.query(`ALTER TABLE "swap" DROP CONSTRAINT "FK_f5189d38b3d3bd496618bf54c57"`); - await queryRunner.query(`ALTER TABLE "swap" DROP CONSTRAINT "FK_52dd74e8c989aa5665ad2852b8b"`); - await queryRunner.query(`ALTER TABLE "return" DROP CONSTRAINT "FK_d4bd17f918fc6c332b74a368c36"`); - await queryRunner.query(`ALTER TABLE "return" DROP CONSTRAINT "FK_bad82d7bff2b08b87094bfac3d6"`); - await queryRunner.query(`ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_fc963e94854bff2714ca84cd193"`); - await queryRunner.query(`ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_1d9ad62038998c3a85c77a53cfb"`); - await queryRunner.query(`ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_fb94fa8d5ca940daa2a58139f86"`); - await queryRunner.query(`ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_d92993a7d554d84571f4eea1d13"`); - await queryRunner.query(`ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_5267705a43d547e232535b656c2"`); - await queryRunner.query(`ALTER TABLE "cart" DROP CONSTRAINT "FK_9d1a161434c610aae7c3df2dc7e"`); - await queryRunner.query(`ALTER TABLE "cart" DROP CONSTRAINT "FK_242205c81c1152fab1b6e848470"`); - await queryRunner.query(`ALTER TABLE "cart" DROP CONSTRAINT "FK_484c329f4783be4e18e5e2ff090"`); - await queryRunner.query(`ALTER TABLE "cart" DROP CONSTRAINT "FK_ced15a9a695d2b5db9dabce763d"`); - await queryRunner.query(`ALTER TABLE "cart" DROP CONSTRAINT "FK_6b9c66b5e36f7c827dfaa092f94"`); - await queryRunner.query(`ALTER TABLE "gift_card" DROP CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0"`); - await queryRunner.query(`ALTER TABLE "gift_card" DROP CONSTRAINT "FK_b6bcf8c3903097b84e85154eed3"`); - await queryRunner.query(`ALTER TABLE "payment" DROP CONSTRAINT "FK_f41553459a4b1491c9893ebc921"`); - await queryRunner.query(`ALTER TABLE "payment" DROP CONSTRAINT "FK_f5221735ace059250daac9d9803"`); - await queryRunner.query(`ALTER TABLE "payment" DROP CONSTRAINT "FK_4665f17abc1e81dd58330e58542"`); - await queryRunner.query(`ALTER TABLE "payment" DROP CONSTRAINT "FK_c17aff091441b7c25ec3d68d36c"`); - await queryRunner.query(`ALTER TABLE "payment_session" DROP CONSTRAINT "FK_d25ba0787e1510ddc5d442ebcfa"`); - await queryRunner.query(`ALTER TABLE "discount" DROP CONSTRAINT "FK_2250c5d9e975987ab212f61a663"`); - await queryRunner.query(`ALTER TABLE "discount" DROP CONSTRAINT "FK_ac2c280de3701b2d66f6817f760"`); - await queryRunner.query(`ALTER TABLE "product" DROP CONSTRAINT "FK_80823b7ae866dc5acae2dac6d2c"`); - await queryRunner.query(`ALTER TABLE "shipping_option" DROP CONSTRAINT "FK_a0e206bfaed3cb63c1860917347"`); - await queryRunner.query(`ALTER TABLE "shipping_option" DROP CONSTRAINT "FK_c951439af4c98bf2bd7fb8726cd"`); - await queryRunner.query(`ALTER TABLE "shipping_option" DROP CONSTRAINT "FK_5c58105f1752fca0f4ce69f4663"`); - await queryRunner.query(`ALTER TABLE "shipping_option_requirement" DROP CONSTRAINT "FK_012a62ba743e427b5ebe9dee18e"`); - await queryRunner.query(`ALTER TABLE "product_option" DROP CONSTRAINT "FK_e634fca34f6b594b87fdbee95f6"`); - await queryRunner.query(`ALTER TABLE "product_option_value" DROP CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01"`); - await queryRunner.query(`ALTER TABLE "product_option_value" DROP CONSTRAINT "FK_cdf4388f294b30a25c627d69fe9"`); - await queryRunner.query(`ALTER TABLE "product_variant" DROP CONSTRAINT "FK_ca67dd080aac5ecf99609960cd2"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_b433e27b7a83e6d12ab26b15b03"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_e15811f81339e4bd8c440aebe1c"`); - await queryRunner.query(`ALTER TABLE "region" DROP CONSTRAINT "FK_3bdd5896ec93be2f1c62a3309a5"`); - await queryRunner.query(`ALTER TABLE "country" DROP CONSTRAINT "FK_b1aac8314662fa6b25569a575bb"`); - await queryRunner.query(`ALTER TABLE "return_item" DROP CONSTRAINT "FK_87774591f44564effd8039d7162"`); - await queryRunner.query(`ALTER TABLE "return_item" DROP CONSTRAINT "FK_7edab75b4fc88ea6d4f2574f087"`); - await queryRunner.query(`ALTER TABLE "fulfillment" DROP CONSTRAINT "FK_beb35a6de60a6c4f91d5ae57e44"`); - await queryRunner.query(`ALTER TABLE "fulfillment" DROP CONSTRAINT "FK_f129acc85e346a10eed12b86fca"`); - await queryRunner.query(`ALTER TABLE "fulfillment" DROP CONSTRAINT "FK_a52e234f729db789cf473297a5c"`); - await queryRunner.query(`ALTER TABLE "fulfillment_item" DROP CONSTRAINT "FK_e13ff60e74206b747a1896212d1"`); - await queryRunner.query(`ALTER TABLE "fulfillment_item" DROP CONSTRAINT "FK_a033f83cc6bd7701a5687ab4b38"`); - await queryRunner.query(`DROP INDEX "IDX_82a6bbb0b527c20a0002ddcbd6"`); - await queryRunner.query(`DROP INDEX "IDX_b4f4b63d1736689b7008980394"`); - await queryRunner.query(`DROP TABLE "store_currencies"`); - await queryRunner.query(`DROP INDEX "IDX_f2bb9f71e95b315eb24b2b84cb"`); - await queryRunner.query(`DROP INDEX "IDX_e62ff11e4730bb3adfead979ee"`); - await queryRunner.query(`DROP TABLE "order_gift_cards"`); - await queryRunner.query(`DROP INDEX "IDX_0fc1ec4e3db9001ad60c19daf1"`); - await queryRunner.query(`DROP INDEX "IDX_e7b488cebe333f449398769b2c"`); - await queryRunner.query(`DROP TABLE "order_discounts"`); - await queryRunner.query(`DROP INDEX "IDX_0fb38b6d167793192bc126d835"`); - await queryRunner.query(`DROP INDEX "IDX_d38047a90f3d42f0be7909e8ae"`); - await queryRunner.query(`DROP TABLE "cart_gift_cards"`); - await queryRunner.query(`DROP INDEX "IDX_8df75ef4f35f217768dc113545"`); - await queryRunner.query(`DROP INDEX "IDX_6680319ebe1f46d18f106191d5"`); - await queryRunner.query(`DROP TABLE "cart_discounts"`); - await queryRunner.query(`DROP INDEX "IDX_a21a7ffbe420d492eb46c305fe"`); - await queryRunner.query(`DROP INDEX "IDX_f4194aa81073f3fab8aa86906f"`); - await queryRunner.query(`DROP TABLE "discount_regions"`); - await queryRunner.query(`DROP INDEX "IDX_be66106a673b88a81c603abe7e"`); - await queryRunner.query(`DROP INDEX "IDX_4e0739e5f0244c08d41174ca08"`); - await queryRunner.query(`DROP TABLE "discount_rule_products"`); - await queryRunner.query(`DROP INDEX "IDX_2212515ba306c79f42c46a99db"`); - await queryRunner.query(`DROP INDEX "IDX_4f166bb8c2bfcef2498d97b406"`); - await queryRunner.query(`DROP TABLE "product_images"`); - await queryRunner.query(`DROP INDEX "IDX_37f361c38a18d12a3fa3158d0c"`); - await queryRunner.query(`DROP INDEX "IDX_c556e14eff4d6f03db593df955"`); - await queryRunner.query(`DROP TABLE "region_fulfillment_providers"`); - await queryRunner.query(`DROP INDEX "IDX_3a6947180aeec283cd92c59ebb"`); - await queryRunner.query(`DROP INDEX "IDX_8aaa78ba90d3802edac317df86"`); - await queryRunner.query(`DROP TABLE "region_payment_providers"`); - await queryRunner.query(`DROP INDEX "IDX_e12875dfb3b1d92d7d7c5377e2"`); - await queryRunner.query(`DROP TABLE "user"`); - await queryRunner.query(`DROP TABLE "store"`); - await queryRunner.query(`DROP TABLE "staged_job"`); - await queryRunner.query(`DROP INDEX "IDX_c49c061b1a686843c5d673506f"`); - await queryRunner.query(`DROP TABLE "oauth"`); - await queryRunner.query(`DROP INDEX "IDX_a421bf4588d0004a9b0c0fe84f"`); - await queryRunner.query(`DROP TABLE "idempotency_key"`); - await queryRunner.query(`DROP TABLE "address"`); - await queryRunner.query(`DROP INDEX "IDX_fdb2f3ad8115da4c7718109a6e"`); - await queryRunner.query(`DROP TABLE "customer"`); - await queryRunner.query(`DROP TABLE "order"`); - await queryRunner.query(`DROP TYPE "order_payment_status_enum"`); - await queryRunner.query(`DROP TYPE "order_fulfillment_status_enum"`); - await queryRunner.query(`DROP TYPE "order_status_enum"`); - await queryRunner.query(`DROP TABLE "refund"`); - await queryRunner.query(`DROP TYPE "refund_reason_enum"`); - await queryRunner.query(`DROP TABLE "gift_card_transaction"`); - await queryRunner.query(`DROP INDEX "IDX_5371cbaa3be5200f373d24e3d5"`); - await queryRunner.query(`DROP INDEX "IDX_3fa354d8d1233ff81097b2fcb6"`); - await queryRunner.query(`DROP INDEX "IDX_43a2b24495fe1d9fc2a9c835bc"`); - await queryRunner.query(`DROP INDEX "IDX_27283ee631862266d0f1c68064"`); - await queryRunner.query(`DROP TABLE "line_item"`); - await queryRunner.query(`DROP TABLE "swap"`); - await queryRunner.query(`DROP TYPE "swap_payment_status_enum"`); - await queryRunner.query(`DROP TYPE "swap_fulfillment_status_enum"`); - await queryRunner.query(`DROP TABLE "return"`); - await queryRunner.query(`DROP TYPE "return_status_enum"`); - await queryRunner.query(`DROP INDEX "IDX_1d9ad62038998c3a85c77a53cf"`); - await queryRunner.query(`DROP INDEX "IDX_fb94fa8d5ca940daa2a58139f8"`); - await queryRunner.query(`DROP INDEX "IDX_d92993a7d554d84571f4eea1d1"`); - await queryRunner.query(`DROP INDEX "IDX_5267705a43d547e232535b656c"`); - await queryRunner.query(`DROP INDEX "IDX_fc963e94854bff2714ca84cd19"`); - await queryRunner.query(`DROP TABLE "shipping_method"`); - await queryRunner.query(`DROP TABLE "cart"`); - await queryRunner.query(`DROP TYPE "cart_type_enum"`); - await queryRunner.query(`DROP INDEX "IDX_53cb5605fa42e82b4d47b47bda"`); - await queryRunner.query(`DROP TABLE "gift_card"`); - await queryRunner.query(`DROP TABLE "payment"`); - await queryRunner.query(`DROP TABLE "payment_session"`); - await queryRunner.query(`DROP TYPE "payment_session_status_enum"`); - await queryRunner.query(`DROP INDEX "IDX_087926f6fec32903be3c8eedfa"`); - await queryRunner.query(`DROP TABLE "discount"`); - await queryRunner.query(`DROP TABLE "discount_rule"`); - await queryRunner.query(`DROP TYPE "discount_rule_allocation_enum"`); - await queryRunner.query(`DROP TYPE "discount_rule_type_enum"`); - await queryRunner.query(`DROP INDEX "IDX_db7355f7bd36c547c8a4f539e5"`); - await queryRunner.query(`DROP TABLE "product"`); - await queryRunner.query(`DROP TABLE "shipping_profile"`); - await queryRunner.query(`DROP TYPE "shipping_profile_type_enum"`); - await queryRunner.query(`DROP TABLE "shipping_option"`); - await queryRunner.query(`DROP TYPE "shipping_option_price_type_enum"`); - await queryRunner.query(`DROP TABLE "shipping_option_requirement"`); - await queryRunner.query(`DROP TYPE "shipping_option_requirement_type_enum"`); - await queryRunner.query(`DROP TABLE "product_option"`); - await queryRunner.query(`DROP INDEX "IDX_cdf4388f294b30a25c627d69fe"`); - await queryRunner.query(`DROP TABLE "product_option_value"`); - await queryRunner.query(`DROP INDEX "IDX_a0a3f124dc5b167622217fee02"`); - await queryRunner.query(`DROP INDEX "IDX_7124082c8846a06a857cca386c"`); - await queryRunner.query(`DROP INDEX "IDX_9db95c4b71f632fc93ecbc3d8b"`); - await queryRunner.query(`DROP INDEX "IDX_f4dc2c0888b66d547c175f090e"`); - await queryRunner.query(`DROP TABLE "product_variant"`); - await queryRunner.query(`DROP TABLE "money_amount"`); - await queryRunner.query(`DROP TABLE "image"`); - await queryRunner.query(`DROP TABLE "region"`); - await queryRunner.query(`DROP TABLE "payment_provider"`); - await queryRunner.query(`DROP INDEX "IDX_e78901b1131eaf8203d9b1cb5f"`); - await queryRunner.query(`DROP TABLE "country"`); - await queryRunner.query(`DROP TABLE "currency"`); - await queryRunner.query(`DROP TABLE "return_item"`); - await queryRunner.query(`DROP TABLE "fulfillment"`); - await queryRunner.query(`DROP TABLE "fulfillment_item"`); - await queryRunner.query(`DROP TABLE "fulfillment_provider"`); - } - -} diff --git a/packages/medusa/src/migrations/1611063174563-countries_currencies.ts b/packages/medusa/src/migrations/1611063174563-countries_currencies.ts deleted file mode 100644 index 1f4a05e8aa..0000000000 --- a/packages/medusa/src/migrations/1611063174563-countries_currencies.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" -import { countries } from "../utils/countries" -import { currencies } from "../utils/currencies" - -export class countriesCurrencies1611063174563 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - for (const c of countries) { - const query = `INSERT INTO "country" ("iso_2", "iso_3", "num_code", "name", "display_name") VALUES ($1, $2, $3, $4, $5)` - - const iso2 = c.alpha2.toLowerCase() - const iso3 = c.alpha3.toLowerCase() - const numeric = c.numeric - const name = c.name.toUpperCase() - const display = c.name - - await queryRunner.query(query, [iso2, iso3, numeric, name, display]) - } - - for (const [_, c] of Object.entries(currencies)) { - const query = `INSERT INTO "currency" ("code", "symbol", "symbol_native", "name") VALUES ($1, $2, $3, $4)` - - const code = c.code.toLowerCase() - const sym = c.symbol - const nat = c.symbol_native - const name = c.name - - await queryRunner.query(query, [code, sym, nat, name]) - } - } - - public async down(queryRunner: QueryRunner): Promise { - for (const c of countries) { - await queryRunner.query( - `DELETE FROM "country" WHERE iso_2 = '${c.alpha2}'` - ) - } - - for (const [_, c] of Object.entries(currencies)) { - await queryRunner.query( - `DELETE FROM "currency" WHERE code = '${c.code.toLowerCase()}'` - ) - } - } -} diff --git a/packages/medusa/src/migrations/1612284947120-claims.ts b/packages/medusa/src/migrations/1612284947120-claims.ts deleted file mode 100644 index 3c9fb1e052..0000000000 --- a/packages/medusa/src/migrations/1612284947120-claims.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class claims1612284947120 implements MigrationInterface { - name = "claims1612284947120" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "shipping_method" DROP CONSTRAINT "CHK_3c00b878c1426d119cd70aa065"` - ) - await queryRunner.query( - `CREATE TABLE "claim_image" ("id" character varying NOT NULL, "claim_item_id" character varying NOT NULL, "url" 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, "metadata" jsonb, CONSTRAINT "PK_7c49e44bfe8840ca7d917890101" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "claim_tag" ("id" character varying NOT NULL, "value" 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, "metadata" jsonb, CONSTRAINT "PK_7761180541142a5926501018d34" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ec10c54769877840c132260e4a" ON "claim_tag" ("value") ` - ) - await queryRunner.query( - `CREATE TYPE "claim_item_reason_enum" AS ENUM('missing_item', 'wrong_item', 'production_failure', 'other')` - ) - await queryRunner.query( - `CREATE TABLE "claim_item" ("id" character varying NOT NULL, "claim_order_id" character varying NOT NULL, "item_id" character varying NOT NULL, "variant_id" character varying NOT NULL, "reason" "claim_item_reason_enum" NOT NULL, "note" character varying, "quantity" integer 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, "metadata" jsonb, CONSTRAINT "PK_5679662039bc4c7c6bc7fa1be2d" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_900a9c3834257304396b2b0fe7" ON "claim_item" ("claim_order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_6e0cad0daef76bb642675910b9" ON "claim_item" ("item_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_64980511ca32c8e92b417644af" ON "claim_item" ("variant_id") ` - ) - await queryRunner.query( - `CREATE TYPE "claim_order_payment_status_enum" AS ENUM('na', 'not_refunded', 'refunded')` - ) - await queryRunner.query( - `CREATE TYPE "claim_order_fulfillment_status_enum" AS ENUM('not_fulfilled', 'partially_fulfilled', 'fulfilled', 'partially_shipped', 'shipped', 'partially_returned', 'returned', 'canceled', 'requires_action')` - ) - await queryRunner.query( - `CREATE TYPE "claim_order_type_enum" AS ENUM('refund', 'replace')` - ) - await queryRunner.query( - `CREATE TABLE "claim_order" ("id" character varying NOT NULL, "payment_status" "claim_order_payment_status_enum" NOT NULL DEFAULT 'na', "fulfillment_status" "claim_order_fulfillment_status_enum" NOT NULL DEFAULT 'not_fulfilled', "type" "claim_order_type_enum" NOT NULL, "order_id" character varying NOT NULL, "shipping_address_id" character varying, "refund_amount" integer, "canceled_at" TIMESTAMP WITH TIME ZONE, "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, "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "PK_8981f5595a4424021466aa4c7a4" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "claim_item_tags" ("item_id" character varying NOT NULL, "tag_id" character varying NOT NULL, CONSTRAINT "PK_54ab8ce0f7e99167068188fbd81" PRIMARY KEY ("item_id", "tag_id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c2c0f3edf39515bd15432afe6e" ON "claim_item_tags" ("item_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_dc9bbf9fcb9ba458d25d512811" ON "claim_item_tags" ("tag_id") ` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" ADD "claim_order_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "return" ADD "claim_order_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "return" ADD CONSTRAINT "UQ_71773d56eb2bacb922bc3283398" UNIQUE ("claim_order_id")` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" ADD "claim_order_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "line_item" ADD "claim_order_id" character varying` - ) - await queryRunner.query( - `ALTER TYPE "refund_reason_enum" RENAME TO "refund_reason_enum_old"` - ) - await queryRunner.query( - `CREATE TYPE "refund_reason_enum" AS ENUM('discount', 'return', 'swap', 'claim', 'other')` - ) - await queryRunner.query( - `ALTER TABLE "refund" ALTER COLUMN "reason" TYPE "refund_reason_enum" USING "reason"::"text"::"refund_reason_enum"` - ) - await queryRunner.query(`DROP TYPE "refund_reason_enum_old"`) - await queryRunner.query(`COMMENT ON COLUMN "refund"."reason" IS NULL`) - await queryRunner.query( - `CREATE INDEX "IDX_d783a66d1c91c0858752c933e6" ON "shipping_method" ("claim_order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_118e3c48f09a7728f41023c94e" ON "line_item" ("claim_order_id") ` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" ADD CONSTRAINT "CHK_a7020b08665bbd64d84a6641cf" CHECK ("claim_order_id" IS NOT NULL OR "order_id" IS NOT NULL OR "cart_id" IS NOT NULL OR "swap_id" IS NOT NULL OR "return_id" IS NOT NULL)` - ) - await queryRunner.query( - `ALTER TABLE "claim_image" ADD CONSTRAINT "FK_21cbfedd83d736d86f4c6f4ce56" FOREIGN KEY ("claim_item_id") REFERENCES "claim_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" ADD CONSTRAINT "FK_900a9c3834257304396b2b0fe7c" FOREIGN KEY ("claim_order_id") REFERENCES "claim_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" ADD CONSTRAINT "FK_6e0cad0daef76bb642675910b9d" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" ADD CONSTRAINT "FK_64980511ca32c8e92b417644afa" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" ADD CONSTRAINT "FK_d783a66d1c91c0858752c933e68" FOREIGN KEY ("claim_order_id") REFERENCES "claim_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "return" ADD CONSTRAINT "FK_71773d56eb2bacb922bc3283398" FOREIGN KEY ("claim_order_id") REFERENCES "claim_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_order" ADD CONSTRAINT "FK_f49e3974465d3c3a33d449d3f31" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_order" ADD CONSTRAINT "FK_017d58bf8260c6e1a2588d258e2" FOREIGN KEY ("shipping_address_id") REFERENCES "address"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" ADD CONSTRAINT "FK_d73e55964e0ff2db8f03807d52e" FOREIGN KEY ("claim_order_id") REFERENCES "claim_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "line_item" ADD CONSTRAINT "FK_118e3c48f09a7728f41023c94ef" FOREIGN KEY ("claim_order_id") REFERENCES "claim_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_item_tags" ADD CONSTRAINT "FK_c2c0f3edf39515bd15432afe6e5" FOREIGN KEY ("item_id") REFERENCES "claim_item"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "claim_item_tags" ADD CONSTRAINT "FK_dc9bbf9fcb9ba458d25d512811b" FOREIGN KEY ("tag_id") REFERENCES "claim_tag"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "claim_item_tags" DROP CONSTRAINT "FK_dc9bbf9fcb9ba458d25d512811b"` - ) - await queryRunner.query( - `ALTER TABLE "claim_item_tags" DROP CONSTRAINT "FK_c2c0f3edf39515bd15432afe6e5"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP CONSTRAINT "FK_118e3c48f09a7728f41023c94ef"` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" DROP CONSTRAINT "FK_d73e55964e0ff2db8f03807d52e"` - ) - await queryRunner.query( - `ALTER TABLE "claim_order" DROP CONSTRAINT "FK_017d58bf8260c6e1a2588d258e2"` - ) - await queryRunner.query( - `ALTER TABLE "claim_order" DROP CONSTRAINT "FK_f49e3974465d3c3a33d449d3f31"` - ) - await queryRunner.query( - `ALTER TABLE "return" DROP CONSTRAINT "FK_71773d56eb2bacb922bc3283398"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" DROP CONSTRAINT "FK_d783a66d1c91c0858752c933e68"` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" DROP CONSTRAINT "FK_64980511ca32c8e92b417644afa"` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" DROP CONSTRAINT "FK_6e0cad0daef76bb642675910b9d"` - ) - await queryRunner.query( - `ALTER TABLE "claim_item" DROP CONSTRAINT "FK_900a9c3834257304396b2b0fe7c"` - ) - await queryRunner.query( - `ALTER TABLE "claim_image" DROP CONSTRAINT "FK_21cbfedd83d736d86f4c6f4ce56"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" DROP CONSTRAINT "CHK_a7020b08665bbd64d84a6641cf"` - ) - await queryRunner.query(`DROP INDEX "IDX_118e3c48f09a7728f41023c94e"`) - await queryRunner.query(`DROP INDEX "IDX_d783a66d1c91c0858752c933e6"`) - await queryRunner.query(`COMMENT ON COLUMN "refund"."reason" IS NULL`) - await queryRunner.query( - `CREATE TYPE "refund_reason_enum_old" AS ENUM('discount', 'return', 'swap', 'other')` - ) - await queryRunner.query( - `ALTER TABLE "refund" ALTER COLUMN "reason" TYPE "refund_reason_enum_old" USING "reason"::"text"::"refund_reason_enum_old"` - ) - await queryRunner.query(`DROP TYPE "refund_reason_enum"`) - await queryRunner.query( - `ALTER TYPE "refund_reason_enum_old" RENAME TO "refund_reason_enum"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP COLUMN "claim_order_id"` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" DROP COLUMN "claim_order_id"` - ) - await queryRunner.query( - `ALTER TABLE "return" DROP CONSTRAINT "UQ_71773d56eb2bacb922bc3283398"` - ) - await queryRunner.query(`ALTER TABLE "return" DROP COLUMN "claim_order_id"`) - await queryRunner.query( - `ALTER TABLE "shipping_method" DROP COLUMN "claim_order_id"` - ) - await queryRunner.query(`DROP INDEX "IDX_dc9bbf9fcb9ba458d25d512811"`) - await queryRunner.query(`DROP INDEX "IDX_c2c0f3edf39515bd15432afe6e"`) - await queryRunner.query(`DROP TABLE "claim_item_tags"`) - await queryRunner.query(`DROP TABLE "claim_order"`) - await queryRunner.query(`DROP TYPE "claim_order_type_enum"`) - await queryRunner.query(`DROP TYPE "claim_order_fulfillment_status_enum"`) - await queryRunner.query(`DROP TYPE "claim_order_payment_status_enum"`) - await queryRunner.query(`DROP INDEX "IDX_64980511ca32c8e92b417644af"`) - await queryRunner.query(`DROP INDEX "IDX_6e0cad0daef76bb642675910b9"`) - await queryRunner.query(`DROP INDEX "IDX_900a9c3834257304396b2b0fe7"`) - await queryRunner.query(`DROP TABLE "claim_item"`) - await queryRunner.query(`DROP TYPE "claim_item_reason_enum"`) - await queryRunner.query(`DROP INDEX "IDX_ec10c54769877840c132260e4a"`) - await queryRunner.query(`DROP TABLE "claim_tag"`) - await queryRunner.query(`DROP TABLE "claim_image"`) - await queryRunner.query( - `ALTER TABLE "shipping_method" ADD CONSTRAINT "CHK_3c00b878c1426d119cd70aa065" CHECK (((order_id IS NOT NULL) OR (cart_id IS NOT NULL) OR (swap_id IS NOT NULL) OR (return_id IS NOT NULL)))` - ) - } -} diff --git a/packages/medusa/src/migrations/1612353094577-indexes.ts b/packages/medusa/src/migrations/1612353094577-indexes.ts deleted file mode 100644 index dd330dbfa7..0000000000 --- a/packages/medusa/src/migrations/1612353094577-indexes.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class indexes1612353094577 implements MigrationInterface { - name = "indexes1612353094577" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE INDEX "IDX_21cbfedd83d736d86f4c6f4ce5" ON "claim_image" ("claim_item_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_7234ed737ff4eb1b6ae6e6d7b0" ON "product_option_value" ("variant_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_b1aac8314662fa6b25569a575b" ON "country" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_012a62ba743e427b5ebe9dee18" ON "shipping_option_requirement" ("shipping_option_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_5c58105f1752fca0f4ce69f466" ON "shipping_option" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c951439af4c98bf2bd7fb8726c" ON "shipping_option" ("profile_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_a0e206bfaed3cb63c186091734" ON "shipping_option" ("provider_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_80823b7ae866dc5acae2dac6d2" ON "product" ("profile_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_17a06d728e4cfbc5bd2ddb70af" ON "money_amount" ("variant_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_b433e27b7a83e6d12ab26b15b0" ON "money_amount" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ca67dd080aac5ecf99609960cd" ON "product_variant" ("product_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ac2c280de3701b2d66f6817f76" ON "discount" ("rule_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_d25ba0787e1510ddc5d442ebcf" ON "payment_session" ("cart_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_d18ad72f2fb7c87f075825b6f8" ON "payment_session" ("provider_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c17aff091441b7c25ec3d68d36" ON "payment" ("swap_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_4665f17abc1e81dd58330e5854" ON "payment" ("cart_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f5221735ace059250daac9d980" ON "payment" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ea94f42b6c88e9191c3649d752" ON "payment" ("provider_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_b6bcf8c3903097b84e85154eed" ON "gift_card" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_dfc1f02bb0552e79076aa58dbb" ON "gift_card" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_6b9c66b5e36f7c827dfaa092f9" ON "cart" ("billing_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ced15a9a695d2b5db9dabce763" ON "cart" ("shipping_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_484c329f4783be4e18e5e2ff09" ON "cart" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_242205c81c1152fab1b6e84847" ON "cart" ("customer_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_9d1a161434c610aae7c3df2dc7" ON "cart" ("payment_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_bad82d7bff2b08b87094bfac3d" ON "return" ("swap_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_71773d56eb2bacb922bc328339" ON "return" ("claim_order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_d4bd17f918fc6c332b74a368c3" ON "return" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f49e3974465d3c3a33d449d3f3" ON "claim_order" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_017d58bf8260c6e1a2588d258e" ON "claim_order" ("shipping_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_d73e55964e0ff2db8f03807d52" ON "fulfillment" ("claim_order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_a52e234f729db789cf473297a5" ON "fulfillment" ("swap_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f129acc85e346a10eed12b86fc" ON "fulfillment" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_beb35a6de60a6c4f91d5ae57e4" ON "fulfillment" ("provider_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_52dd74e8c989aa5665ad2852b8" ON "swap" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_d7d441b81012f87d4265fa57d2" ON "gift_card_transaction" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_eec9d9af4ca098e19ea6b499ea" ON "refund" ("order_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_579e01fb94f4f58db480857e05" ON "order" ("display_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c99a206eb11ad45f6b7f04f2dc" ON "order" ("cart_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_cd7812c96209c5bdd48a6b858b" ON "order" ("customer_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_5568d3b9ce9f7abeeb37511ecf" ON "order" ("billing_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_19b0c6293443d1b464f604c331" ON "order" ("shipping_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_e1fcce2b18dbcdbe0a5ba9a68b" ON "order" ("region_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_8abe81b9aac151ae60bf507ad1" ON "customer" ("billing_address_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_9c9614b2f9d01665800ea8dbff" ON "address" ("customer_id") ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_9c9614b2f9d01665800ea8dbff"`) - await queryRunner.query(`DROP INDEX "IDX_8abe81b9aac151ae60bf507ad1"`) - await queryRunner.query(`DROP INDEX "IDX_e1fcce2b18dbcdbe0a5ba9a68b"`) - await queryRunner.query(`DROP INDEX "IDX_19b0c6293443d1b464f604c331"`) - await queryRunner.query(`DROP INDEX "IDX_5568d3b9ce9f7abeeb37511ecf"`) - await queryRunner.query(`DROP INDEX "IDX_cd7812c96209c5bdd48a6b858b"`) - await queryRunner.query(`DROP INDEX "IDX_c99a206eb11ad45f6b7f04f2dc"`) - await queryRunner.query(`DROP INDEX "IDX_579e01fb94f4f58db480857e05"`) - await queryRunner.query(`DROP INDEX "IDX_eec9d9af4ca098e19ea6b499ea"`) - await queryRunner.query(`DROP INDEX "IDX_d7d441b81012f87d4265fa57d2"`) - await queryRunner.query(`DROP INDEX "IDX_52dd74e8c989aa5665ad2852b8"`) - await queryRunner.query(`DROP INDEX "IDX_beb35a6de60a6c4f91d5ae57e4"`) - await queryRunner.query(`DROP INDEX "IDX_f129acc85e346a10eed12b86fc"`) - await queryRunner.query(`DROP INDEX "IDX_a52e234f729db789cf473297a5"`) - await queryRunner.query(`DROP INDEX "IDX_d73e55964e0ff2db8f03807d52"`) - await queryRunner.query(`DROP INDEX "IDX_017d58bf8260c6e1a2588d258e"`) - await queryRunner.query(`DROP INDEX "IDX_f49e3974465d3c3a33d449d3f3"`) - await queryRunner.query(`DROP INDEX "IDX_d4bd17f918fc6c332b74a368c3"`) - await queryRunner.query(`DROP INDEX "IDX_71773d56eb2bacb922bc328339"`) - await queryRunner.query(`DROP INDEX "IDX_bad82d7bff2b08b87094bfac3d"`) - await queryRunner.query(`DROP INDEX "IDX_9d1a161434c610aae7c3df2dc7"`) - await queryRunner.query(`DROP INDEX "IDX_242205c81c1152fab1b6e84847"`) - await queryRunner.query(`DROP INDEX "IDX_484c329f4783be4e18e5e2ff09"`) - await queryRunner.query(`DROP INDEX "IDX_ced15a9a695d2b5db9dabce763"`) - await queryRunner.query(`DROP INDEX "IDX_6b9c66b5e36f7c827dfaa092f9"`) - await queryRunner.query(`DROP INDEX "IDX_dfc1f02bb0552e79076aa58dbb"`) - await queryRunner.query(`DROP INDEX "IDX_b6bcf8c3903097b84e85154eed"`) - await queryRunner.query(`DROP INDEX "IDX_ea94f42b6c88e9191c3649d752"`) - await queryRunner.query(`DROP INDEX "IDX_f5221735ace059250daac9d980"`) - await queryRunner.query(`DROP INDEX "IDX_4665f17abc1e81dd58330e5854"`) - await queryRunner.query(`DROP INDEX "IDX_c17aff091441b7c25ec3d68d36"`) - await queryRunner.query(`DROP INDEX "IDX_d18ad72f2fb7c87f075825b6f8"`) - await queryRunner.query(`DROP INDEX "IDX_d25ba0787e1510ddc5d442ebcf"`) - await queryRunner.query(`DROP INDEX "IDX_ac2c280de3701b2d66f6817f76"`) - await queryRunner.query(`DROP INDEX "IDX_ca67dd080aac5ecf99609960cd"`) - await queryRunner.query(`DROP INDEX "IDX_b433e27b7a83e6d12ab26b15b0"`) - await queryRunner.query(`DROP INDEX "IDX_17a06d728e4cfbc5bd2ddb70af"`) - await queryRunner.query(`DROP INDEX "IDX_80823b7ae866dc5acae2dac6d2"`) - await queryRunner.query(`DROP INDEX "IDX_a0e206bfaed3cb63c186091734"`) - await queryRunner.query(`DROP INDEX "IDX_c951439af4c98bf2bd7fb8726c"`) - await queryRunner.query(`DROP INDEX "IDX_5c58105f1752fca0f4ce69f466"`) - await queryRunner.query(`DROP INDEX "IDX_012a62ba743e427b5ebe9dee18"`) - await queryRunner.query(`DROP INDEX "IDX_b1aac8314662fa6b25569a575b"`) - await queryRunner.query(`DROP INDEX "IDX_7234ed737ff4eb1b6ae6e6d7b0"`) - await queryRunner.query(`DROP INDEX "IDX_21cbfedd83d736d86f4c6f4ce5"`) - } -} diff --git a/packages/medusa/src/migrations/1613146953072-notifications.ts b/packages/medusa/src/migrations/1613146953072-notifications.ts deleted file mode 100644 index 2261ee712b..0000000000 --- a/packages/medusa/src/migrations/1613146953072-notifications.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class notifications1613146953072 implements MigrationInterface { - name = "notifications1613146953072" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "notification_provider" ("id" character varying NOT NULL, "is_installed" boolean NOT NULL DEFAULT true, CONSTRAINT "PK_0425c2423e2ce9fdfd5c23761d9" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "notification" ("id" character varying NOT NULL, "event_name" character varying, "resource_type" character varying NOT NULL, "resource_id" character varying NOT NULL, "customer_id" character varying, "to" character varying NOT NULL, "data" jsonb NOT NULL, "parent_id" character varying, "provider_id" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "PK_705b6c7cdf9b2c2ff7ac7872cb7" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_df1494d263740fcfb1d09a98fc" ON "notification" ("resource_type") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ea6a358d9ce41c16499aae55f9" ON "notification" ("resource_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_b5df0f53a74b9d0c0a2b652c88" ON "notification" ("customer_id") ` - ) - await queryRunner.query( - `ALTER TABLE "notification" ADD CONSTRAINT "FK_b5df0f53a74b9d0c0a2b652c88d" FOREIGN KEY ("customer_id") REFERENCES "customer"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "notification" ADD CONSTRAINT "FK_371db513192c083f48ba63c33be" FOREIGN KEY ("parent_id") REFERENCES "notification"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "notification" ADD CONSTRAINT "FK_0425c2423e2ce9fdfd5c23761d9" FOREIGN KEY ("provider_id") REFERENCES "notification_provider"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "notification" DROP CONSTRAINT "FK_0425c2423e2ce9fdfd5c23761d9"` - ) - await queryRunner.query( - `ALTER TABLE "notification" DROP CONSTRAINT "FK_371db513192c083f48ba63c33be"` - ) - await queryRunner.query( - `ALTER TABLE "notification" DROP CONSTRAINT "FK_b5df0f53a74b9d0c0a2b652c88d"` - ) - await queryRunner.query(`DROP INDEX "IDX_b5df0f53a74b9d0c0a2b652c88"`) - await queryRunner.query(`DROP INDEX "IDX_ea6a358d9ce41c16499aae55f9"`) - await queryRunner.query(`DROP INDEX "IDX_df1494d263740fcfb1d09a98fc"`) - await queryRunner.query(`DROP TABLE "notification"`) - await queryRunner.query(`DROP TABLE "notification_provider"`) - } -} diff --git a/packages/medusa/src/migrations/1613146953073-product_type_category_tags.ts b/packages/medusa/src/migrations/1613146953073-product_type_category_tags.ts deleted file mode 100644 index 72c0abf38b..0000000000 --- a/packages/medusa/src/migrations/1613146953073-product_type_category_tags.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class productTypeCategoryTags1613146953073 - implements MigrationInterface { - name = "productTypeCategoryTags1613146953073" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "product_collection" ("id" character varying NOT NULL, "title" character varying NOT NULL, "handle" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_49d419fc77d3aed46c835c558ac" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_6910923cb678fd6e99011a21cc" ON "product_collection" ("handle") ` - ) - await queryRunner.query( - `CREATE TABLE "product_tag" ("id" character varying NOT NULL, "value" 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, "metadata" jsonb, CONSTRAINT "PK_1439455c6528caa94fcc8564fda" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "product_type" ("id" character varying NOT NULL, "value" 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, "metadata" jsonb, CONSTRAINT "PK_e0843930fbb8854fe36ca39dae1" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "product_tags" ("product_id" character varying NOT NULL, "product_tag_id" character varying NOT NULL, CONSTRAINT "PK_1cf5c9537e7198df494b71b993f" PRIMARY KEY ("product_id", "product_tag_id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_5b0c6fc53c574299ecc7f9ee22" ON "product_tags" ("product_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_21683a063fe82dafdf681ecc9c" ON "product_tags" ("product_tag_id") ` - ) - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "tags"`) - await queryRunner.query( - `ALTER TABLE "product" ADD "collection_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD "type_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD CONSTRAINT "FK_49d419fc77d3aed46c835c558ac" FOREIGN KEY ("collection_id") REFERENCES "product_collection"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_tags" ADD CONSTRAINT "FK_5b0c6fc53c574299ecc7f9ee22e" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_tags" ADD CONSTRAINT "FK_21683a063fe82dafdf681ecc9c4" FOREIGN KEY ("product_tag_id") REFERENCES "product_tag"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD CONSTRAINT "FK_e0843930fbb8854fe36ca39dae1" FOREIGN KEY ("type_id") REFERENCES "product_type"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_tags" DROP CONSTRAINT "FK_21683a063fe82dafdf681ecc9c4"` - ) - await queryRunner.query( - `ALTER TABLE "product_tags" DROP CONSTRAINT "FK_5b0c6fc53c574299ecc7f9ee22e"` - ) - await queryRunner.query( - `ALTER TABLE "product" DROP CONSTRAINT "FK_49d419fc77d3aed46c835c558ac"` - ) - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "type_id"`) - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "collection_id"`) - await queryRunner.query( - `ALTER TABLE "product" DROP CONSTRAINT "FK_e0843930fbb8854fe36ca39dae1"` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD "tags" character varying` - ) - await queryRunner.query(`DROP INDEX "IDX_21683a063fe82dafdf681ecc9c"`) - await queryRunner.query(`DROP INDEX "IDX_5b0c6fc53c574299ecc7f9ee22"`) - await queryRunner.query(`DROP TABLE "product_tags"`) - await queryRunner.query(`DROP TABLE "product_type"`) - await queryRunner.query(`DROP TABLE "product_tag"`) - await queryRunner.query(`DROP INDEX "IDX_6910923cb678fd6e99011a21cc"`) - await queryRunner.query(`DROP TABLE "product_collection"`) - } -} diff --git a/packages/medusa/src/migrations/1613384784316-draft_orders.ts b/packages/medusa/src/migrations/1613384784316-draft_orders.ts deleted file mode 100644 index 04a35d901d..0000000000 --- a/packages/medusa/src/migrations/1613384784316-draft_orders.ts +++ /dev/null @@ -1,50 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class draftOrders1613384784316 implements MigrationInterface { - name = 'draftOrders1613384784316' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TYPE "draft_order_status_enum" AS ENUM('open', 'completed')`); - await queryRunner.query(`CREATE TABLE "draft_order" ("id" character varying NOT NULL, "status" "draft_order_status_enum" NOT NULL DEFAULT 'open', "display_id" SERIAL NOT NULL, "cart_id" character varying, "order_id" character varying, "canceled_at" TIMESTAMP WITH TIME ZONE, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "completed_at" TIMESTAMP WITH TIME ZONE, "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "REL_5bd11d0e2a9628128e2c26fd0a" UNIQUE ("cart_id"), CONSTRAINT "REL_8f6dd6c49202f1466ebf21e77d" UNIQUE ("order_id"), CONSTRAINT "PK_f478946c183d98f8d88a94cfcd7" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE INDEX "IDX_e87cc617a22ef4edce5601edab" ON "draft_order" ("display_id") `); - await queryRunner.query(`CREATE INDEX "IDX_5bd11d0e2a9628128e2c26fd0a" ON "draft_order" ("cart_id") `); - await queryRunner.query(`CREATE INDEX "IDX_8f6dd6c49202f1466ebf21e77d" ON "draft_order" ("order_id") `); - await queryRunner.query(`ALTER TABLE "order" ADD "draft_order_id" character varying`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "UQ_727b872f86c7378474a8fa46147" UNIQUE ("draft_order_id")`); - await queryRunner.query(`ALTER TYPE "cart_type_enum" RENAME TO "cart_type_enum_old"`); - await queryRunner.query(`CREATE TYPE "cart_type_enum" AS ENUM('default', 'swap', 'draft_order', 'payment_link')`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" DROP DEFAULT`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" TYPE "cart_type_enum" USING "type"::"text"::"cart_type_enum"`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" SET DEFAULT 'default'`); - await queryRunner.query(`DROP TYPE "cart_type_enum_old"`); - await queryRunner.query(`COMMENT ON COLUMN "cart"."type" IS NULL`); - await queryRunner.query(`ALTER TABLE "draft_order" ADD CONSTRAINT "FK_5bd11d0e2a9628128e2c26fd0a6" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "draft_order" ADD CONSTRAINT "FK_8f6dd6c49202f1466ebf21e77da" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "order" ADD CONSTRAINT "FK_727b872f86c7378474a8fa46147" FOREIGN KEY ("draft_order_id") REFERENCES "draft_order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "store" ADD "payment_link_template" character varying`); - await queryRunner.query(`ALTER TABLE "shipping_option" ADD "admin_only" boolean NOT NULL DEFAULT false`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "FK_727b872f86c7378474a8fa46147"`); - await queryRunner.query(`ALTER TABLE "draft_order" DROP CONSTRAINT "FK_8f6dd6c49202f1466ebf21e77da"`); - await queryRunner.query(`ALTER TABLE "draft_order" DROP CONSTRAINT "FK_5bd11d0e2a9628128e2c26fd0a6"`); - await queryRunner.query(`COMMENT ON COLUMN "cart"."type" IS NULL`); - await queryRunner.query(`CREATE TYPE "cart_type_enum_old" AS ENUM('default', 'swap', 'payment_link')`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" DROP DEFAULT`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" TYPE "cart_type_enum_old" USING "type"::"text"::"cart_type_enum_old"`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" SET DEFAULT 'default'`); - await queryRunner.query(`DROP TYPE "cart_type_enum"`); - await queryRunner.query(`ALTER TYPE "cart_type_enum_old" RENAME TO "cart_type_enum"`); - await queryRunner.query(`ALTER TABLE "order" DROP CONSTRAINT "UQ_727b872f86c7378474a8fa46147"`); - await queryRunner.query(`ALTER TABLE "order" DROP COLUMN "draft_order_id"`); - await queryRunner.query(`DROP INDEX "IDX_8f6dd6c49202f1466ebf21e77d"`); - await queryRunner.query(`DROP INDEX "IDX_5bd11d0e2a9628128e2c26fd0a"`); - await queryRunner.query(`DROP INDEX "IDX_e87cc617a22ef4edce5601edab"`); - await queryRunner.query(`DROP TABLE "draft_order"`); - await queryRunner.query(`DROP TYPE "draft_order_status_enum"`); - await queryRunner.query(`ALTER TABLE "store" DROP COLUMN "payment_link_template"`); - await queryRunner.query(`ALTER TABLE "shipping_option" DROP COLUMN "admin_only"`) - } - -} diff --git a/packages/medusa/src/migrations/1613656135167-tracking_links.ts b/packages/medusa/src/migrations/1613656135167-tracking_links.ts deleted file mode 100644 index 4755a24c04..0000000000 --- a/packages/medusa/src/migrations/1613656135167-tracking_links.ts +++ /dev/null @@ -1,16 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class trackingLinks1613656135167 implements MigrationInterface { - name = 'trackingLinks1613656135167' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TABLE "tracking_link" ("id" character varying NOT NULL, "url" character varying, "tracking_number" character varying NOT NULL, "fulfillment_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, "metadata" jsonb, "idempotency_key" character varying, CONSTRAINT "PK_fcfd77feb9012ec2126d7c0bfb6" PRIMARY KEY ("id"))`); - await queryRunner.query(`ALTER TABLE "tracking_link" ADD CONSTRAINT "FK_471e9e4c96e02ba209a307db32b" FOREIGN KEY ("fulfillment_id") REFERENCES "fulfillment"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "tracking_link" DROP CONSTRAINT "FK_471e9e4c96e02ba209a307db32b"`); - await queryRunner.query(`DROP TABLE "tracking_link"`); - } - -} diff --git a/packages/medusa/src/migrations/1614684597235-cart_context.ts b/packages/medusa/src/migrations/1614684597235-cart_context.ts deleted file mode 100644 index 1dfa9e193c..0000000000 --- a/packages/medusa/src/migrations/1614684597235-cart_context.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class cartContext1614684597235 implements MigrationInterface { - name = "cartContext1614684597235" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "cart" ADD "context" jsonb`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "cart" DROP COLUMN "context"`) - } -} diff --git a/packages/medusa/src/migrations/1615891636559-return_reason.ts b/packages/medusa/src/migrations/1615891636559-return_reason.ts deleted file mode 100644 index c1c73cb8ac..0000000000 --- a/packages/medusa/src/migrations/1615891636559-return_reason.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class returnReason1615891636559 implements MigrationInterface { - name = "returnReason1615891636559" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "return_reason" ("id" character varying NOT NULL, "value" character varying NOT NULL, "label" character varying NOT NULL, "description" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_95fd1172973165790903e65660a" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_00605f9d662c06b81c1b60ce24" ON "return_reason" ("value") ` - ) - await queryRunner.query( - `ALTER TABLE "return_item" ADD "reason_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "return_item" ADD "note" character varying` - ) - await queryRunner.query( - `ALTER TABLE "return_item" ADD CONSTRAINT "FK_d742532378a65022e7ceb328828" FOREIGN KEY ("reason_id") REFERENCES "return_reason"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "return_item" DROP CONSTRAINT "FK_d742532378a65022e7ceb328828"` - ) - await queryRunner.query(`ALTER TABLE "return_item" DROP COLUMN "note"`) - await queryRunner.query(`ALTER TABLE "return_item" DROP COLUMN "reason_id"`) - await queryRunner.query(`DROP INDEX "IDX_00605f9d662c06b81c1b60ce24"`) - await queryRunner.query(`DROP TABLE "return_reason"`) - } -} diff --git a/packages/medusa/src/migrations/1615970124120-discount_usage_count.ts b/packages/medusa/src/migrations/1615970124120-discount_usage_count.ts deleted file mode 100644 index bd88342f41..0000000000 --- a/packages/medusa/src/migrations/1615970124120-discount_usage_count.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class discountUsageCount1615970124120 implements MigrationInterface { - name = "discountUsageCount1615970124120" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "discount_rule" ADD "usage_count" integer NOT NULL DEFAULT '0'` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "discount_rule" DROP COLUMN "usage_count"` - ) - } -} diff --git a/packages/medusa/src/migrations/1617002207608-discount_usage.ts b/packages/medusa/src/migrations/1617002207608-discount_usage.ts deleted file mode 100644 index 99d3697963..0000000000 --- a/packages/medusa/src/migrations/1617002207608-discount_usage.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class discountUsage1617002207608 implements MigrationInterface { - name = "discountUsage1617002207608" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "discount_rule" DROP COLUMN "usage_limit"` - ) - await queryRunner.query( - `ALTER TABLE "discount_rule" DROP COLUMN "usage_count"` - ) - await queryRunner.query(`ALTER TABLE "discount" ADD "usage_limit" integer`) - await queryRunner.query( - `ALTER TABLE "discount" ADD "usage_count" integer NOT NULL DEFAULT '0'` - ) - await queryRunner.query( - `ALTER TABLE "discount_rule" ALTER COLUMN "description" DROP NOT NULL` - ) - await queryRunner.query( - `COMMENT ON COLUMN "discount_rule"."description" IS NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "discount" DROP COLUMN "usage_count"`) - await queryRunner.query(`ALTER TABLE "discount" DROP COLUMN "usage_limit"`) - await queryRunner.query( - `ALTER TABLE "discount_rule" ADD "usage_count" integer NOT NULL DEFAULT '0'` - ) - await queryRunner.query( - `ALTER TABLE "discount_rule" ADD "usage_limit" integer` - ) - await queryRunner.query( - `COMMENT ON COLUMN "discount_rule"."description" IS NULL` - ) - await queryRunner.query( - `ALTER TABLE "discount_rule" ALTER COLUMN "description" SET NOT NULL` - ) - } -} diff --git a/packages/medusa/src/migrations/1619108646647-nullable_password.ts b/packages/medusa/src/migrations/1619108646647-nullable_password.ts deleted file mode 100644 index 429282c045..0000000000 --- a/packages/medusa/src/migrations/1619108646647-nullable_password.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class nullablePassword1619108646647 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "user" ALTER COLUMN "password_hash" DROP NOT NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "user" ALTER COLUMN "password_hash" TYPE character varying, ALTER COLUMN "password_hash" NOT NULL` - ) - } -} diff --git a/packages/medusa/src/migrations/1623231564533-no_notification.ts b/packages/medusa/src/migrations/1623231564533-no_notification.ts deleted file mode 100644 index dcd56690b0..0000000000 --- a/packages/medusa/src/migrations/1623231564533-no_notification.ts +++ /dev/null @@ -1,25 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class noNotification1623231564533 implements MigrationInterface { - name = 'noNotification1623231564533' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "return" ADD "no_notification" boolean`); - await queryRunner.query(`ALTER TABLE "claim_order" ADD "no_notification" boolean`); - await queryRunner.query(`ALTER TABLE "swap" ADD "no_notification" boolean`); - await queryRunner.query(`ALTER TABLE "order" ADD "no_notification" boolean`); - await queryRunner.query(`ALTER TABLE "draft_order" ADD "no_notification_order" boolean`); - await queryRunner.query(`ALTER TABLE "fulfillment" ADD "no_notification" boolean`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "fulfillment" DROP COLUMN "no_notification"`); - await queryRunner.query(`ALTER TABLE "draft_order" DROP COLUMN "no_notification_order"`); - await queryRunner.query(`ALTER TABLE "order" DROP COLUMN "no_notification"`); - await queryRunner.query(`ALTER TABLE "swap" DROP COLUMN "no_notification"`); - await queryRunner.query(`ALTER TABLE "claim_order" DROP COLUMN "no_notification"`); - await queryRunner.query(`ALTER TABLE "return" DROP COLUMN "no_notification"`); - - } - -} diff --git a/packages/medusa/src/migrations/1624287602631-gc_remove_unique_order.ts b/packages/medusa/src/migrations/1624287602631-gc_remove_unique_order.ts deleted file mode 100644 index c3fbfd4c4d..0000000000 --- a/packages/medusa/src/migrations/1624287602631-gc_remove_unique_order.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class gcRemoveUniqueOrder1624287602631 implements MigrationInterface { - name = "gcRemoveUniqueOrder1624287602631" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "gift_card" DROP CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0"`) - await queryRunner.query(`COMMENT ON COLUMN "gift_card"."order_id" IS NULL`) - await queryRunner.query(`ALTER TABLE "gift_card" DROP CONSTRAINT "REL_dfc1f02bb0552e79076aa58dbb"`) - await queryRunner.query(`ALTER TABLE "gift_card" ADD CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "gift_card" DROP CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0"`) - await queryRunner.query(`ALTER TABLE "gift_card" ADD CONSTRAINT "REL_dfc1f02bb0552e79076aa58dbb" UNIQUE ("order_id")`) - await queryRunner.query(`COMMENT ON COLUMN "gift_card"."order_id" IS NULL`) - await queryRunner.query(`ALTER TABLE "gift_card" ADD CONSTRAINT "FK_dfc1f02bb0552e79076aa58dbb0" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`) - } -} diff --git a/packages/medusa/src/migrations/1624610325746-soft_deleting_unique_constraints.ts b/packages/medusa/src/migrations/1624610325746-soft_deleting_unique_constraints.ts deleted file mode 100644 index 2bfb814c82..0000000000 --- a/packages/medusa/src/migrations/1624610325746-soft_deleting_unique_constraints.ts +++ /dev/null @@ -1,42 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class softDeletingUniqueConstraints1624610325746 implements MigrationInterface { - name = 'softDeletingUniqueConstraints1624610325746' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_6910923cb678fd6e99011a21cc"`); - await queryRunner.query(`DROP INDEX "IDX_db7355f7bd36c547c8a4f539e5"`); - await queryRunner.query(`DROP INDEX "IDX_087926f6fec32903be3c8eedfa"`); - await queryRunner.query(`DROP INDEX "IDX_f4dc2c0888b66d547c175f090e"`); - await queryRunner.query(`DROP INDEX "IDX_9db95c4b71f632fc93ecbc3d8b"`); - await queryRunner.query(`DROP INDEX "IDX_7124082c8846a06a857cca386c"`); - await queryRunner.query(`DROP INDEX "IDX_a0a3f124dc5b167622217fee02"`); - - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_e08af711f3493df1e921c4c9ef" ON "product_collection" ("handle") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_77c4073c30ea7793f484750529" ON "product" ("handle") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_ae3e22c67d7c7a969a363533c0" ON "discount" ("code") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_0683952543d7d3f4fffc427034" ON "product_variant" ("sku") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_410649600ce31c10c4b667ca10" ON "product_variant" ("barcode") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_5248fda27b9f16ef818604bb6f" ON "product_variant" ("ean") WHERE deleted_at IS NOT NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_832f86daf8103491d634a967da" ON "product_variant" ("upc") WHERE deleted_at IS NOT NULL`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_ae3e22c67d7c7a969a363533c0"`); - await queryRunner.query(`DROP INDEX "IDX_77c4073c30ea7793f484750529"`); - await queryRunner.query(`DROP INDEX "IDX_e08af711f3493df1e921c4c9ef"`); - await queryRunner.query(`DROP INDEX "IDX_832f86daf8103491d634a967da"`); - await queryRunner.query(`DROP INDEX "IDX_5248fda27b9f16ef818604bb6f"`); - await queryRunner.query(`DROP INDEX "IDX_410649600ce31c10c4b667ca10"`); - await queryRunner.query(`DROP INDEX "IDX_0683952543d7d3f4fffc427034"`); - - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_087926f6fec32903be3c8eedfa" ON "discount" ("code") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_db7355f7bd36c547c8a4f539e5" ON "product" ("handle") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_6910923cb678fd6e99011a21cc" ON "product_collection" ("handle") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_a0a3f124dc5b167622217fee02" ON "product_variant" ("upc") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_7124082c8846a06a857cca386c" ON "product_variant" ("ean") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_9db95c4b71f632fc93ecbc3d8b" ON "product_variant" ("barcode") `); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_f4dc2c0888b66d547c175f090e" ON "product_variant" ("sku") `); - } - -} diff --git a/packages/medusa/src/migrations/1625560513367-ensure_cancellation_fields_exist.ts b/packages/medusa/src/migrations/1625560513367-ensure_cancellation_fields_exist.ts deleted file mode 100644 index 7c1a0d0425..0000000000 --- a/packages/medusa/src/migrations/1625560513367-ensure_cancellation_fields_exist.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class ensureCancellationFieldsExist1625560513367 - implements MigrationInterface { - name = "ensureCancellationFieldsExist1625560513367" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "swap" ADD "canceled_at" TIMESTAMP WITH TIME ZONE` - ) - await queryRunner.query( - `ALTER TYPE "return_status_enum" RENAME TO "return_status_enum_old"` - ) - await queryRunner.query( - `CREATE TYPE "return_status_enum" AS ENUM('requested', 'received', 'requires_action', 'canceled')` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" DROP DEFAULT` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" TYPE "return_status_enum" USING "status"::"text"::"return_status_enum"` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" SET DEFAULT 'requested'` - ) - await queryRunner.query(`DROP TYPE "return_status_enum_old"`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "return_status_enum_old" AS ENUM('requested', 'received', 'requires_action')` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" DROP DEFAULT` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" TYPE "return_status_enum_old" USING "status"::"text"::"return_status_enum_old"` - ) - await queryRunner.query( - `ALTER TABLE "return" ALTER COLUMN "status" SET DEFAULT 'requested'` - ) - await queryRunner.query(`DROP TYPE "return_status_enum"`) - await queryRunner.query( - `ALTER TYPE "return_status_enum_old" RENAME TO "return_status_enum"` - ) - await queryRunner.query(`ALTER TABLE "swap" DROP COLUMN "canceled_at"`) - } -} diff --git a/packages/medusa/src/migrations/1627995307200-add_discountable_to_product.ts b/packages/medusa/src/migrations/1627995307200-add_discountable_to_product.ts deleted file mode 100644 index cfb2477148..0000000000 --- a/packages/medusa/src/migrations/1627995307200-add_discountable_to_product.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class addDiscountableToProduct1627995307200 implements MigrationInterface { - name = 'addDiscountableToProduct1627995307200' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product" ADD "discountable" boolean NOT NULL DEFAULT true`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "discountable"`); - } - -} diff --git a/packages/medusa/src/migrations/1630505790603-allow_backorder_swaps.ts b/packages/medusa/src/migrations/1630505790603-allow_backorder_swaps.ts deleted file mode 100644 index 1ecbfd4026..0000000000 --- a/packages/medusa/src/migrations/1630505790603-allow_backorder_swaps.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class allowBackorderSwaps1630505790603 implements MigrationInterface { - name = 'allowBackorderSwaps1630505790603' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "swap" ADD "allow_backorder" boolean NOT NULL DEFAULT false`); - await queryRunner.query(`ALTER TABLE "cart" ADD "payment_authorized_at" TIMESTAMP WITH TIME ZONE`); - await queryRunner.query(`ALTER TYPE "swap_payment_status_enum" RENAME TO "swap_payment_status_enum_old"`); - await queryRunner.query(`CREATE TYPE "swap_payment_status_enum" AS ENUM('not_paid', 'awaiting', 'captured', 'confirmed', 'canceled', 'difference_refunded', 'partially_refunded', 'refunded', 'requires_action')`); - await queryRunner.query(`ALTER TABLE "swap" ALTER COLUMN "payment_status" TYPE "swap_payment_status_enum" USING "payment_status"::"text"::"swap_payment_status_enum"`); - await queryRunner.query(`DROP TYPE "swap_payment_status_enum_old"`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TYPE "swap_payment_status_enum_old" AS ENUM('not_paid', 'awaiting', 'captured', 'canceled', 'difference_refunded', 'partially_refunded', 'refunded', 'requires_action')`); - await queryRunner.query(`ALTER TABLE "swap" ALTER COLUMN "payment_status" TYPE "swap_payment_status_enum_old" USING "payment_status"::"text"::"swap_payment_status_enum_old"`); - await queryRunner.query(`DROP TYPE "swap_payment_status_enum"`); - await queryRunner.query(`ALTER TYPE "swap_payment_status_enum_old" RENAME TO "swap_payment_status_enum"`); - await queryRunner.query(`ALTER TABLE "cart" DROP COLUMN "payment_authorized_at"`); - await queryRunner.query(`ALTER TABLE "swap" DROP COLUMN "allow_backorder"`); - } - -} diff --git a/packages/medusa/src/migrations/1631104895519-rank_column_with_default_value.ts b/packages/medusa/src/migrations/1631104895519-rank_column_with_default_value.ts deleted file mode 100644 index 75b501cc38..0000000000 --- a/packages/medusa/src/migrations/1631104895519-rank_column_with_default_value.ts +++ /dev/null @@ -1,23 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class RankColumnWithDefaultValue1631104895519 implements MigrationInterface { - name = 'RankColumnWithDefaultValue1631104895519' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product_variant" ADD "variant_rank" integer DEFAULT '0'`); - await queryRunner.query(`ALTER TABLE "product_option_value" DROP CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01"`); - await queryRunner.query(`ALTER TABLE "product_option_value" ADD CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE cascade ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0"`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE cascade ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product_variant" DROP COLUMN "variant_rank"`); - await queryRunner.query(`ALTER TABLE "product_option_value" DROP CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01"`); - await queryRunner.query(`ALTER TABLE "product_option_value" ADD CONSTRAINT "FK_7234ed737ff4eb1b6ae6e6d7b01" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0"`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - - } - -} diff --git a/packages/medusa/src/migrations/1631261634964-enforce_uniqueness.ts b/packages/medusa/src/migrations/1631261634964-enforce_uniqueness.ts deleted file mode 100644 index 1ec7b44c5c..0000000000 --- a/packages/medusa/src/migrations/1631261634964-enforce_uniqueness.ts +++ /dev/null @@ -1,41 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class enforceUniqueness1631261634964 implements MigrationInterface { - name = 'enforceUniqueness1631261634964' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_e08af711f3493df1e921c4c9ef"`); - await queryRunner.query(`DROP INDEX "IDX_77c4073c30ea7793f484750529"`); - await queryRunner.query(`DROP INDEX "IDX_0683952543d7d3f4fffc427034"`); - await queryRunner.query(`DROP INDEX "IDX_410649600ce31c10c4b667ca10"`); - await queryRunner.query(`DROP INDEX "IDX_5248fda27b9f16ef818604bb6f"`); - await queryRunner.query(`DROP INDEX "IDX_832f86daf8103491d634a967da"`); - await queryRunner.query(`DROP INDEX "IDX_ae3e22c67d7c7a969a363533c0"`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_6f234f058bbbea810dce1d04d0" ON "product_collection" ("handle") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_cf9cc6c3f2e6414b992223fff1" ON "product" ("handle") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_2ca8cfbdafb998ecfd6d340389" ON "product_variant" ("sku") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_045d4a149c09f4704e0bc08dd4" ON "product_variant" ("barcode") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_b5b6225539ee8501082fbc0714" ON "product_variant" ("ean") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_aa16f61348be02dd07ce3fc54e" ON "product_variant" ("upc") WHERE deleted_at IS NULL`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_f65bf52e2239ace276ece2b2f4" ON "discount" ("code") WHERE deleted_at IS NULL`); - } - - public async down(queryRunner: QueryRunner): Promise { - - await queryRunner.query(`DROP INDEX "IDX_f65bf52e2239ace276ece2b2f4"`); - await queryRunner.query(`DROP INDEX "IDX_aa16f61348be02dd07ce3fc54e"`); - await queryRunner.query(`DROP INDEX "IDX_b5b6225539ee8501082fbc0714"`); - await queryRunner.query(`DROP INDEX "IDX_045d4a149c09f4704e0bc08dd4"`); - await queryRunner.query(`DROP INDEX "IDX_2ca8cfbdafb998ecfd6d340389"`); - await queryRunner.query(`DROP INDEX "IDX_cf9cc6c3f2e6414b992223fff1"`); - await queryRunner.query(`DROP INDEX "IDX_6f234f058bbbea810dce1d04d0"`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_ae3e22c67d7c7a969a363533c0" ON "discount" ("code") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_832f86daf8103491d634a967da" ON "product_variant" ("upc") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_5248fda27b9f16ef818604bb6f" ON "product_variant" ("ean") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_410649600ce31c10c4b667ca10" ON "product_variant" ("barcode") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_0683952543d7d3f4fffc427034" ON "product_variant" ("sku") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_77c4073c30ea7793f484750529" ON "product" ("handle") WHERE (deleted_at IS NOT NULL)`); - await queryRunner.query(`CREATE UNIQUE INDEX "IDX_e08af711f3493df1e921c4c9ef" ON "product_collection" ("handle") WHERE (deleted_at IS NOT NULL)`); - } - -} diff --git a/packages/medusa/src/migrations/1631696624528-valid_duration_for_discount.ts b/packages/medusa/src/migrations/1631696624528-valid_duration_for_discount.ts deleted file mode 100644 index 267954d4e1..0000000000 --- a/packages/medusa/src/migrations/1631696624528-valid_duration_for_discount.ts +++ /dev/null @@ -1,14 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class validDurationForDiscount1631696624528 implements MigrationInterface { - name = 'validDurationForDiscount1631696624528' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "discount" ADD "valid_duration" character varying`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "discount" DROP COLUMN "valid_duration"`); - } - -} \ No newline at end of file diff --git a/packages/medusa/src/migrations/1631800727788-nested_return_reasons.ts b/packages/medusa/src/migrations/1631800727788-nested_return_reasons.ts deleted file mode 100644 index c50c957e09..0000000000 --- a/packages/medusa/src/migrations/1631800727788-nested_return_reasons.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class nestedReturnReasons1631800727788 implements MigrationInterface { - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "return_reason" ADD "parent_return_reason_id" character varying` - - ) - await queryRunner.query(`ALTER TABLE "return_reason" ADD CONSTRAINT "FK_2250c5d9e975987ab212f61a657" FOREIGN KEY ("parent_return_reason_id") REFERENCES "return_reason"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "return_reason" DROP COLUMN "parent_return_reason_id"` - ) - - } - -} diff --git a/packages/medusa/src/migrations/1631864388026-status_on_product.ts b/packages/medusa/src/migrations/1631864388026-status_on_product.ts deleted file mode 100644 index 1a54b5eb77..0000000000 --- a/packages/medusa/src/migrations/1631864388026-status_on_product.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class statusOnProduct1631864388026 implements MigrationInterface { - name = "statusOnProduct1631864388026" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "product_status_enum" AS ENUM('draft', 'proposed', 'published', 'rejected')` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD "status" "product_status_enum" ` - ) - await queryRunner.query( - `UPDATE "product" SET "status" = 'published' WHERE "status" IS NULL` - ) - await queryRunner.query( - `ALTER TABLE "product" ALTER COLUMN "status" SET NOT NULL` - ) - await queryRunner.query( - `ALTER TABLE "product" ALTER COLUMN "status" SET DEFAULT 'draft'` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "status"`) - await queryRunner.query(`DROP TYPE "product_status_enum"`) - } -} diff --git a/packages/medusa/src/migrations/1632220294687-add_notes.ts b/packages/medusa/src/migrations/1632220294687-add_notes.ts deleted file mode 100644 index 9550e11507..0000000000 --- a/packages/medusa/src/migrations/1632220294687-add_notes.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addNotes1632220294687 implements MigrationInterface { - name = "addNotes1632220294687" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "note" ("id" character varying NOT NULL, "value" character varying NOT NULL, "resource_type" character varying NOT NULL, "resource_id" character varying NOT NULL, "author_id" character varying, "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, "metadata" jsonb, CONSTRAINT "PK_96d0c172a4fba276b1bbed43058" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f74980b411cf94af523a72af7d" ON "note" ("resource_type") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_3287f98befad26c3a7dab088cf" ON "note" ("resource_id") ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_3287f98befad26c3a7dab088cf"`) - await queryRunner.query(`DROP INDEX "IDX_f74980b411cf94af523a72af7d"`) - await queryRunner.query(`DROP TABLE "note"`) - } -} diff --git a/packages/medusa/src/migrations/1632828114899-delete_date_on_shipping_option_requirements.ts b/packages/medusa/src/migrations/1632828114899-delete_date_on_shipping_option_requirements.ts deleted file mode 100644 index 12011f31a9..0000000000 --- a/packages/medusa/src/migrations/1632828114899-delete_date_on_shipping_option_requirements.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class deleteDateOnShippingOptionRequirements1632828114899 - implements MigrationInterface { - name = "deleteDateOnShippingOptionRequirements1632828114899" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "shipping_option_requirement" ADD "deleted_at" TIMESTAMP WITH TIME ZONE` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "shipping_option_requirement" DROP COLUMN "deleted_at"` - ) - } -} diff --git a/packages/medusa/src/migrations/1633512755401-extended_user_api.ts b/packages/medusa/src/migrations/1633512755401-extended_user_api.ts deleted file mode 100644 index e946d7df52..0000000000 --- a/packages/medusa/src/migrations/1633512755401-extended_user_api.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class extendedUserApi1633512755401 implements MigrationInterface { - name = "extendedUserApi1633512755401" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "invite_role_enum" AS ENUM('admin', 'member', 'developer')` - ) - await queryRunner.query( - `CREATE TABLE "invite" ("id" character varying NOT NULL, "user_email" character varying NOT NULL, "role" "invite_role_enum" DEFAULT 'member', "accepted" boolean NOT NULL DEFAULT false, "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, "metadata" jsonb, CONSTRAINT "PK_fc9fa190e5a3c5d80604a4f63e1" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `ALTER TABLE "invite" ADD "token" character varying NOT NULL` - ) - await queryRunner.query( - `ALTER TABLE "invite" ADD "expires_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - - await queryRunner.query( - `CREATE TYPE "user_role_enum" AS ENUM('admin', 'member', 'developer')` - ) - await queryRunner.query( - `ALTER TABLE "user" ADD "role" "user_role_enum" DEFAULT 'member'` - ) - - await queryRunner.query( - `ALTER TABLE "store" ADD "invite_link_template" character varying` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_6b0ce4b4bcfd24491510bf19d1" ON "invite" ("user_email")` - ) - await queryRunner.query(`DROP INDEX "IDX_e12875dfb3b1d92d7d7c5377e2"`) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_ba8de19442d86957a3aa3b5006" ON "user" ("email") WHERE deleted_at IS NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_ba8de19442d86957a3aa3b5006"`) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_e12875dfb3b1d92d7d7c5377e2" ON "user" ("email") ` - ) - await queryRunner.query(`DROP INDEX "IDX_6b0ce4b4bcfd24491510bf19d1"`) - await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "role"`) - await queryRunner.query(`DROP TYPE "user_role_enum"`) - await queryRunner.query( - `ALTER TABLE "invite" DROP COLUMN "expires_at"` - ) - await queryRunner.query(`ALTER TABLE "invite" DROP COLUMN "token"`) - - await queryRunner.query(`DROP TABLE "invite"`) - await queryRunner.query(`DROP TYPE "invite_role_enum"`) - await queryRunner.query( - `ALTER TABLE "store" DROP COLUMN "invite_link_template"` - ) - } -} diff --git a/packages/medusa/src/migrations/1633614437919-add_custom_shipping_options.ts b/packages/medusa/src/migrations/1633614437919-add_custom_shipping_options.ts deleted file mode 100644 index 3f7824e9ba..0000000000 --- a/packages/medusa/src/migrations/1633614437919-add_custom_shipping_options.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {MigrationInterface, QueryRunner} from "typeorm"; - -export class addCustomShippingOptions1633614437919 implements MigrationInterface { - name = 'addCustomShippingOptions1633614437919' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TABLE "custom_shipping_option" ("id" character varying NOT NULL, "price" integer NOT NULL, "shipping_option_id" character varying NOT NULL, "cart_id" character varying, "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, "metadata" jsonb, CONSTRAINT "UQ_0f838b122a9a01d921aa1cdb669" UNIQUE ("shipping_option_id", "cart_id"), CONSTRAINT "PK_8dfcb5c1172c29eec4a728420cc" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE INDEX "IDX_44090cb11b06174cbcc667e91c" ON "custom_shipping_option" ("shipping_option_id") `); - await queryRunner.query(`CREATE INDEX "IDX_93caeb1bb70d37c1d36d6701a7" ON "custom_shipping_option" ("cart_id") `); - await queryRunner.query(`ALTER TYPE "cart_type_enum" RENAME TO "cart_type_enum_old"`); - await queryRunner.query(`CREATE TYPE "cart_type_enum" AS ENUM('default', 'swap', 'draft_order', 'payment_link', 'claim')`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" DROP DEFAULT`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" TYPE "cart_type_enum" USING "type"::"text"::"cart_type_enum"`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" SET DEFAULT 'default'`); - await queryRunner.query(`DROP TYPE "cart_type_enum_old"`); - await queryRunner.query(`ALTER TABLE "custom_shipping_option" ADD CONSTRAINT "FK_44090cb11b06174cbcc667e91ca" FOREIGN KEY ("shipping_option_id") REFERENCES "shipping_option"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "custom_shipping_option" ADD CONSTRAINT "FK_93caeb1bb70d37c1d36d6701a7a" FOREIGN KEY ("cart_id") REFERENCES "cart"("id") ON DELETE NO ACTION ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "custom_shipping_option" DROP CONSTRAINT "FK_93caeb1bb70d37c1d36d6701a7a"`); - await queryRunner.query(`ALTER TABLE "custom_shipping_option" DROP CONSTRAINT "FK_44090cb11b06174cbcc667e91ca"`); - await queryRunner.query(`CREATE TYPE "cart_type_enum_old" AS ENUM('default', 'swap', 'draft_order', 'payment_link')`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" DROP DEFAULT`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" TYPE "cart_type_enum_old" USING "type"::"text"::"cart_type_enum_old"`); - await queryRunner.query(`ALTER TABLE "cart" ALTER COLUMN "type" SET DEFAULT 'default'`); - await queryRunner.query(`DROP TYPE "cart_type_enum"`); - await queryRunner.query(`ALTER TYPE "cart_type_enum_old" RENAME TO "cart_type_enum"`); - await queryRunner.query(`DROP INDEX "IDX_93caeb1bb70d37c1d36d6701a7"`); - await queryRunner.query(`DROP INDEX "IDX_44090cb11b06174cbcc667e91c"`); - await queryRunner.query(`DROP TABLE "custom_shipping_option"`); - } - -} diff --git a/packages/medusa/src/migrations/1638543550000-order_tax_rate_to_real_type.ts b/packages/medusa/src/migrations/1638543550000-order_tax_rate_to_real_type.ts deleted file mode 100644 index 67c1a7e060..0000000000 --- a/packages/medusa/src/migrations/1638543550000-order_tax_rate_to_real_type.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class orderTaxRateToRealType1638543550000 implements MigrationInterface { - name = "orderTaxRateToRealType1638543550000" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "order" ALTER COLUMN "tax_rate" TYPE REAL` - ) - await queryRunner.query( - `ALTER TABLE "region" ALTER COLUMN "tax_rate" TYPE REAL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "order" ALTER COLUMN "tax_rate" TYPE INTEGER` - ) - await queryRunner.query( - `ALTER TABLE "region" ALTER COLUMN "tax_rate" TYPE NUMERIC` - ) - } -} diff --git a/packages/medusa/src/migrations/1638952072999-external_id_order.ts b/packages/medusa/src/migrations/1638952072999-external_id_order.ts deleted file mode 100644 index 8466607818..0000000000 --- a/packages/medusa/src/migrations/1638952072999-external_id_order.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class externalIdOrder1638952072999 implements MigrationInterface { - name = "externalIdOrder1638952072999" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "order" ADD "external_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "product" ADD "external_id" character varying` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "product" DROP COLUMN "external_id"`) - await queryRunner.query(`ALTER TABLE "order" DROP COLUMN "external_id"`) - } -} diff --git a/packages/medusa/src/migrations/1641636508055-new_tax_system.ts b/packages/medusa/src/migrations/1641636508055-new_tax_system.ts deleted file mode 100644 index 898c4eeb0a..0000000000 --- a/packages/medusa/src/migrations/1641636508055-new_tax_system.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class newTaxSystem1641636508055 implements MigrationInterface { - name = "newTaxSystem1641636508055" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "tax_rate" ("id" character varying NOT NULL, "rate" real, "code" character varying, "name" character varying NOT NULL, "region_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_23b71b53f650c0b39e99ccef4fd" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "tax_provider" ("id" character varying NOT NULL, "is_installed" boolean NOT NULL DEFAULT true, CONSTRAINT "PK_b198bf82ba6a317c11763d99b99" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "line_item_tax_line" ("id" character varying NOT NULL, "rate" real NOT NULL, "name" character varying NOT NULL, "code" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "item_id" character varying NOT NULL, CONSTRAINT "PK_4a0f4322fcd5ce4af85727f89a8" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_5077fa54b0d037e984385dfe8a" ON "line_item_tax_line" ("item_id") ` - ) - await queryRunner.query( - `CREATE TABLE "shipping_method_tax_line" ("id" character varying NOT NULL, "rate" real NOT NULL, "name" character varying NOT NULL, "code" character varying, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, "shipping_method_id" character varying NOT NULL, CONSTRAINT "PK_54c94f5908aacbd51cf0a73edb1" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_926ca9f29014af8091722dede0" ON "shipping_method_tax_line" ("shipping_method_id") ` - ) - await queryRunner.query( - `CREATE TABLE "product_tax_rate" ("product_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_326257ce468df46cd5c8c5922e9" PRIMARY KEY ("product_id", "rate_id"))` - ) - await queryRunner.query( - `CREATE TABLE "product_type_tax_rate" ("product_type_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_ddc9242de1d99bc7674969289f0" PRIMARY KEY ("product_type_id", "rate_id"))` - ) - await queryRunner.query( - `CREATE TABLE "shipping_tax_rate" ("shipping_option_id" character varying NOT NULL, "rate_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_bcd93b14d7e2695365d383f5eae" PRIMARY KEY ("shipping_option_id", "rate_id"))` - ) - await queryRunner.query( - `ALTER TABLE "region" ADD "gift_cards_taxable" boolean NOT NULL DEFAULT true` - ) - await queryRunner.query( - `ALTER TABLE "region" ADD "automatic_taxes" boolean NOT NULL DEFAULT true` - ) - await queryRunner.query( - `ALTER TABLE "region" ADD "tax_provider_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "line_item" ADD "is_return" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `UPDATE "line_item" SET "is_return" = true WHERE "id" IN (SELECT "id" from "line_item" WHERE "metadata"->>'is_return_line' = 'true')` - ) - await queryRunner.query( - `ALTER TABLE "order" ALTER COLUMN "tax_rate" DROP NOT NULL` - ) - await queryRunner.query( - `CREATE INDEX "IDX_2484cf14c437a04586b07e7ddd" ON "product_tax_rate" ("rate_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_1d04aebeabb6a89f87e536a124" ON "product_tax_rate" ("product_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_ece65a774192b34253abc4cd67" ON "product_type_tax_rate" ("rate_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_25a3138bb236f63d9bb6c8ff11" ON "product_type_tax_rate" ("product_type_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_346e0016cf045b998074774764" ON "shipping_tax_rate" ("rate_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f672727ab020df6c50fb64c1a7" ON "shipping_tax_rate" ("shipping_option_id") ` - ) - await queryRunner.query( - `ALTER TABLE "tax_rate" ADD CONSTRAINT "FK_b95a1e03b051993d208366cb960" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "region" ADD CONSTRAINT "FK_91f88052197680f9790272aaf5b" FOREIGN KEY ("tax_provider_id") REFERENCES "tax_provider"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" ADD CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method_tax_line" ADD CONSTRAINT "FK_926ca9f29014af8091722dede08" FOREIGN KEY ("shipping_method_id") REFERENCES "shipping_method"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_tax_rate" ADD CONSTRAINT "FK_1d04aebeabb6a89f87e536a124d" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_tax_rate" ADD CONSTRAINT "FK_2484cf14c437a04586b07e7dddb" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_type_tax_rate" ADD CONSTRAINT "FK_25a3138bb236f63d9bb6c8ff111" FOREIGN KEY ("product_type_id") REFERENCES "product_type"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "product_type_tax_rate" ADD CONSTRAINT "FK_ece65a774192b34253abc4cd672" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "shipping_tax_rate" ADD CONSTRAINT "FK_f672727ab020df6c50fb64c1a70" FOREIGN KEY ("shipping_option_id") REFERENCES "shipping_option"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "shipping_tax_rate" ADD CONSTRAINT "FK_346e0016cf045b9980747747645" FOREIGN KEY ("rate_id") REFERENCES "tax_rate"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "shipping_tax_rate" DROP CONSTRAINT "FK_346e0016cf045b9980747747645"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_tax_rate" DROP CONSTRAINT "FK_f672727ab020df6c50fb64c1a70"` - ) - await queryRunner.query( - `ALTER TABLE "product_type_tax_rate" DROP CONSTRAINT "FK_ece65a774192b34253abc4cd672"` - ) - await queryRunner.query( - `ALTER TABLE "product_type_tax_rate" DROP CONSTRAINT "FK_25a3138bb236f63d9bb6c8ff111"` - ) - await queryRunner.query( - `ALTER TABLE "product_tax_rate" DROP CONSTRAINT "FK_2484cf14c437a04586b07e7dddb"` - ) - await queryRunner.query( - `ALTER TABLE "product_tax_rate" DROP CONSTRAINT "FK_1d04aebeabb6a89f87e536a124d"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method_tax_line" DROP CONSTRAINT "FK_926ca9f29014af8091722dede08"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" DROP CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad"` - ) - await queryRunner.query( - `ALTER TABLE "region" DROP CONSTRAINT "FK_91f88052197680f9790272aaf5b"` - ) - await queryRunner.query( - `ALTER TABLE "tax_rate" DROP CONSTRAINT "FK_b95a1e03b051993d208366cb960"` - ) - await queryRunner.query( - `DROP INDEX "IDX_f672727ab020df6c50fb64c1a7"` - ) - await queryRunner.query( - `DROP INDEX "IDX_346e0016cf045b998074774764"` - ) - await queryRunner.query( - `DROP INDEX "IDX_25a3138bb236f63d9bb6c8ff11"` - ) - await queryRunner.query( - `DROP INDEX "IDX_ece65a774192b34253abc4cd67"` - ) - await queryRunner.query( - `DROP INDEX "IDX_1d04aebeabb6a89f87e536a124"` - ) - await queryRunner.query( - `DROP INDEX "IDX_2484cf14c437a04586b07e7ddd"` - ) - await queryRunner.query( - `ALTER TABLE "order" ALTER COLUMN "tax_rate" SET NOT NULL` - ) - await queryRunner.query(`ALTER TABLE "line_item" DROP COLUMN "is_return"`) - await queryRunner.query( - `ALTER TABLE "region" DROP COLUMN "tax_provider_id"` - ) - await queryRunner.query( - `ALTER TABLE "region" DROP COLUMN "automatic_taxes"` - ) - await queryRunner.query( - `ALTER TABLE "region" DROP COLUMN "gift_cards_taxable"` - ) - await queryRunner.query(`DROP TABLE "shipping_tax_rate"`) - await queryRunner.query(`DROP TABLE "product_type_tax_rate"`) - await queryRunner.query(`DROP TABLE "product_tax_rate"`) - await queryRunner.query( - `DROP INDEX "IDX_926ca9f29014af8091722dede0"` - ) - await queryRunner.query(`DROP TABLE "shipping_method_tax_line"`) - await queryRunner.query( - `DROP INDEX "IDX_5077fa54b0d037e984385dfe8a"` - ) - await queryRunner.query(`DROP TABLE "line_item_tax_line"`) - await queryRunner.query(`DROP TABLE "tax_provider"`) - await queryRunner.query(`DROP TABLE "tax_rate"`) - } -} diff --git a/packages/medusa/src/migrations/1644943746861-customer_groups.ts b/packages/medusa/src/migrations/1644943746861-customer_groups.ts deleted file mode 100644 index 39bdeba12b..0000000000 --- a/packages/medusa/src/migrations/1644943746861-customer_groups.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class customerGroups1644943746861 implements MigrationInterface { - name = "customerGroups1644943746861" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "customer_group" ("id" character varying NOT NULL, "name" 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, "metadata" jsonb, CONSTRAINT "PK_88e7da3ff7262d9e0a35aa3664e" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_c4c3a5225a7a1f0af782c40abc" ON "customer_group" ("name") WHERE deleted_at IS NULL` - ) - await queryRunner.query( - `CREATE TABLE "customer_group_customers" ("customer_group_id" character varying NOT NULL, "customer_id" character varying NOT NULL, CONSTRAINT "PK_e28a55e34ad1e2d3df9a0ac86d3" PRIMARY KEY ("customer_group_id", "customer_id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_620330964db8d2999e67b0dbe3" ON "customer_group_customers" ("customer_group_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_3c6412d076292f439269abe1a2" ON "customer_group_customers" ("customer_id") ` - ) - await queryRunner.query( - `ALTER TABLE "customer_group_customers" ADD CONSTRAINT "FK_620330964db8d2999e67b0dbe3e" FOREIGN KEY ("customer_group_id") REFERENCES "customer_group"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "customer_group_customers" ADD CONSTRAINT "FK_3c6412d076292f439269abe1a23" FOREIGN KEY ("customer_id") REFERENCES "customer"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "customer_group_customers" DROP CONSTRAINT "FK_3c6412d076292f439269abe1a23"` - ) - await queryRunner.query( - `ALTER TABLE "customer_group_customers" DROP CONSTRAINT "FK_620330964db8d2999e67b0dbe3e"` - ) - - await queryRunner.query(`DROP INDEX "IDX_3c6412d076292f439269abe1a2"`) - await queryRunner.query(`DROP INDEX "IDX_620330964db8d2999e67b0dbe3"`) - await queryRunner.query(`DROP TABLE "customer_group_customers"`) - await queryRunner.query(`DROP INDEX "IDX_c4c3a5225a7a1f0af782c40abc"`) - await queryRunner.query(`DROP TABLE "customer_group"`) - } -} diff --git a/packages/medusa/src/migrations/1646324713514-discount_conditions.ts b/packages/medusa/src/migrations/1646324713514-discount_conditions.ts deleted file mode 100644 index f0559cbe18..0000000000 --- a/packages/medusa/src/migrations/1646324713514-discount_conditions.ts +++ /dev/null @@ -1,245 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class discountConditions1646324713514 implements MigrationInterface { - name = "discountConditions1646324713514" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "discount_condition_type_enum" AS ENUM('products', 'product_types', 'product_collections', 'product_tags', 'customer_groups')` - ) - await queryRunner.query( - `CREATE TYPE "discount_condition_operator_enum" AS ENUM('in', 'not_in')` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition" ("id" character varying NOT NULL, "type" "discount_condition_type_enum" NOT NULL, "operator" "discount_condition_operator_enum" NOT NULL, "discount_rule_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, "metadata" jsonb, CONSTRAINT "PK_e6b81d83133ddc21a2baf2e2204" PRIMARY KEY ("id"), CONSTRAINT "dctypeuniq" UNIQUE ("type", "operator", "discount_rule_id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_efff700651718e452ca9580a62" ON "discount_condition" ("discount_rule_id") ` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition_customer_group" ("customer_group_id" character varying NOT NULL, "condition_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_cdc8b2277169a16b8b7d4c73e0e" PRIMARY KEY ("customer_group_id", "condition_id"))` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition_product_collection" ("product_collection_id" character varying NOT NULL, "condition_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_b3508fc787aa4a38705866cbb6d" PRIMARY KEY ("product_collection_id", "condition_id"))` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition_product_tag" ("product_tag_id" character varying NOT NULL, "condition_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_a95382c1e62205b121aa058682b" PRIMARY KEY ("product_tag_id", "condition_id"))` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition_product_type" ("product_type_id" character varying NOT NULL, "condition_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_35d538a5a24399d0df978df12ed" PRIMARY KEY ("product_type_id", "condition_id"))` - ) - await queryRunner.query( - `CREATE TABLE "discount_condition_product" ("product_id" character varying NOT NULL, "condition_id" character varying NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "metadata" jsonb, CONSTRAINT "PK_994eb4529fdbf14450d64ec17e8" PRIMARY KEY ("product_id", "condition_id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_f05132301e95bdab4ba1cf29a2" ON "discount_condition_product" ("condition_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c759f53b2e48e8cfb50638fe4e" ON "discount_condition_product" ("product_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_6ef23ce0b1d9cf9b5b833e52b9" ON "discount_condition_product_type" ("condition_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_e706deb68f52ab2756119b9e70" ON "discount_condition_product_type" ("product_type_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_fbb2499551ed074526f3ee3624" ON "discount_condition_product_tag" ("condition_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_01486cc9dc6b36bf658685535f" ON "discount_condition_product_tag" ("product_tag_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_a1c4f9cfb599ad1f0db39cadd5" ON "discount_condition_product_collection" ("condition_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_a0b05dc4257abe639cb75f8eae" ON "discount_condition_product_collection" ("product_collection_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_8486ee16e69013c645d0b8716b" ON "discount_condition_customer_group" ("condition_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_4d5f98645a67545d8dea42e2eb" ON "discount_condition_customer_group" ("customer_group_id") ` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition" ADD CONSTRAINT "FK_efff700651718e452ca9580a624" FOREIGN KEY ("discount_rule_id") REFERENCES "discount_rule"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" ADD CONSTRAINT "FK_4d5f98645a67545d8dea42e2eb8" FOREIGN KEY ("customer_group_id") REFERENCES "customer_group"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" ADD CONSTRAINT "FK_8486ee16e69013c645d0b8716b6" FOREIGN KEY ("condition_id") REFERENCES "discount_condition"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" ADD CONSTRAINT "FK_a0b05dc4257abe639cb75f8eae2" FOREIGN KEY ("product_collection_id") REFERENCES "product_collection"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" ADD CONSTRAINT "FK_a1c4f9cfb599ad1f0db39cadd5f" FOREIGN KEY ("condition_id") REFERENCES "discount_condition"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" ADD CONSTRAINT "FK_01486cc9dc6b36bf658685535f6" FOREIGN KEY ("product_tag_id") REFERENCES "product_tag"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" ADD CONSTRAINT "FK_fbb2499551ed074526f3ee36241" FOREIGN KEY ("condition_id") REFERENCES "discount_condition"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" ADD CONSTRAINT "FK_e706deb68f52ab2756119b9e704" FOREIGN KEY ("product_type_id") REFERENCES "product_type"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" ADD CONSTRAINT "FK_6ef23ce0b1d9cf9b5b833e52b9d" FOREIGN KEY ("condition_id") REFERENCES "discount_condition"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" ADD CONSTRAINT "FK_c759f53b2e48e8cfb50638fe4e0" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" ADD CONSTRAINT "FK_f05132301e95bdab4ba1cf29a24" FOREIGN KEY ("condition_id") REFERENCES "discount_condition"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "discount_condition_product" DROP CONSTRAINT "FK_f05132301e95bdab4ba1cf29a24"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" DROP CONSTRAINT "FK_c759f53b2e48e8cfb50638fe4e0"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" DROP CONSTRAINT "FK_6ef23ce0b1d9cf9b5b833e52b9d"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" DROP CONSTRAINT "FK_e706deb68f52ab2756119b9e704"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" DROP CONSTRAINT "FK_fbb2499551ed074526f3ee36241"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" DROP CONSTRAINT "FK_01486cc9dc6b36bf658685535f6"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" DROP CONSTRAINT "FK_a1c4f9cfb599ad1f0db39cadd5f"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" DROP CONSTRAINT "FK_a0b05dc4257abe639cb75f8eae2"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" DROP CONSTRAINT "FK_8486ee16e69013c645d0b8716b6"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" DROP CONSTRAINT "FK_4d5f98645a67545d8dea42e2eb8"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition" DROP CONSTRAINT "FK_efff700651718e452ca9580a624"` - ) - await queryRunner.query(`DROP INDEX "IDX_4d5f98645a67545d8dea42e2eb"`) - await queryRunner.query(`DROP INDEX "IDX_8486ee16e69013c645d0b8716b"`) - await queryRunner.query(`DROP INDEX "IDX_a0b05dc4257abe639cb75f8eae"`) - await queryRunner.query(`DROP INDEX "IDX_a1c4f9cfb599ad1f0db39cadd5"`) - await queryRunner.query(`DROP INDEX "IDX_01486cc9dc6b36bf658685535f"`) - await queryRunner.query(`DROP INDEX "IDX_fbb2499551ed074526f3ee3624"`) - await queryRunner.query(`DROP INDEX "IDX_e706deb68f52ab2756119b9e70"`) - await queryRunner.query(`DROP INDEX "IDX_6ef23ce0b1d9cf9b5b833e52b9"`) - await queryRunner.query(`DROP INDEX "IDX_c759f53b2e48e8cfb50638fe4e"`) - await queryRunner.query(`DROP INDEX "IDX_f05132301e95bdab4ba1cf29a2"`) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" DROP COLUMN "metadata"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" DROP COLUMN "updated_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" DROP COLUMN "created_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" DROP COLUMN "metadata"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" DROP COLUMN "updated_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" DROP COLUMN "created_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" DROP COLUMN "metadata"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" DROP COLUMN "updated_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" DROP COLUMN "created_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" DROP COLUMN "metadata"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" DROP COLUMN "updated_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" DROP COLUMN "created_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" DROP COLUMN "metadata"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" DROP COLUMN "updated_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" DROP COLUMN "created_at"` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" ADD "metadata" jsonb` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" ADD "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_customer_group" ADD "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" ADD "metadata" jsonb` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" ADD "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_collection" ADD "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" ADD "metadata" jsonb` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" ADD "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_tag" ADD "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" ADD "metadata" jsonb` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" ADD "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product_type" ADD "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" ADD "metadata" jsonb` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" ADD "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query( - `ALTER TABLE "discount_condition_product" ADD "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()` - ) - await queryRunner.query(`DROP TABLE "discount_condition_product"`) - await queryRunner.query(`DROP TABLE "discount_condition_product_type"`) - await queryRunner.query(`DROP TABLE "discount_condition_product_tag"`) - await queryRunner.query( - `DROP TABLE "discount_condition_product_collection"` - ) - await queryRunner.query(`DROP TABLE "discount_condition_customer_group"`) - await queryRunner.query(`DROP INDEX "IDX_efff700651718e452ca9580a62"`) - await queryRunner.query(`DROP TABLE "discount_condition"`) - await queryRunner.query(`DROP TYPE "discount_condition_operator_enum"`) - await queryRunner.query(`DROP TYPE "discount_condition_type_enum"`) - } -} diff --git a/packages/medusa/src/migrations/1646915480108-update_money_amount_add_price_list.ts b/packages/medusa/src/migrations/1646915480108-update_money_amount_add_price_list.ts deleted file mode 100644 index df5bfe87a1..0000000000 --- a/packages/medusa/src/migrations/1646915480108-update_money_amount_add_price_list.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm"; - -export class updateMoneyAmountAddPriceList1646915480108 implements MigrationInterface { - name = 'updateMoneyAmountAddPriceList1646915480108' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE TYPE "price_list_type_enum" AS ENUM('sale', 'override')`); - await queryRunner.query(`CREATE TYPE "price_list_status_enum" AS ENUM('active', 'draft')`); - await queryRunner.query(`CREATE TABLE "price_list" ("id" character varying NOT NULL, "name" character varying NOT NULL, "description" character varying NOT NULL, "type" "price_list_type_enum" NOT NULL DEFAULT 'sale', "status" "price_list_status_enum" NOT NULL DEFAULT 'draft', "starts_at" TIMESTAMP WITH TIME ZONE, "ends_at" TIMESTAMP WITH TIME ZONE, "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, CONSTRAINT "PK_52ea7826468b1c889cb2c28df03" PRIMARY KEY ("id"))`); - await queryRunner.query(`CREATE TABLE "price_list_customer_groups" ("price_list_id" character varying NOT NULL, "customer_group_id" character varying NOT NULL, CONSTRAINT "PK_1afcbe15cc8782dc80c05707df9" PRIMARY KEY ("price_list_id", "customer_group_id"))`); - await queryRunner.query(`CREATE INDEX "IDX_52875734e9dd69064f0041f4d9" ON "price_list_customer_groups" ("price_list_id") `); - await queryRunner.query(`CREATE INDEX "IDX_c5516f550433c9b1c2630d787a" ON "price_list_customer_groups" ("customer_group_id") `); - await queryRunner.query(`ALTER TABLE "money_amount" DROP COLUMN "sale_amount"`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD "min_quantity" integer`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD "max_quantity" integer`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD "price_list_id" character varying`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD CONSTRAINT "FK_f249976b079375499662eb80c40" FOREIGN KEY ("price_list_id") REFERENCES "price_list"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - await queryRunner.query(`ALTER TABLE "price_list_customer_groups" ADD CONSTRAINT "FK_52875734e9dd69064f0041f4d92" FOREIGN KEY ("price_list_id") REFERENCES "price_list"("id") ON DELETE CASCADE ON UPDATE CASCADE`); - await queryRunner.query(`ALTER TABLE "price_list_customer_groups" ADD CONSTRAINT "FK_c5516f550433c9b1c2630d787a7" FOREIGN KEY ("customer_group_id") REFERENCES "customer_group"("id") ON DELETE CASCADE ON UPDATE NO ACTION`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "price_list_customer_groups" DROP CONSTRAINT "FK_c5516f550433c9b1c2630d787a7"`); - await queryRunner.query(`ALTER TABLE "price_list_customer_groups" DROP CONSTRAINT "FK_52875734e9dd69064f0041f4d92"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP CONSTRAINT "FK_f249976b079375499662eb80c40"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP COLUMN "price_list_id"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP COLUMN "max_quantity"`); - await queryRunner.query(`ALTER TABLE "money_amount" DROP COLUMN "min_quantity"`); - await queryRunner.query(`ALTER TABLE "money_amount" ADD "sale_amount" integer`); - await queryRunner.query(`DROP INDEX "IDX_c5516f550433c9b1c2630d787a"`); - await queryRunner.query(`DROP INDEX "IDX_52875734e9dd69064f0041f4d9"`); - await queryRunner.query(`DROP TABLE "price_list_customer_groups"`); - await queryRunner.query(`DROP TABLE "price_list"`); - await queryRunner.query(`DROP TYPE "price_list_status_enum"`); - await queryRunner.query(`DROP TYPE "price_list_type_enum"`); - } - -} diff --git a/packages/medusa/src/migrations/1648600574750-add_line_item_adjustments.ts b/packages/medusa/src/migrations/1648600574750-add_line_item_adjustments.ts deleted file mode 100644 index 687956398f..0000000000 --- a/packages/medusa/src/migrations/1648600574750-add_line_item_adjustments.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addLineItemAdjustments1648600574750 implements MigrationInterface { - name = "addLineItemAdjustments1648600574750" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "line_item_adjustment" ("id" character varying NOT NULL, "item_id" character varying NOT NULL, "description" character varying NOT NULL, "discount_id" character varying, "amount" integer NOT NULL, "metadata" jsonb, CONSTRAINT "PK_2b1360103753df2dc8257c2c8c3" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_be9aea2ccf3567007b6227da4d" ON "line_item_adjustment" ("item_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_2f41b20a71f30e60471d7e3769" ON "line_item_adjustment" ("discount_id") ` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_bf701b88d2041392a288785ada" ON "line_item_adjustment" ("discount_id", "item_id") WHERE "discount_id" IS NOT NULL` - ) - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" ADD CONSTRAINT "FK_be9aea2ccf3567007b6227da4d2" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" ADD CONSTRAINT "FK_2f41b20a71f30e60471d7e3769c" FOREIGN KEY ("discount_id") REFERENCES "discount"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" DROP CONSTRAINT "FK_2f41b20a71f30e60471d7e3769c"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" DROP CONSTRAINT "FK_be9aea2ccf3567007b6227da4d2"` - ) - await queryRunner.query(`DROP INDEX "IDX_bf701b88d2041392a288785ada"`) - await queryRunner.query(`DROP INDEX "IDX_2f41b20a71f30e60471d7e3769"`) - await queryRunner.query(`DROP INDEX "IDX_be9aea2ccf3567007b6227da4d"`) - await queryRunner.query(`DROP TABLE "line_item_adjustment"`) - } -} diff --git a/packages/medusa/src/migrations/1648641130007-tax_line_constraints.ts b/packages/medusa/src/migrations/1648641130007-tax_line_constraints.ts deleted file mode 100644 index c7795d236f..0000000000 --- a/packages/medusa/src/migrations/1648641130007-tax_line_constraints.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class taxLineConstraints1648641130007 implements MigrationInterface { - name = "taxLineConstraints1648641130007" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" ADD CONSTRAINT "UQ_3c2af51043ed7243e7d9775a2ad" UNIQUE ("item_id", "code")` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method_tax_line" ADD CONSTRAINT "UQ_cd147fca71e50bc954139fa3104" UNIQUE ("shipping_method_id", "code")` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "shipping_method_tax_line" DROP CONSTRAINT "UQ_cd147fca71e50bc954139fa3104"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" DROP CONSTRAINT "UQ_3c2af51043ed7243e7d9775a2ad"` - ) - } -} diff --git a/packages/medusa/src/migrations/1649775522087-add_batch_job_model.ts b/packages/medusa/src/migrations/1649775522087-add_batch_job_model.ts deleted file mode 100644 index cfa20c2452..0000000000 --- a/packages/medusa/src/migrations/1649775522087-add_batch_job_model.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addBatchJobModel1649775522087 implements MigrationInterface { - name = "addBatchJobModel1649775522087" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "batch_job" - ( - "id" character varying NOT NULL, - "type" text NOT NULL, - "created_by" character varying, - "context" jsonb, - "result" jsonb, - "dry_run" boolean NOT NULL DEFAULT FALSE, - "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - "pre_processed_at" TIMESTAMP WITH TIME ZONE, - "confirmed_at" TIMESTAMP WITH TIME ZONE, - "processing_at" TIMESTAMP WITH TIME ZONE, - "completed_at" TIMESTAMP WITH TIME ZONE, - "failed_at" TIMESTAMP WITH TIME ZONE, - "canceled_at" TIMESTAMP WITH TIME ZONE, - "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - "deleted_at" TIMESTAMP WITH TIME ZONE, - CONSTRAINT "PK_e57f84d485145d5be96bc6d871e" PRIMARY KEY ("id") - )` - ) - - await queryRunner.query( - `ALTER TABLE "batch_job" - ADD CONSTRAINT "FK_fa53ca4f5fd90605b532802a626" FOREIGN KEY ("created_by") REFERENCES "user" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "batch_job" - DROP CONSTRAINT "FK_fa53ca4f5fd90605b532802a626"` - ) - await queryRunner.query(`DROP TABLE "batch_job"`) - } -} diff --git a/packages/medusa/src/migrations/1656949291839-sales_channel.ts b/packages/medusa/src/migrations/1656949291839-sales_channel.ts deleted file mode 100644 index 24c39c4d34..0000000000 --- a/packages/medusa/src/migrations/1656949291839-sales_channel.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" -import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels" - -export const featureFlag = SalesChannelFeatureFlag.key - -export class salesChannel1656949291839 implements MigrationInterface { - name = "salesChannel1656949291839" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "sales_channel" ("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" character varying NOT NULL, "description" character varying, "is_disabled" boolean NOT NULL DEFAULT false, CONSTRAINT "PK_d1eb0b923ea5a0eb1e0916191f1" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "product_sales_channel" ("product_id" character varying NOT NULL, "sales_channel_id" character varying NOT NULL, CONSTRAINT "PK_fd29b6a8bd641052628dee19583" PRIMARY KEY ("product_id", "sales_channel_id"))` - ) - - await queryRunner.query( - `CREATE INDEX "IDX_5a4d5e1e60f97633547821ec8d" ON "product_sales_channel" ("product_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_37341bad297fe5cca91f921032" ON "product_sales_channel" ("sales_channel_id") ` - ) - - await queryRunner.query( - `ALTER TABLE "cart" ADD "sales_channel_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "order" ADD "sales_channel_id" character varying` - ) - - await queryRunner.query( - `ALTER TABLE "store" ADD "default_sales_channel_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "store" ADD CONSTRAINT "UQ_61b0f48cccbb5f41c750bac7286" UNIQUE ("default_sales_channel_id")` - ) - - await queryRunner.query( - `ALTER TABLE "cart" ADD CONSTRAINT "FK_a2bd3c26f42e754b9249ba78fd6" FOREIGN KEY ("sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "order" ADD CONSTRAINT "FK_6ff7e874f01b478c115fdd462eb" FOREIGN KEY ("sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "store" ADD CONSTRAINT "FK_61b0f48cccbb5f41c750bac7286" FOREIGN KEY ("default_sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - - await queryRunner.query( - `ALTER TABLE "product_sales_channel" ADD CONSTRAINT "FK_5a4d5e1e60f97633547821ec8d6" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE CASCADE ON UPDATE CASCADE` - ) - await queryRunner.query( - `ALTER TABLE "product_sales_channel" ADD CONSTRAINT "FK_37341bad297fe5cca91f921032b" FOREIGN KEY ("sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE CASCADE ON UPDATE CASCADE` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_sales_channel" DROP CONSTRAINT "FK_37341bad297fe5cca91f921032b"` - ) - await queryRunner.query( - `ALTER TABLE "product_sales_channel" DROP CONSTRAINT "FK_5a4d5e1e60f97633547821ec8d6"` - ) - - await queryRunner.query( - `ALTER TABLE "store" DROP COLUMN "default_sales_channel_id"` - ) - await queryRunner.query( - `ALTER TABLE "order" DROP COLUMN "sales_channel_id"` - ) - await queryRunner.query(`ALTER TABLE "cart" DROP COLUMN "sales_channel_id"`) - await queryRunner.query(`DROP TABLE "product_sales_channel"`) - await queryRunner.query(`DROP TABLE "sales_channel"`) - } -} diff --git a/packages/medusa/src/migrations/1657098186554-taxed_gift_card_transactions.ts b/packages/medusa/src/migrations/1657098186554-taxed_gift_card_transactions.ts deleted file mode 100644 index f96cc2cd3a..0000000000 --- a/packages/medusa/src/migrations/1657098186554-taxed_gift_card_transactions.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class taxedGiftCardTransactions1657098186554 - implements MigrationInterface -{ - name = "taxedGiftCardTransactions1657098186554" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "gift_card_transaction" ADD "is_taxable" boolean` - ) - await queryRunner.query( - `ALTER TABLE "gift_card_transaction" ADD "tax_rate" real` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "gift_card_transaction" DROP COLUMN "is_taxable"` - ) - await queryRunner.query( - `ALTER TABLE "gift_card_transaction" DROP COLUMN "tax_rate"` - ) - } -} diff --git a/packages/medusa/src/migrations/1657267320181-extended_batch_job.ts b/packages/medusa/src/migrations/1657267320181-extended_batch_job.ts deleted file mode 100644 index b978edc19e..0000000000 --- a/packages/medusa/src/migrations/1657267320181-extended_batch_job.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class extendedBatchJob1657267320181 implements MigrationInterface { - name = "extendedBatchJob1657267320181" - - public async up(queryRunner: QueryRunner): Promise { - // check if batch job table exists and status column exists - // if that's the case, the previous migration has already been run - const batchJobColumnStatusExists = await queryRunner.query(` - SELECT exists ( - SELECT FROM information_schema.columns - WHERE table_name = 'batch_job' - AND column_name = 'status' - )`) - - // if the table exists, we alter the table to add the new columns - if (batchJobColumnStatusExists[0].exists) { - await queryRunner.query(` - ALTER TABLE "batch_job" DROP COLUMN "status"; - DROP TYPE "batch_job_status_enum"; - ALTER TABLE "batch_job" ADD "dry_run" boolean NOT NULL DEFAULT false; - ALTER TABLE "batch_job" ADD "pre_processed_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" ADD "processing_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" ADD "confirmed_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" ADD "completed_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" ADD "canceled_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" ADD "failed_at" TIMESTAMP WITH TIME ZONE; - ALTER TABLE "batch_job" DROP COLUMN "created_by"; - ALTER TABLE "batch_job" ADD "created_by" character varying; - ALTER TABLE "batch_job" ADD CONSTRAINT "FK_cdf30493ba1c9ef207e1e80c10a" FOREIGN KEY ("created_by") REFERENCES "user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - `) - } - } - - public async down(queryRunner: QueryRunner): Promise { - void 0 - } -} diff --git a/packages/medusa/src/migrations/1659501357661-tax_inclusive_pricing.ts b/packages/medusa/src/migrations/1659501357661-tax_inclusive_pricing.ts deleted file mode 100644 index 78867e719e..0000000000 --- a/packages/medusa/src/migrations/1659501357661-tax_inclusive_pricing.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" -import TaxInclusivePricingFlag from "../loaders/feature-flags/tax-inclusive-pricing" - -export const featureFlag = TaxInclusivePricingFlag.key - -export class test1659501357661 implements MigrationInterface { - name = "test1659501357661" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "currency" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `ALTER TABLE "region" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `ALTER TABLE "shipping_option" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `ALTER TABLE "price_list" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - await queryRunner.query( - `ALTER TABLE "line_item" ADD "includes_tax" boolean NOT NULL DEFAULT false` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item" DROP COLUMN "includes_tax"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_method" DROP COLUMN "includes_tax"` - ) - await queryRunner.query( - `ALTER TABLE "price_list" DROP COLUMN "includes_tax"` - ) - await queryRunner.query( - `ALTER TABLE "shipping_option" DROP COLUMN "includes_tax"` - ) - await queryRunner.query(`ALTER TABLE "region" DROP COLUMN "includes_tax"`) - await queryRunner.query(`ALTER TABLE "currency" DROP COLUMN "includes_tax"`) - } -} diff --git a/packages/medusa/src/migrations/1660040729000-payment_session_uniq_cartId_providerId.ts b/packages/medusa/src/migrations/1660040729000-payment_session_uniq_cartId_providerId.ts deleted file mode 100644 index d738af3d86..0000000000 --- a/packages/medusa/src/migrations/1660040729000-payment_session_uniq_cartId_providerId.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class paymentSessionUniqCartIdProviderId1660040729000 implements MigrationInterface { - name = "paymentSessionUniqCartIdProviderId1660040729000" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`CREATE UNIQUE INDEX "UniqPaymentSessionCartIdProviderId" ON "payment_session" ("cart_id", "provider_id")`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "UniqPaymentSessionCartIdProviderId"`) - } -} diff --git a/packages/medusa/src/migrations/1661345741249-multi_payment_cart.ts b/packages/medusa/src/migrations/1661345741249-multi_payment_cart.ts deleted file mode 100644 index 2ada304469..0000000000 --- a/packages/medusa/src/migrations/1661345741249-multi_payment_cart.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class multiPaymentCart1661345741249 implements MigrationInterface { - name = "multiPaymentCart1661345741249" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "payment" DROP CONSTRAINT "REL_4665f17abc1e81dd58330e5854"` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "UniquePaymentActive" ON "payment" ("cart_id") WHERE canceled_at IS NULL` - ) - await queryRunner.query( - `CREATE INDEX "IDX_aac4855eadda71aa1e4b6d7684" ON "payment" ("cart_id") WHERE canceled_at IS NOT NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_aac4855eadda71aa1e4b6d7684"`) - await queryRunner.query(`DROP INDEX "UniquePaymentActive"`) - await queryRunner.query( - `ALTER TABLE "payment" ADD CONSTRAINT "REL_4665f17abc1e81dd58330e5854" UNIQUE ("cart_id")` - ) - } -} diff --git a/packages/medusa/src/migrations/1661863940645-swap_fulfillment_status_requires_action.ts b/packages/medusa/src/migrations/1661863940645-swap_fulfillment_status_requires_action.ts deleted file mode 100644 index c4a1d88b08..0000000000 --- a/packages/medusa/src/migrations/1661863940645-swap_fulfillment_status_requires_action.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class swapFulfillmentStatusRequiresAction1661863940645 - implements MigrationInterface -{ - name = "swapFulfillmentStatusRequiresAction1661863940645" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TYPE "swap_fulfillment_status_enum" RENAME TO "swap_fulfillment_status_enum_old"` - ) - await queryRunner.query( - `CREATE TYPE "swap_fulfillment_status_enum" AS ENUM('not_fulfilled', 'fulfilled', 'shipped', 'partially_shipped', 'canceled', 'requires_action')` - ) - await queryRunner.query( - `ALTER TABLE "swap" ALTER COLUMN "fulfillment_status" TYPE "swap_fulfillment_status_enum" USING "fulfillment_status"::"text"::"swap_fulfillment_status_enum"` - ) - await queryRunner.query(`DROP TYPE "swap_fulfillment_status_enum_old"`) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "swap_fulfillment_status_enum_old" AS ENUM('not_fulfilled', 'fulfilled', 'shipped', 'canceled', 'requires_action')` - ) - await queryRunner.query( - `ALTER TABLE "swap" ALTER COLUMN "fulfillment_status" TYPE "swap_fulfillment_status_enum_old" USING "fulfillment_status"::"text"::"swap_fulfillment_status_enum_old"` - ) - await queryRunner.query(`DROP TYPE "swap_fulfillment_status_enum"`) - await queryRunner.query( - `ALTER TYPE "swap_fulfillment_status_enum_old" RENAME TO "swap_fulfillment_status_enum"` - ) - } -} diff --git a/packages/medusa/src/migrations/1663059812399-order_editing.ts b/packages/medusa/src/migrations/1663059812399-order_editing.ts deleted file mode 100644 index 03a043248a..0000000000 --- a/packages/medusa/src/migrations/1663059812399-order_editing.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class orderEditing1663059812399 implements MigrationInterface { - name = "orderEditing1663059812399" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TYPE "order_item_change_type_enum" AS ENUM('item_add', 'item_remove', 'item_update')` - ) - await queryRunner.query( - `CREATE TABLE "order_item_change" ("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, "type" "order_item_change_type_enum" NOT NULL, "order_edit_id" character varying NOT NULL, "original_line_item_id" character varying, "line_item_id" character varying, CONSTRAINT "UQ_da93cee3ca0dd50a5246268c2e9" UNIQUE ("order_edit_id", "line_item_id"), CONSTRAINT "UQ_5b7a99181e4db2ea821be0b6196" UNIQUE ("order_edit_id", "original_line_item_id"), CONSTRAINT "REL_5f9688929761f7df108b630e64" UNIQUE ("line_item_id"), CONSTRAINT "PK_d6eb138f77ffdee83567b85af0c" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE TABLE "order_edit" ("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(), "order_id" character varying NOT NULL, "internal_note" character varying, "created_by" character varying NOT NULL, "requested_by" character varying, "requested_at" TIMESTAMP WITH TIME ZONE, "confirmed_by" character varying, "confirmed_at" TIMESTAMP WITH TIME ZONE, "declined_by" character varying, "declined_reason" character varying, "declined_at" TIMESTAMP WITH TIME ZONE, "canceled_by" character varying, "canceled_at" TIMESTAMP WITH TIME ZONE, CONSTRAINT "PK_58ab6acf2e84b4e827f5f846f7a" PRIMARY KEY ("id"))` - ) - - await queryRunner.query( - `ALTER TABLE "order_item_change" ADD CONSTRAINT "FK_44feeebb258bf4cfa4cc4202281" FOREIGN KEY ("order_edit_id") REFERENCES "order_edit"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "order_item_change" ADD CONSTRAINT "FK_b4d53b8d03c9f5e7d4317e818d9" FOREIGN KEY ("original_line_item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "order_item_change" ADD CONSTRAINT "FK_5f9688929761f7df108b630e64a" FOREIGN KEY ("line_item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "order_edit" ADD CONSTRAINT "FK_1f3a251488a91510f57e1bf93cd" FOREIGN KEY ("order_id") REFERENCES "order"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "order_edit" DROP CONSTRAINT "FK_1f3a251488a91510f57e1bf93cd"` - ) - await queryRunner.query( - `ALTER TABLE "order_item_change" DROP CONSTRAINT "FK_5f9688929761f7df108b630e64a"` - ) - await queryRunner.query( - `ALTER TABLE "order_item_change" DROP CONSTRAINT "FK_b4d53b8d03c9f5e7d4317e818d9"` - ) - await queryRunner.query( - `ALTER TABLE "order_item_change" DROP CONSTRAINT "FK_44feeebb258bf4cfa4cc4202281"` - ) - - await queryRunner.query(`DROP TABLE "order_edit"`) - await queryRunner.query(`DROP TABLE "order_item_change"`) - await queryRunner.query(`DROP TYPE "order_item_change_type_enum"`) - } -} diff --git a/packages/medusa/src/migrations/1663059812400-linte-item-original-item-relation.ts b/packages/medusa/src/migrations/1663059812400-linte-item-original-item-relation.ts deleted file mode 100644 index 23200d95a6..0000000000 --- a/packages/medusa/src/migrations/1663059812400-linte-item-original-item-relation.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class lineItemOriginalItemRelation1663059812400 - implements MigrationInterface -{ - name = "lineItemOriginalItemRelation1663059812400" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item" - ADD COLUMN IF NOT EXISTS original_item_id character varying, - ADD COLUMN IF NOT EXISTS order_edit_id character varying` - ) - - await queryRunner.query( - `ALTER TABLE "line_item" - ADD CONSTRAINT "line_item_original_item_fk" FOREIGN KEY ("original_item_id") REFERENCES "line_item" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - await queryRunner.query( - `ALTER TABLE "line_item" - ADD CONSTRAINT "line_item_order_edit_fk" FOREIGN KEY ("order_edit_id") REFERENCES "order_edit" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - - await queryRunner.query( - `CREATE UNIQUE INDEX "unique_li_original_item_id_order_edit_id" ON "line_item" ("order_edit_id", "original_item_id") WHERE original_item_id IS NOT NULL AND order_edit_id IS NOT NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `DROP INDEX IF EXISTS "unique_li_original_item_id_order_edit_id"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP CONSTRAINT "line_item_original_item_fk"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP CONSTRAINT "line_item_order_edit_fk"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP COLUMN "original_item_id"` - ) - await queryRunner.query( - `ALTER TABLE "line_item" DROP COLUMN "order_edit_id"` - ) - } -} diff --git a/packages/medusa/src/migrations/1664880666982-payment-collection.ts b/packages/medusa/src/migrations/1664880666982-payment-collection.ts deleted file mode 100644 index 7af8e1131b..0000000000 --- a/packages/medusa/src/migrations/1664880666982-payment-collection.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class paymentCollection1664880666982 implements MigrationInterface { - name = "paymentCollection1664880666982" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - CREATE TYPE "PAYMENT_COLLECTION_TYPE_ENUM" AS ENUM ('order_edit'); - - CREATE TYPE "PAYMENT_COLLECTION_STATUS_ENUM" AS ENUM ( - 'not_paid', 'awaiting', 'authorized', - 'partially_authorized', 'canceled' - ); - - CREATE TABLE IF NOT EXISTS payment_collection - ( - 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 NULL, - type "PAYMENT_COLLECTION_TYPE_ENUM" NOT NULL, - status "PAYMENT_COLLECTION_STATUS_ENUM" NOT NULL, - description text NULL, - amount integer NOT NULL, - authorized_amount integer NULL, - region_id character varying NOT NULL, - currency_code character varying NOT NULL, - metadata jsonb NULL, - created_by character varying NOT NULL, - CONSTRAINT "PK_payment_collection_id" PRIMARY KEY ("id") - ); - CREATE INDEX "IDX_payment_collection_region_id" ON "payment_collection" ("region_id") WHERE deleted_at IS NULL; - CREATE INDEX "IDX_payment_collection_currency_code" ON "payment_collection" ("currency_code") WHERE deleted_at IS NULL; - - ALTER TABLE "payment_collection" ADD CONSTRAINT "FK_payment_collection_region_id" FOREIGN KEY ("region_id") REFERENCES "region"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - - - CREATE TABLE payment_collection_sessions - ( - payment_collection_id CHARACTER VARYING NOT NULL, - payment_session_id CHARACTER VARYING NOT NULL, - CONSTRAINT "PK_payment_collection_sessions" PRIMARY KEY ("payment_collection_id", "payment_session_id") - ); - CREATE INDEX "IDX_payment_collection_sessions_payment_collection_id" ON "payment_collection_sessions" ("payment_collection_id"); - CREATE INDEX "IDX_payment_collection_sessions_payment_session_id" ON "payment_collection_sessions" ("payment_session_id"); - - ALTER TABLE "payment_collection_sessions" ADD CONSTRAINT "FK_payment_collection_sessions_payment_collection_id" FOREIGN KEY ("payment_collection_id") REFERENCES "payment_collection"("id") ON DELETE CASCADE ON UPDATE NO ACTION; - ALTER TABLE "payment_collection_sessions" ADD CONSTRAINT "FK_payment_collection_sessions_payment_session_id" FOREIGN KEY ("payment_session_id") REFERENCES "payment_session"("id") ON DELETE CASCADE ON UPDATE NO ACTION; - - - CREATE TABLE payment_collection_payments - ( - payment_collection_id CHARACTER VARYING NOT NULL, - payment_id CHARACTER VARYING NOT NULL, - CONSTRAINT "PK_payment_collection_payments" PRIMARY KEY ("payment_collection_id", "payment_id") - ); - CREATE INDEX "IDX_payment_collection_payments_payment_collection_id" ON "payment_collection_payments" ("payment_collection_id"); - CREATE INDEX "IDX_payment_collection_payments_payment_id" ON "payment_collection_payments" ("payment_id"); - - ALTER TABLE "payment_collection_payments" ADD CONSTRAINT "FK_payment_collection_payments_payment_collection_id" FOREIGN KEY ("payment_collection_id") REFERENCES "payment_collection"("id") ON DELETE CASCADE ON UPDATE NO ACTION; - ALTER TABLE "payment_collection_payments" ADD CONSTRAINT "FK_payment_collection_payments_payment_id" FOREIGN KEY ("payment_id") REFERENCES "payment"("id") ON DELETE CASCADE ON UPDATE NO ACTION; - - - ALTER TABLE order_edit ADD COLUMN payment_collection_id character varying NULL; - CREATE INDEX "IDX_order_edit_payment_collection_id" ON "order_edit" ("payment_collection_id"); - ALTER TABLE "order_edit" ADD CONSTRAINT "FK_order_edit_payment_collection_id" FOREIGN KEY ("payment_collection_id") REFERENCES "payment_collection"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - - ALTER TABLE payment_session ADD COLUMN payment_authorized_at timestamp WITH time zone NULL; - ALTER TABLE payment_session ADD COLUMN amount integer NULL; - ALTER TABLE payment_session ALTER COLUMN cart_id DROP NOT NULL; - - ALTER TABLE refund ADD COLUMN payment_id character varying NULL; - CREATE INDEX "IDX_refund_payment_id" ON "refund" ("payment_id"); - ALTER TABLE "refund" ADD CONSTRAINT "FK_refund_payment_id" FOREIGN KEY ("payment_id") REFERENCES "payment"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - ALTER TABLE refund ALTER COLUMN order_id DROP NOT NULL; - `) - - // Add missing indexes - await queryRunner.query(` - CREATE INDEX "IDX_order_edit_order_id" ON "order_edit" ("order_id"); - CREATE INDEX "IDX_money_amount_currency_code" ON "money_amount" ("currency_code"); - CREATE INDEX "IDX_order_currency_code" ON "order" ("currency_code"); - CREATE INDEX "IDX_payment_currency_code" ON "payment" ("currency_code"); - CREATE INDEX "IDX_region_currency_code" ON "region" ("currency_code"); - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX "IDX_order_edit_payment_collection_id"; - ALTER TABLE order_edit DROP CONSTRAINT "FK_order_edit_payment_collection_id"; - - DROP INDEX "IDX_refund_payment_id"; - ALTER TABLE refund DROP CONSTRAINT "FK_refund_payment_id"; - ALTER TABLE refund ALTER COLUMN order_id SET NOT NULL; - - ALTER TABLE payment_collection DROP CONSTRAINT "FK_payment_collection_region_id"; - ALTER TABLE payment_collection_sessions DROP CONSTRAINT "FK_payment_collection_sessions_payment_collection_id"; - ALTER TABLE payment_collection_sessions DROP CONSTRAINT "FK_payment_collection_sessions_payment_session_id"; - ALTER TABLE payment_collection_payments DROP CONSTRAINT "FK_payment_collection_payments_payment_collection_id"; - ALTER TABLE payment_collection_payments DROP CONSTRAINT "FK_payment_collection_payments_payment_id"; - ALTER TABLE order_edit DROP COLUMN payment_collection_id; - ALTER TABLE payment_session DROP COLUMN payment_authorized_at; - ALTER TABLE payment_session DROP COLUMN amount; - ALTER TABLE payment_session ALTER COLUMN cart_id SET NOT NULL; - ALTER TABLE refund DROP COLUMN payment_id; - - DROP TABLE payment_collection; - DROP TABLE payment_collection_sessions; - DROP TABLE payment_collection_payments; - - DROP TYPE "PAYMENT_COLLECTION_TYPE_ENUM"; - DROP TYPE "PAYMENT_COLLECTION_STATUS_ENUM"; - `) - - await queryRunner.query(` - DROP INDEX "IDX_order_edit_order_id"; - DROP INDEX "IDX_money_amount_currency_code"; - DROP INDEX "IDX_order_currency_code"; - DROP INDEX "IDX_payment_currency_code"; - DROP INDEX "IDX_region_currency_code"; - `) - } -} diff --git a/packages/medusa/src/migrations/1666173221888-add_analytics_config.ts b/packages/medusa/src/migrations/1666173221888-add_analytics_config.ts deleted file mode 100644 index e4bbba185c..0000000000 --- a/packages/medusa/src/migrations/1666173221888-add_analytics_config.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" -import AnalyticsFeatureFlag from "../loaders/feature-flags/analytics" - -export const featureFlag = AnalyticsFeatureFlag.key - -export class addAnalyticsConfig1666173221888 implements MigrationInterface { - name = "addAnalyticsConfig1666173221888" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "analytics_config" ("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, "user_id" character varying NOT NULL, "opt_out" boolean NOT NULL DEFAULT false, "anonymize" boolean NOT NULL DEFAULT false, CONSTRAINT "PK_93505647c5d7cb479becb810b0f" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_379ca70338ce9991f3affdeedf" ON "analytics_config" ("id", "user_id") WHERE deleted_at IS NULL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `DROP INDEX "IDX_379ca70338ce9991f3affdeedf"` - ) - await queryRunner.query(`DROP TABLE "analytics_config"`) - } -} diff --git a/packages/medusa/src/migrations/1667815005070-publishable_api_key.ts b/packages/medusa/src/migrations/1667815005070-publishable_api_key.ts deleted file mode 100644 index 0562a1b9f9..0000000000 --- a/packages/medusa/src/migrations/1667815005070-publishable_api_key.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class publishableApiKey1667815005070 implements MigrationInterface { - name = "publishableApiKey1667815005070" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "publishable_api_key_sales_channel" ("sales_channel_id" character varying NOT NULL, "publishable_key_id" character varying NOT NULL, CONSTRAINT "PK_68eaeb14bdac8954460054c567c" PRIMARY KEY ("sales_channel_id", "publishable_key_id"))` - ) - await queryRunner.query( - `CREATE TABLE "publishable_api_key" ("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(), "created_by" character varying, "revoked_by" character varying, "revoked_at" TIMESTAMP WITH TIME ZONE, "title" character varying NOT NULL, CONSTRAINT "PK_9e613278673a87de92c606b4494" PRIMARY KEY ("id"))` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP TABLE "publishable_api_key"`) - await queryRunner.query(`DROP TABLE "publishable_api_key_sales_channel"`) - } -} diff --git a/packages/medusa/src/migrations/1669032280562-update_customer_email_constraint.ts b/packages/medusa/src/migrations/1669032280562-update_customer_email_constraint.ts deleted file mode 100644 index 474932f938..0000000000 --- a/packages/medusa/src/migrations/1669032280562-update_customer_email_constraint.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class updateCustomerEmailConstraint_1669032280562 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `DROP INDEX "IDX_fdb2f3ad8115da4c7718109a6e"` - ) - - await queryRunner.query( - `ALTER TABLE "customer" ADD CONSTRAINT "UQ_unique_email_for_guests_and_customer_accounts" UNIQUE ("email", "has_account")` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "customer" DROP CONSTRAINT "UQ_unique_email_for_guests_and_customer_accounts"` - ) - - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_fdb2f3ad8115da4c7718109a6e" ON "customer" ("email") ` - ) - } -} diff --git a/packages/medusa/src/migrations/1670855241304-add-tax-rate-to-gift-cards.ts b/packages/medusa/src/migrations/1670855241304-add-tax-rate-to-gift-cards.ts deleted file mode 100644 index cf7f8c063c..0000000000 --- a/packages/medusa/src/migrations/1670855241304-add-tax-rate-to-gift-cards.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addTaxRateToGiftCards1670855241304 implements MigrationInterface { - name = "addTaxRateToGiftCards1670855241304" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "gift_card" ADD COLUMN IF NOT EXISTS tax_rate REAL` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "gift_card" DROP COLUMN IF EXISTS "tax_rate"` - ) - } -} diff --git a/packages/medusa/src/migrations/1671711415179-multi_location.ts b/packages/medusa/src/migrations/1671711415179-multi_location.ts deleted file mode 100644 index 7531c8fd1e..0000000000 --- a/packages/medusa/src/migrations/1671711415179-multi_location.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class multiLocation1671711415179 implements MigrationInterface { - name = "multiLocation1671711415179" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `CREATE TABLE "sales_channel_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(), "sales_channel_id" text NOT NULL, "location_id" text NOT NULL, CONSTRAINT "PK_afd2c2c52634bc8280a9c9ee533" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_6caaa358f12ed0b846f00e2dcd" ON "sales_channel_location" ("sales_channel_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c2203162ca946a71aeb98390b0" ON "sales_channel_location" ("location_id") ` - ) - await queryRunner.query( - `CREATE TABLE "product_variant_inventory_item" ("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(), "inventory_item_id" text NOT NULL, "variant_id" text NOT NULL, "quantity" integer NOT NULL DEFAULT '1', CONSTRAINT "UQ_c9be7c1b11a1a729eb51d1b6bca" UNIQUE ("variant_id", "inventory_item_id"), CONSTRAINT "PK_9a1188b8d36f4d198303b4f7efa" PRIMARY KEY ("id"))` - ) - await queryRunner.query( - `CREATE INDEX "IDX_c74e8c2835094a37dead376a3b" ON "product_variant_inventory_item" ("inventory_item_id") ` - ) - await queryRunner.query( - `CREATE INDEX "IDX_bf5386e7f2acc460adbf96d6f3" ON "product_variant_inventory_item" ("variant_id") ` - ) - await queryRunner.query( - `ALTER TABLE "return" ADD "location_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" ADD "location_id" character varying` - ) - await queryRunner.query( - `ALTER TABLE "store" ADD "default_location_id" character varying` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "store" DROP COLUMN "default_location_id"` - ) - await queryRunner.query( - `ALTER TABLE "fulfillment" DROP COLUMN "location_id"` - ) - await queryRunner.query(`ALTER TABLE "return" DROP COLUMN "location_id"`) - await queryRunner.query(`DROP INDEX "IDX_bf5386e7f2acc460adbf96d6f3"`) - await queryRunner.query(`DROP INDEX "IDX_c74e8c2835094a37dead376a3b"`) - await queryRunner.query(`DROP TABLE "product_variant_inventory_item"`) - await queryRunner.query(`DROP INDEX "IDX_c2203162ca946a71aeb98390b0"`) - await queryRunner.query(`DROP INDEX "IDX_6caaa358f12ed0b846f00e2dcd"`) - await queryRunner.query(`DROP TABLE "sales_channel_location"`) - } -} diff --git a/packages/medusa/src/migrations/1672906846559-product-category.ts b/packages/medusa/src/migrations/1672906846559-product-category.ts deleted file mode 100644 index 1e9688921f..0000000000 --- a/packages/medusa/src/migrations/1672906846559-product-category.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class productCategory1672906846559 implements MigrationInterface { - name = "productCategory1672906846559" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - CREATE TABLE "product_category" - ( - "id" character varying NOT NULL, - "name" text NOT NULL, - "handle" text NOT NULL, - "parent_category_id" character varying, - "mpath" text, - "is_active" boolean DEFAULT false, - "is_internal" boolean DEFAULT false, - "deleted_at" TIMESTAMP WITH TIME ZONE, - "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - CONSTRAINT "PK_qgguwbn1cwstxk93efl0px9oqwt" PRIMARY KEY ("id") - ) - `) - - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_product_category_handle" ON "product_category" ("handle") WHERE deleted_at IS NULL` - ) - - await queryRunner.query( - `CREATE INDEX "IDX_product_category_path" ON "product_category" ("mpath")` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_product_category_path"`) - await queryRunner.query(`DROP INDEX "IDX_product_category_handle"`) - await queryRunner.query(`DROP TABLE "product_category"`) - } -} diff --git a/packages/medusa/src/migrations/1672906846560-payment-session-is-initiated.ts b/packages/medusa/src/migrations/1672906846560-payment-session-is-initiated.ts deleted file mode 100644 index aef377903d..0000000000 --- a/packages/medusa/src/migrations/1672906846560-payment-session-is-initiated.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class PaymentSessionIsInitiated1672906846560 implements MigrationInterface { - name = "paymentSessionIsInitiated1672906846560" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE payment_session ADD COLUMN is_initiated BOOLEAN NOT NULL DEFAULT false - `) - - // Set is_initiated to true if there is more that 0 key in the data. We assume that if data contains any key - // A payment has been initiated to the payment provider - await queryRunner.query(` - UPDATE payment_session SET is_initiated = true WHERE ( - SELECT coalesce(json_array_length(json_agg(keys)), 0) - FROM jsonb_object_keys(data) AS keys (keys) - ) > 0 - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE payment_session DROP COLUMN is_initiated`) - } -} diff --git a/packages/medusa/src/migrations/1673003729870-staged_job_options.ts b/packages/medusa/src/migrations/1673003729870-staged_job_options.ts deleted file mode 100644 index fe43d44d09..0000000000 --- a/packages/medusa/src/migrations/1673003729870-staged_job_options.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class stagedJobOptions1673003729870 implements MigrationInterface { - name = "stagedJobOptions1673003729870" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "staged_job" ADD "options" jsonb NOT NULL DEFAULT '{}'::JSONB` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`ALTER TABLE "staged_job" DROP COLUMN "options"`) - } -} diff --git a/packages/medusa/src/migrations/1673550502785-unique_pay_sess_cart_id.ts b/packages/medusa/src/migrations/1673550502785-unique_pay_sess_cart_id.ts deleted file mode 100644 index 620a0263e6..0000000000 --- a/packages/medusa/src/migrations/1673550502785-unique_pay_sess_cart_id.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm"; - -export class uniquePaySessCartId1673550502785 implements MigrationInterface { - name = 'uniquePaySessCartId1673550502785' - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX IF EXISTS "public"."UniqPaymentSessionCartIdProviderId"`); - await queryRunner.query(`DROP INDEX IF EXISTS "UniqPaymentSessionCartIdProviderId"`); - await queryRunner.query(`CREATE UNIQUE INDEX "UniqPaymentSessionCartIdProviderId" ON "payment_session" ("cart_id", "provider_id") WHERE cart_id IS NOT NULL`); - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "public"."UniqPaymentSessionCartIdProviderId"`); - await queryRunner.query(`CREATE UNIQUE INDEX "UniqPaymentSessionCartIdProviderId" ON "payment_session" ("cart_id", "provider_id") `); - } -} diff --git a/packages/medusa/src/migrations/1674455083104-product_category_product.ts b/packages/medusa/src/migrations/1674455083104-product_category_product.ts deleted file mode 100644 index 2227cecb6c..0000000000 --- a/packages/medusa/src/migrations/1674455083104-product_category_product.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm"; - -export class productCategoryProduct1674455083104 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - ` - CREATE TABLE "product_category_product" ( - "product_category_id" character varying NOT NULL, - "product_id" character varying NOT NULL, - CONSTRAINT "FK_product_category_id" FOREIGN KEY ("product_category_id") REFERENCES product_category("id") ON DELETE CASCADE ON UPDATE NO ACTION, - CONSTRAINT "FK_product_id" FOREIGN KEY ("product_id") REFERENCES product("id") ON DELETE CASCADE ON UPDATE NO ACTION - ) - ` - ) - - await queryRunner.query( - ` - CREATE UNIQUE INDEX "IDX_upcp_product_id_product_category_id" - ON "product_category_product" ("product_category_id", "product_id") - ` - ) - - await queryRunner.query( - ` - CREATE INDEX "IDX_pcp_product_category_id" - ON "product_category_product" ("product_category_id") - ` - ) - - await queryRunner.query( - ` - CREATE INDEX "IDX_pcp_product_id" - ON "product_category_product" ("product_id") - ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX "IDX_upcp_product_id_product_category_id"`) - await queryRunner.query(`DROP INDEX "IDX_pcp_product_category_id"`) - await queryRunner.query(`DROP INDEX "IDX_pcp_product_id"`) - - await queryRunner.query(`DROP TABLE "product_category_product"`) - } -} diff --git a/packages/medusa/src/migrations/1675689306130-multi_location_soft_delete.ts b/packages/medusa/src/migrations/1675689306130-multi_location_soft_delete.ts deleted file mode 100644 index 7f1643cf77..0000000000 --- a/packages/medusa/src/migrations/1675689306130-multi_location_soft_delete.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class multiLocationSoftDelete1675689306130 - implements MigrationInterface -{ - name = "multiLocationSoftDelete1675689306130" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE sales_channel_location - ADD COLUMN "deleted_at" TIMESTAMP WITH TIME ZONE; - - DROP INDEX "IDX_6caaa358f12ed0b846f00e2dcd"; - DROP INDEX "IDX_c2203162ca946a71aeb98390b0"; - - CREATE INDEX "IDX_sales_channel_location_sales_channel_id" ON "sales_channel_location" ("sales_channel_id") WHERE deleted_at IS NULL; - CREATE INDEX "IDX_sales_channel_location_location_id" ON "sales_channel_location" ("location_id") WHERE deleted_at IS NULL; - - ALTER TABLE product_variant_inventory_item - ADD COLUMN "deleted_at" TIMESTAMP WITH TIME ZONE; - - DROP INDEX "IDX_c74e8c2835094a37dead376a3b"; - DROP INDEX "IDX_bf5386e7f2acc460adbf96d6f3"; - - CREATE INDEX "IDX_product_variant_inventory_item_inventory_item_id" ON "product_variant_inventory_item" ("inventory_item_id") WHERE deleted_at IS NULL; - CREATE INDEX "IDX_product_variant_inventory_item_variant_id" ON "product_variant_inventory_item" ("variant_id") WHERE deleted_at IS NULL; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX "IDX_sales_channel_location_sales_channel_id"; - DROP INDEX "IDX_sales_channel_location_location_id"; - - DROP INDEX "IDX_product_variant_inventory_item_inventory_item_id"; - DROP INDEX "IDX_product_variant_inventory_item_variant_id"; - - CREATE INDEX "IDX_6caaa358f12ed0b846f00e2dcd" ON "sales_channel_location" ("sales_channel_id"); - CREATE INDEX "IDX_c2203162ca946a71aeb98390b0" ON "sales_channel_location" ("location_id"); - - CREATE INDEX "IDX_c74e8c2835094a37dead376a3b" ON "product_variant_inventory_item" ("inventory_item_id"); - CREATE INDEX "IDX_bf5386e7f2acc460adbf96d6f3" ON "product_variant_inventory_item" ("variant_id"); - - ALTER TABLE sales_channel_location - DROP COLUMN "deleted_at"; - - ALTER TABLE product_variant_inventory_item - DROP COLUMN "deleted_at"; - `) - } -} diff --git a/packages/medusa/src/migrations/1677234878504-product_category_rank.ts b/packages/medusa/src/migrations/1677234878504-product_category_rank.ts deleted file mode 100644 index a63a81cd0c..0000000000 --- a/packages/medusa/src/migrations/1677234878504-product_category_rank.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class productCategoryRank1677234878504 implements MigrationInterface { - name = "productCategoryRank1677234878504" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "product_category" - ADD COLUMN "rank" integer DEFAULT '0' NOT NULL CHECK ("rank" >= 0); - `) - - await queryRunner.query(` - CREATE UNIQUE INDEX "UniqProductCategoryParentIdRank" - ON "product_category" ("parent_category_id", "rank"); - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX "UniqProductCategoryParentIdRank"; - `) - await queryRunner.query(` - ALTER TABLE "product_category" DROP COLUMN "rank"; - `) - } -} diff --git a/packages/medusa/src/migrations/1678093365811-ensure_required_quantity.ts b/packages/medusa/src/migrations/1678093365811-ensure_required_quantity.ts deleted file mode 100644 index b07fca4b3d..0000000000 --- a/packages/medusa/src/migrations/1678093365811-ensure_required_quantity.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class ensureRequiredQuantity1678093365811 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DO - $$ - BEGIN - ALTER TABLE product_variant_inventory_item - RENAME COLUMN quantity TO required_quantity; - EXCEPTION - WHEN undefined_column THEN - END; - $$; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DO - $$ - BEGIN - ALTER TABLE product_variant_inventory_item - RENAME COLUMN required_quantity TO quantity; - EXCEPTION - WHEN undefined_column THEN - END; - $$; - `) - } -} diff --git a/packages/medusa/src/migrations/1678093365812-line-item-adjustments-amount.ts b/packages/medusa/src/migrations/1678093365812-line-item-adjustments-amount.ts deleted file mode 100644 index 93ed4bd95c..0000000000 --- a/packages/medusa/src/migrations/1678093365812-line-item-adjustments-amount.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class lineItemAdjustmentsAmount1678093365812 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE line_item_adjustment ALTER COLUMN amount TYPE NUMERIC; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE line_item_adjustment ALTER COLUMN amount TYPE integer; - `) - } -} diff --git a/packages/medusa/src/migrations/1679950221063-category-remove-soft-delete.ts b/packages/medusa/src/migrations/1679950221063-category-remove-soft-delete.ts deleted file mode 100644 index 37fd79f2b0..0000000000 --- a/packages/medusa/src/migrations/1679950221063-category-remove-soft-delete.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class categoryRemoveSoftDelete1679950221063 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DELETE FROM "product_category" WHERE "deleted_at" IS NOT NULL;`) - await queryRunner.query(`ALTER TABLE "product_category" DROP COLUMN "deleted_at";`) - await queryRunner.query(`DROP INDEX IF EXISTS "IDX_product_category_handle";`) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_product_category_handle" ON "product_category" ("handle");` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX IF EXISTS "IDX_product_category_handle";`) - await queryRunner.query(`ALTER TABLE "product_category" ADD COLUMN "deleted_at" timestamp with time zone;`) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_product_category_handle" ON "product_category" ("handle") WHERE deleted_at IS NULL;` - ) - } -} diff --git a/packages/medusa/src/migrations/1679950645253-category-create-indexes.ts b/packages/medusa/src/migrations/1679950645253-category-create-indexes.ts deleted file mode 100644 index 33cea8ba15..0000000000 --- a/packages/medusa/src/migrations/1679950645253-category-create-indexes.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class categoryCreateIndexes1679950645253 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - CREATE INDEX "IDX_product_category_active_public" ON "product_category" ( - "parent_category_id", - "is_active", - "is_internal" - ) WHERE ( - ("is_active" IS TRUE) AND - ("is_internal" IS FALSE) - ); - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX "IDX_product_category_active_public"; - `) - } -} diff --git a/packages/medusa/src/migrations/1679950645254-product-domain-impoved-indexes.ts b/packages/medusa/src/migrations/1679950645254-product-domain-impoved-indexes.ts deleted file mode 100644 index bbc572998b..0000000000 --- a/packages/medusa/src/migrations/1679950645254-product-domain-impoved-indexes.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class productDomainImprovedIndexes1679950645254 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - // If you want to reset it to 'on' run 'set enable_nestloop to on;' - // Improve large IN queries, since we have separate queries every time it is better to turn it off - await queryRunner.query(` - /* You can turn of this settings if you are in a context with lots of variants) set enable_nestloop to off; */ - - DROP INDEX IF EXISTS "IDX_17a06d728e4cfbc5bd2ddb70af"; - CREATE INDEX IF NOT EXISTS idx_money_amount_variant_id ON money_amount (variant_id); - - DROP INDEX IF EXISTS "IDX_b433e27b7a83e6d12ab26b15b0"; - CREATE INDEX IF NOT EXISTS idx_money_amount_region_id ON money_amount (region_id); - - DROP INDEX IF EXISTS "IDX_7234ed737ff4eb1b6ae6e6d7b0"; - CREATE INDEX IF NOT EXISTS idx_product_option_value_variant_id ON product_option_value (variant_id); - - DROP INDEX IF EXISTS "IDX_cdf4388f294b30a25c627d69fe"; - CREATE INDEX IF NOT EXISTS idx_product_option_value_option_id ON product_option_value (option_id); - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX IF EXISTS idx_money_amount_variant_id; - DROP INDEX IF EXISTS idx_money_amount_region_id; - DROP INDEX IF EXISTS idx_product_option_value_variant_id; - DROP INDEX IF EXISTS idx_product_option_value_option_id; - - CREATE INDEX IF NOT EXISTS "IDX_17a06d728e4cfbc5bd2ddb70af" ON "money_amount" ("variant_id"); - CREATE INDEX IF NOT EXISTS "IDX_b433e27b7a83e6d12ab26b15b0" ON "money_amount" ("region_id"); - CREATE INDEX IF NOT EXISTS "IDX_7234ed737ff4eb1b6ae6e6d7b0" ON "product_option_value" ("variant_id"); - CREATE INDEX IF NOT EXISTS "IDX_cdf4388f294b30a25c627d69fe" ON "product_option_value" ("option_id"); - `) - } -} diff --git a/packages/medusa/src/migrations/1679950645254-product-search-gin-indexes.ts b/packages/medusa/src/migrations/1679950645254-product-search-gin-indexes.ts deleted file mode 100644 index 906c96136e..0000000000 --- a/packages/medusa/src/migrations/1679950645254-product-search-gin-indexes.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class productSearchGinIndexes1679950645254 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - try { - await queryRunner.query(` - CREATE EXTENSION IF NOT EXISTS pg_trgm; - - CREATE INDEX IF NOT EXISTS idx_gin_product_title ON product USING gin (title gin_trgm_ops) WHERE deleted_at is null; - CREATE INDEX IF NOT EXISTS idx_gin_product_description ON product USING gin (description gin_trgm_ops) WHERE deleted_at is null; - - CREATE INDEX IF NOT EXISTS idx_gin_product_variant_title ON product_variant USING gin (title gin_trgm_ops) WHERE deleted_at is null; - CREATE INDEX IF NOT EXISTS idx_gin_product_variant_sku ON product_variant USING gin (sku gin_trgm_ops) WHERE deleted_at is null; - - CREATE INDEX IF NOT EXISTS idx_gin_product_collection ON product_collection USING gin (title gin_trgm_ops) WHERE deleted_at is null; - `) - } catch (e) { - // noop - // The extension might not be installed, in that case do nothing except warn - console.warn("Could not create pg_trgm extension or indexes, skipping. If you want to use the pg_trgm extension, please install it manually and then run the migration productSearchGinIndexes1679950645254.") - } - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX IF EXISTS idx_gin_product_title; - DROP INDEX IF EXISTS idx_gin_product_description; - DROP INDEX IF EXISTS idx_gin_product_variant_title; - DROP INDEX IF EXISTS idx_gin_product_variant_sku; - DROP INDEX IF EXISTS idx_gin_product_collection; - `) - } -} diff --git a/packages/medusa/src/migrations/1680714052628-add_sales_channel_metadata.ts b/packages/medusa/src/migrations/1680714052628-add_sales_channel_metadata.ts deleted file mode 100644 index c516dddb4a..0000000000 --- a/packages/medusa/src/migrations/1680714052628-add_sales_channel_metadata.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" -import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels" - -export const featureFlag = SalesChannelFeatureFlag.key - -export class addSalesChannelMetadata1680714052628 - implements MigrationInterface -{ - name = "addSalesChannelMetadata1680714052628" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "sales_channel" ADD COLUMN "metadata" jsonb NULL;` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "sales_channel" DROP COLUMN "metadata"` - ) - } -} diff --git a/packages/medusa/src/migrations/1680857773272-add-description-to-product-category.ts b/packages/medusa/src/migrations/1680857773272-add-description-to-product-category.ts deleted file mode 100644 index 8ccc1fe1d6..0000000000 --- a/packages/medusa/src/migrations/1680857773272-add-description-to-product-category.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addDescriptionToProductCategory1680857773272 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_category" ADD COLUMN IF NOT EXISTS "description" TEXT NOT NULL DEFAULT ''` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_category" DROP COLUMN IF EXISTS "description"` - ) - } -} diff --git a/packages/medusa/src/migrations/1680857773272-line-item-tax-adjustment-on-cascade-delete.ts b/packages/medusa/src/migrations/1680857773272-line-item-tax-adjustment-on-cascade-delete.ts deleted file mode 100644 index 943e4d847b..0000000000 --- a/packages/medusa/src/migrations/1680857773272-line-item-tax-adjustment-on-cascade-delete.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class lineItemTaxAdjustmentOnCascadeDelete1680857773272 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" DROP CONSTRAINT IF EXISTS "FK_5077fa54b0d037e984385dfe8ad"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" ADD CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" DROP CONSTRAINT IF EXISTS "FK_be9aea2ccf3567007b6227da4d2"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" ADD CONSTRAINT "FK_be9aea2ccf3567007b6227da4d2" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE CASCADE ON UPDATE NO ACTION` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" DROP CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_tax_line" ADD CONSTRAINT "FK_5077fa54b0d037e984385dfe8ad" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" DROP CONSTRAINT "FK_be9aea2ccf3567007b6227da4d2"` - ) - await queryRunner.query( - `ALTER TABLE "line_item_adjustment" ADD CONSTRAINT "FK_be9aea2ccf3567007b6227da4d2" FOREIGN KEY ("item_id") REFERENCES "line_item"("id") ON DELETE NO ACTION ON UPDATE NO ACTION` - ) - } -} diff --git a/packages/medusa/src/migrations/1680857773273-add-table-product-shipping-profile.ts b/packages/medusa/src/migrations/1680857773273-add-table-product-shipping-profile.ts deleted file mode 100644 index 334000fca0..0000000000 --- a/packages/medusa/src/migrations/1680857773273-add-table-product-shipping-profile.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class addTableProductShippingProfile1680857773273 - implements MigrationInterface -{ - name = "addTableProductShippingProfile1680857773273" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - ` - CREATE TABLE IF NOT EXISTS "product_shipping_profile" - ( - "profile_id" text NOT NULL, - "product_id" text NOT NULL - ); - - INSERT INTO "product_shipping_profile" ("profile_id", "product_id") - SELECT "profile_id", "id" FROM "product"; - - ALTER TABLE "product" DROP COLUMN IF EXISTS "profile_id"; - CREATE UNIQUE INDEX IF NOT EXISTS "idx_product_shipping_profile_profile_id_product_id_unique" ON "product_shipping_profile" ("profile_id", "product_id"); - CREATE INDEX IF NOT EXISTS "idx_product_shipping_profile_product_id" ON "product_shipping_profile" ("product_id"); - CREATE INDEX IF NOT EXISTS "idx_product_shipping_profile_profile_id" ON "product_shipping_profile" ("profile_id"); - DROP INDEX IF EXISTS "IDX_80823b7ae866dc5acae2dac6d2"; - ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX IF EXISTS "idx_product_shipping_profile_profile_id_product_id_unique"; - DROP INDEX IF EXISTS "idx_product_shipping_profile_product_id"; - DROP INDEX IF EXISTS "idx_product_shipping_profile_profile_id"; - - ALTER TABLE "product" ADD COLUMN IF NOT EXISTS "profile_id" CHARACTER VARYING; - - UPDATE "product" SET "profile_id" = "product_shipping_profile"."profile_id" - FROM "product_shipping_profile" - WHERE "product"."id" = "product_shipping_profile"."product_id"; - - DROP TABLE IF EXISTS "product_shipping_profile"; - - ALTER TABLE "product" ALTER COLUMN profile_id SET NOT NULL; - - CREATE INDEX IF NOT EXISTS "IDX_80823b7ae866dc5acae2dac6d2" ON "product" ("profile_id"); - ALTER TABLE "product" ADD CONSTRAINT "FK_80823b7ae866dc5acae2dac6d2c" FOREIGN KEY ("profile_id") REFERENCES "shipping_profile"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - `) - } -} diff --git a/packages/medusa/src/migrations/1680857773273-drop-product-id-fk-sales-channels.ts b/packages/medusa/src/migrations/1680857773273-drop-product-id-fk-sales-channels.ts deleted file mode 100644 index 57cffea2b9..0000000000 --- a/packages/medusa/src/migrations/1680857773273-drop-product-id-fk-sales-channels.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class dropProductIdFkSalesChannels1680857773273 - implements MigrationInterface -{ - name = "dropProductIdFkSalesChannels1680857773273" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - alter table if exists "product_sales_channel" drop constraint if exists "FK_5a4d5e1e60f97633547821ec8d6"; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE if exists "product_sales_channel" ADD CONSTRAINT if not exists "FK_5a4d5e1e60f97633547821ec8d6" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE cascade ON UPDATE NO ACTION; - `) - } -} diff --git a/packages/medusa/src/migrations/1680857773273-drop-variant-id-fk-money-amount.ts b/packages/medusa/src/migrations/1680857773273-drop-variant-id-fk-money-amount.ts deleted file mode 100644 index f544ce52ec..0000000000 --- a/packages/medusa/src/migrations/1680857773273-drop-variant-id-fk-money-amount.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class dropVariantIdFkMoneyAmount1680857773273 - implements MigrationInterface -{ - name = "dropVariantIdFkMoneyAmount1680857773273" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - ` - alter table if exists "money_amount" drop constraint if exists "FK_17a06d728e4cfbc5bd2ddb70af0"; - ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE if exists "money_amount" ADD CONSTRAINT if not exists "FK_17a06d728e4cfbc5bd2ddb70af0" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE cascade ON UPDATE NO ACTION; - `) - } -} diff --git a/packages/medusa/src/migrations/1692870898423-update_return_reason_index.ts b/packages/medusa/src/migrations/1692870898423-update_return_reason_index.ts deleted file mode 100644 index 699e44db82..0000000000 --- a/packages/medusa/src/migrations/1692870898423-update_return_reason_index.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class UpdateReturnReasonIndex1692870898423 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `DROP INDEX IF EXISTS "IDX_00605f9d662c06b81c1b60ce24";` - ) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_return_reason_value" ON "return_reason" ("value") WHERE deleted_at IS NULL;` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(`DROP INDEX IF EXISTS "IDX_return_reason_value";`) - await queryRunner.query( - `CREATE UNIQUE INDEX "IDX_00605f9d662c06b81c1b60ce24" ON "return_reason" ("value") ` - ) - } -} diff --git a/packages/medusa/src/migrations/1692870898424-line-item-product-id.ts b/packages/medusa/src/migrations/1692870898424-line-item-product-id.ts deleted file mode 100644 index 8a491eb331..0000000000 --- a/packages/medusa/src/migrations/1692870898424-line-item-product-id.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class LineItemProductId1692870898424 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "line_item" DROP CONSTRAINT IF EXISTS "FK_5371cbaa3be5200f373d24e3d5b"; - ALTER TABLE "line_item" ADD COLUMN IF NOT EXISTS "product_id" text; - - UPDATE "line_item" SET "product_id" = pv."product_id" - FROM "product_variant" pv - WHERE "line_item"."variant_id" = "pv"."id"; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "line_item" DROP COLUMN IF EXISTS "product_id"; - ALTER TABLE "line_item" ADD CONSTRAINT "FK_5371cbaa3be5200f373d24e3d5b" FOREIGN KEY ("variant_id") REFERENCES "product_variant" ("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - `) - } -} diff --git a/packages/medusa/src/migrations/1692870898425-add-timestemps-to-product-shipping-profiles.ts b/packages/medusa/src/migrations/1692870898425-add-timestemps-to-product-shipping-profiles.ts deleted file mode 100644 index 1bd78fa418..0000000000 --- a/packages/medusa/src/migrations/1692870898425-add-timestemps-to-product-shipping-profiles.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class AddTimestempsToProductShippingProfiles1692870898425 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "product_shipping_profile" ADD COLUMN IF NOT EXISTS "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "product_shipping_profile" ADD COLUMN IF NOT EXISTS "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "product_shipping_profile" ADD COLUMN IF NOT EXISTS "deleted_at" TIMESTAMP WITH TIME ZONE; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "product_shipping_profile" DROP COLUMN IF NOT EXISTS "created_at"; - ALTER TABLE "product_shipping_profile" DROP COLUMN IF NOT EXISTS "updated_at"; - ALTER TABLE "product_shipping_profile" DROP COLUMN IF NOT EXISTS "deleted_at"; - `) - } -} diff --git a/packages/medusa/src/migrations/1692953518123-drop_money_amount_constraints_for_pricing_module.ts b/packages/medusa/src/migrations/1692953518123-drop_money_amount_constraints_for_pricing_module.ts deleted file mode 100644 index dad775b78e..0000000000 --- a/packages/medusa/src/migrations/1692953518123-drop_money_amount_constraints_for_pricing_module.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class dropMoneyAmountConstraintsForPricingModule1692953518123 - implements MigrationInterface -{ - name = "dropMoneyAmountConstraintsForPricingModule1692953518123" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - ` - CREATE TABLE IF NOT EXISTS "product_variant_money_amount" - ( - "id" character varying NOT NULL, - "money_amount_id" text NOT NULL, - "variant_id" text NOT NULL, - "deleted_at" TIMESTAMP WITH TIME ZONE, - "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), - CONSTRAINT "PK_product_variant_money_amount" PRIMARY KEY ("id") - ); - - INSERT INTO "product_variant_money_amount"("id", "money_amount_id", "variant_id") - SELECT CONCAT('pvma_', id), "id", "variant_id" FROM "money_amount"; - - ALTER TABLE "money_amount" DROP COLUMN IF EXISTS "variant_id"; - CREATE UNIQUE INDEX IF NOT EXISTS "idx_product_variant_money_amount_money_amount_id_unique" ON "product_variant_money_amount" ("money_amount_id"); - CREATE INDEX IF NOT EXISTS "idx_product_variant_money_amount_variant_id" ON "product_variant_money_amount" ("variant_id"); - ` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - ` - DROP INDEX IF EXISTS "idx_product_variant_money_amount_money_amount_id_unique"; - DROP INDEX IF EXISTS "idx_product_variant_money_amount_variant_id"; - - ALTER TABLE "money_amount" ADD COLUMN IF NOT EXISTS "variant_id" text; - - UPDATE "money_amount" SET "variant_id" = "product_variant_money_amount"."variant_id" - FROM "product_variant_money_amount" - WHERE "money_amount"."id" = "product_variant_money_amount"."money_amount_id"; - - DROP TABLE IF EXISTS "product_variant_money_amount"; - - CREATE INDEX IF NOT EXISTS idx_product_variant_money_amount_id ON money_amount (variant_id); - ALTER TABLE "money_amount" ADD CONSTRAINT "FK_17a06d728e4cfbc5bd2ddb70af0" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - ` - ) - } -} diff --git a/packages/medusa/src/migrations/1694602553610-drop-fks-isolated-product.ts b/packages/medusa/src/migrations/1694602553610-drop-fks-isolated-product.ts deleted file mode 100644 index c3e49b2247..0000000000 --- a/packages/medusa/src/migrations/1694602553610-drop-fks-isolated-product.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class dropFksIsolatedProducts1694602553610 - implements MigrationInterface -{ - name = "dropFksIsolatedProducts1694602553610" - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE IF EXISTS "product_tax_rate" DROP CONSTRAINT IF EXISTS "FK_1d04aebeabb6a89f87e536a124d"; - ALTER TABLE IF EXISTS "product_type_tax_rate" DROP CONSTRAINT IF EXISTS "FK_25a3138bb236f63d9bb6c8ff111"; - ALTER TABLE IF EXISTS "claim_item" DROP CONSTRAINT IF EXISTS "FK_64980511ca32c8e92b417644afa"; - ALTER TABLE IF EXISTS "discount_condition_product" DROP CONSTRAINT IF EXISTS "FK_c759f53b2e48e8cfb50638fe4e0"; - ALTER TABLE IF EXISTS "discount_condition_product_collection" DROP CONSTRAINT IF EXISTS "FK_a0b05dc4257abe639cb75f8eae2"; - ALTER TABLE IF EXISTS "discount_condition_product_tag" DROP CONSTRAINT IF EXISTS "FK_01486cc9dc6b36bf658685535f6"; - ALTER TABLE IF EXISTS "discount_condition_product_type" DROP CONSTRAINT IF EXISTS "FK_e706deb68f52ab2756119b9e704"; - ALTER TABLE IF EXISTS "discount_rule_products" DROP CONSTRAINT IF EXISTS "FK_be66106a673b88a81c603abe7eb"; - - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE IF EXISTS "product_tax_rate" ADD CONSTRAINT "FK_1d04aebeabb6a89f87e536a124d" FOREIGN KEY ("product_id") REFERENCES "product"("id") ON DELETE cascade ON UPDATE NO ACTION; - ALTER TABLE IF EXISTS "product_type_tax_rate" ADD CONSTRAINT "FK_25a3138bb236f63d9bb6c8ff111" FOREIGN KEY ("product_type_id") REFERENCES "product_type"("id") ON DELETE cascade ON UPDATE NO ACTION; - ALTER TABLE IF EXISTS "claim_item" ADD CONSTRAINT "FK_64980511ca32c8e92b417644afa" FOREIGN KEY ("variant_id") REFERENCES "product_variant"("id") ON UPDATE NO ACTION ON DELETE NO ACTION; - ALTER TABLE IF EXISTS discount_condition_product ADD CONSTRAINT "FK_c759f53b2e48e8cfb50638fe4e0" FOREIGN KEY (product_id) REFERENCES product (id) ON UPDATE NO ACTION ON DELETE CASCADE; - ALTER TABLE IF EXISTS discount_condition_product_collection ADD CONSTRAINT "FK_a0b05dc4257abe639cb75f8eae2" FOREIGN KEY (product_collection_id) REFERENCES product_collection (id) ON UPDATE NO ACTION ON DELETE CASCADE; - ALTER TABLE IF EXISTS discount_condition_product_tag ADD CONSTRAINT "FK_01486cc9dc6b36bf658685535f6" FOREIGN KEY (product_tag_id) REFERENCES product_tag (id) ON UPDATE NO ACTION ON DELETE CASCADE; - ALTER TABLE IF EXISTS discount_condition_product_type ADD CONSTRAINT "FK_e706deb68f52ab2756119b9e704" FOREIGN KEY (product_type_id) REFERENCES product_type (id) ON UPDATE NO ACTION ON DELETE CASCADE; - ALTER TABLE IF EXISTS discount_rule_products ADD CONSTRAINT "FK_be66106a673b88a81c603abe7eb" FOREIGN KEY (product_id) REFERENCES product (id) ON UPDATE NO ACTION ON DELETE CASCADE; - `) - } -} diff --git a/packages/medusa/src/migrations/1698056997411-product-sales-channels-link.ts b/packages/medusa/src/migrations/1698056997411-product-sales-channels-link.ts deleted file mode 100644 index 7c4da3a180..0000000000 --- a/packages/medusa/src/migrations/1698056997411-product-sales-channels-link.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class ProductSalesChannelsLink1698056997411 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "product_sales_channel" ADD COLUMN IF NOT EXISTS "id" text; - UPDATE "product_sales_channel" SET "id" = 'prodsc_' || substr(md5(random()::text), 0, 27) WHERE id is NULL; - ALTER TABLE "product_sales_channel" ALTER COLUMN "id" SET NOT NULL; - - ALTER TABLE "product_sales_channel" DROP CONSTRAINT IF EXISTS "PK_fd29b6a8bd641052628dee19583"; - ALTER TABLE "product_sales_channel" ADD CONSTRAINT "product_sales_channel_pk" PRIMARY KEY (id); - ALTER TABLE "product_sales_channel" ADD CONSTRAINT "product_sales_channel_product_id_sales_channel_id_unique" UNIQUE (product_id, sales_channel_id); - - ALTER TABLE "product_sales_channel" ADD COLUMN IF NOT EXISTS "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "product_sales_channel" ADD COLUMN IF NOT EXISTS "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "product_sales_channel" ADD COLUMN IF NOT EXISTS "deleted_at" TIMESTAMP WITH TIME ZONE; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE product_sales_channel DROP CONSTRAINT IF EXISTS "product_sales_channel_pk"; - ALTER TABLE product_sales_channel DROP CONSTRAINT IF EXISTS "product_sales_channel_product_id_sales_channel_id_unique"; - ALTER TABLE product_sales_channel drop column if exists "id"; - - ALTER TABLE "product_sales_channel" DROP COLUMN IF EXISTS "created_at"; - ALTER TABLE "product_sales_channel" DROP COLUMN IF EXISTS "updated_at"; - ALTER TABLE "product_sales_channel" DROP COLUMN IF EXISTS "deleted_at"; - - ALTER TABLE product_sales_channel ADD CONSTRAINT "PK_product_sales_channel" PRIMARY KEY (product_id, sales_channel_id); - `) - } -} diff --git a/packages/medusa/src/migrations/1699371074198-drop-non-null-constraint-price-list.ts b/packages/medusa/src/migrations/1699371074198-drop-non-null-constraint-price-list.ts deleted file mode 100644 index ea69625625..0000000000 --- a/packages/medusa/src/migrations/1699371074198-drop-non-null-constraint-price-list.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class DropNonNullConstraintPriceList1699371074198 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE IF EXISTS price_list ALTER COLUMN name DROP NOT NULL; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE IF EXISTS price_list ALTER COLUMN name SET NOT NULL; - `) - } -} diff --git a/packages/medusa/src/migrations/1699564794649-add-metadata-to-product-category.ts b/packages/medusa/src/migrations/1699564794649-add-metadata-to-product-category.ts deleted file mode 100644 index 8205f36910..0000000000 --- a/packages/medusa/src/migrations/1699564794649-add-metadata-to-product-category.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class AddMetadataToProductCategory1699564794649 implements MigrationInterface { - - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_category" ADD COLUMN "metadata" jsonb NULL;` - ) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query( - `ALTER TABLE "product_category" DROP COLUMN "metadata"` - ) - } - -} diff --git a/packages/medusa/src/migrations/1701860329931-order-sales-channels-link.ts b/packages/medusa/src/migrations/1701860329931-order-sales-channels-link.ts deleted file mode 100644 index d005e813f4..0000000000 --- a/packages/medusa/src/migrations/1701860329931-order-sales-channels-link.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -import SalesChannelFeatureFlag from "../loaders/feature-flags/sales-channels" - -export const featureFlag = [SalesChannelFeatureFlag.key] - -export class OrderSalesChannelLink1701860329931 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - CREATE TABLE IF NOT EXISTS "order_sales_channel" - ( - "id" character varying NOT NULL, - "order_id" character varying NOT NULL, - "sales_channel_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, - CONSTRAINT "order_sales_channel_pk" PRIMARY KEY ("order_id", "sales_channel_id"), - CONSTRAINT "order_sales_channel_order_id_unique" UNIQUE ("order_id") - ); - CREATE INDEX IF NOT EXISTS "IDX_id_order_sales_channel" ON "order_sales_channel" ("id"); - - insert into "order_sales_channel" (id, order_id, sales_channel_id) - (select 'ordersc_' || substr(md5(random()::text), 0, 27), id, sales_channel_id from "order" WHERE sales_channel_id IS NOT NULL); - - ALTER TABLE "order" DROP CONSTRAINT IF EXISTS "FK_6ff7e874f01b478c115fdd462eb"; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - UPDATE "order" - SET "sales_channel_id" = "order_sales_channel"."sales_channel_id" - FROM "order_sales_channel" - WHERE "order"."id" = "order_sales_channel"."order_id"; - - DROP TABLE IF EXISTS "order_sales_channel"; - - ALTER TABLE "order" ADD CONSTRAINT "FK_6ff7e874f01b478c115fdd462eb" FOREIGN KEY ("sales_channel_id") REFERENCES "sales_channel"("id") ON DELETE NO ACTION ON UPDATE NO ACTION; - `) - } -} diff --git a/packages/medusa/src/migrations/1701894188811-publishable-key-sales-channels-link.ts b/packages/medusa/src/migrations/1701894188811-publishable-key-sales-channels-link.ts deleted file mode 100644 index 017645c1fe..0000000000 --- a/packages/medusa/src/migrations/1701894188811-publishable-key-sales-channels-link.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class PublishableKeySalesChannelLink1701894188811 - implements MigrationInterface -{ - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "publishable_api_key_sales_channel" ADD COLUMN IF NOT EXISTS "id" text; - UPDATE "publishable_api_key_sales_channel" SET "id" = 'pksc_' || substr(md5(random()::text), 0, 27) WHERE id is NULL; - ALTER TABLE "publishable_api_key_sales_channel" ALTER COLUMN "id" SET NOT NULL; - - CREATE INDEX IF NOT EXISTS "IDX_id_publishable_api_key_sales_channel" ON "publishable_api_key_sales_channel" ("id"); - - ALTER TABLE "publishable_api_key_sales_channel" ADD COLUMN IF NOT EXISTS "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "publishable_api_key_sales_channel" ADD COLUMN IF NOT EXISTS "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(); - ALTER TABLE "publishable_api_key_sales_channel" ADD COLUMN IF NOT EXISTS "deleted_at" TIMESTAMP WITH TIME ZONE; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - DROP INDEX IF EXISTS "IDX_id_publishable_api_key_sales_channel"; - ALTER TABLE "publishable_api_key_sales_channel" DROP COLUMN IF EXISTS "id"; - ALTER TABLE "publishable_api_key_sales_channel" DROP COLUMN IF EXISTS "created_at"; - ALTER TABLE "publishable_api_key_sales_channel" DROP COLUMN IF EXISTS "updated_at"; - ALTER TABLE "publishable_api_key_sales_channel" DROP COLUMN IF EXISTS "deleted_at"; - `) - } -} diff --git a/packages/medusa/src/migrations/1709888477798-alter-customer-unique-constraint.ts b/packages/medusa/src/migrations/1709888477798-alter-customer-unique-constraint.ts deleted file mode 100644 index 70258ccc1a..0000000000 --- a/packages/medusa/src/migrations/1709888477798-alter-customer-unique-constraint.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { MigrationInterface, QueryRunner } from "typeorm" - -export class AlterCustomerUniqueConstraint1709888477798 implements MigrationInterface { - public async up(queryRunner: QueryRunner): Promise { - await queryRunner.query(` - ALTER TABLE "customer" DROP CONSTRAINT "UQ_unique_email_for_guests_and_customer_accounts"; - - CREATE UNIQUE INDEX "IDX_unique_email_for_guests_and_customer_accounts" ON "customer" ("email", "has_account") WHERE "deleted_at" IS NULL; - `) - } - - public async down(queryRunner: QueryRunner): Promise { - // ensure we dont have duplicated email,has_account to avoid violation of the previous unique constraint - await queryRunner.query(` - WITH RankedCustomers AS ( - SELECT - id, - ROW_NUMBER() OVER ( - PARTITION BY email, has_account - ORDER BY CASE WHEN deleted_at IS NULL THEN 0 ELSE 1 END, id - ) AS rn - FROM - customer - ) - DELETE FROM customer - WHERE id IN ( - SELECT id FROM RankedCustomers WHERE rn > 1 - ); - `); - - await queryRunner.query(` - DROP INDEX "IDX_unique_email_for_guests_and_customer_accounts"; - - ALTER TABLE "customer" ADD CONSTRAINT "UQ_unique_email_for_guests_and_customer_accounts" UNIQUE ("email", "has_account"); - `) - } -} diff --git a/packages/medusa/src/models/idempotency-key.ts b/packages/medusa/src/models/idempotency-key.ts deleted file mode 100644 index 437389cee0..0000000000 --- a/packages/medusa/src/models/idempotency-key.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { - BeforeInsert, - Column, - CreateDateColumn, - Entity, - Index, - PrimaryColumn, -} from "typeorm" -import { DbAwareColumn, resolveDbType } from "../utils/db-aware-column" - -import { generateEntityId } from "../utils/generate-entity-id" - -@Entity() -export class IdempotencyKey { - @PrimaryColumn() - id: string - - @Index({ unique: true }) - @Column() - idempotency_key: string - - @CreateDateColumn({ type: resolveDbType("timestamptz") }) - created_at: Date - - @DbAwareColumn({ type: "timestamptz", nullable: true }) - locked_at: Date - - @Column({ nullable: true }) - request_method: string - - @DbAwareColumn({ type: "jsonb", nullable: true }) - request_params: Record - - @Column({ nullable: true }) - request_path: string - - @Column({ type: "int", nullable: true }) - response_code: number - - @DbAwareColumn({ type: "jsonb", nullable: true }) - response_body: Record - - @Column({ default: "started" }) - recovery_point: string - - /** - * @apiIgnore - */ - @BeforeInsert() - private beforeInsert(): void { - this.id = generateEntityId(this.id, "ikey") - } -} - -/** - * @schema IdempotencyKey - * title: "Idempotency Key" - * description: "Idempotency Key is used to continue a process in case of any failure that might occur." - * type: object - * required: - * - created_at - * - id - * - idempotency_key - * - locked_at - * - recovery_point - * - response_code - * - response_body - * - request_method - * - request_params - * - request_path - * properties: - * id: - * description: The idempotency key's ID - * type: string - * example: ikey_01G8X9A7ESKAJXG2H0E6F1MW7A - * idempotency_key: - * description: The unique randomly generated key used to determine the state of a process. - * type: string - * externalDocs: - * url: https://docs.medusajs.com/development/idempotency-key/overview.md - * description: Learn more how to use the idempotency key. - * created_at: - * description: Date which the idempotency key was locked. - * type: string - * format: date-time - * locked_at: - * description: Date which the idempotency key was locked. - * nullable: true - * type: string - * format: date-time - * request_method: - * description: The method of the request - * nullable: true - * type: string - * example: POST - * request_params: - * description: The parameters passed to the request - * nullable: true - * type: object - * example: - * id: cart_01G8ZH853Y6TFXWPG5EYE81X63 - * request_path: - * description: The request's path - * nullable: true - * type: string - * example: /store/carts/cart_01G8ZH853Y6TFXWPG5EYE81X63/complete - * response_code: - * description: The response's code. - * nullable: true - * type: string - * example: 200 - * response_body: - * description: The response's body - * nullable: true - * type: object - * example: - * id: cart_01G8ZH853Y6TFXWPG5EYE81X63 - * recovery_point: - * description: Where to continue from. - * type: string - * default: started - */ diff --git a/packages/medusa/src/models/index.ts b/packages/medusa/src/models/index.ts deleted file mode 100644 index 93db1cf7c0..0000000000 --- a/packages/medusa/src/models/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./idempotency-key" -export * from "./staged-job" diff --git a/packages/medusa/src/models/staged-job.ts b/packages/medusa/src/models/staged-job.ts deleted file mode 100644 index ac2810ec05..0000000000 --- a/packages/medusa/src/models/staged-job.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { BeforeInsert, Column, Entity, PrimaryColumn } from "typeorm" - -import { DbAwareColumn } from "../utils/db-aware-column" -import { generateEntityId } from "../utils/generate-entity-id" - -@Entity() -export class StagedJob { - @PrimaryColumn() - id: string - - @Column() - event_name: string - - @DbAwareColumn({ type: "jsonb" }) - data: Record - - @DbAwareColumn({ type: "jsonb", default: {} }) - options: Record - - /** - * @apiIgnore - */ - @BeforeInsert() - private beforeInsert(): void { - this.id = generateEntityId(this.id, "job") - } -} - -/** - * @schema StagedJob - * title: "Staged Job" - * description: "A staged job resource" - * type: object - * required: - * - data - * - event_name - * - id - * - options - * properties: - * id: - * description: The staged job's ID - * type: string - * example: job_01F0YET7BZTARY9MKN1SJ7AAXF - * event_name: - * description: The name of the event - * type: string - * example: order.placed - * data: - * description: Data necessary for the job - * type: object - * example: {} - * option: - * description: The staged job's option - * type: object - * example: {} - */ diff --git a/packages/medusa/src/modules-config.ts b/packages/medusa/src/modules-config.ts deleted file mode 100644 index 19887336a3..0000000000 --- a/packages/medusa/src/modules-config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { MedusaModuleConfig, Modules } from "@medusajs/modules-sdk" - -const modules: MedusaModuleConfig = { - [Modules.PRODUCT]: true, - [Modules.PRICING]: true, -} - -export default modules diff --git a/packages/medusa/src/repositories/__mocks__/cart.js b/packages/medusa/src/repositories/__mocks__/cart.js deleted file mode 100644 index 5d76f57cfa..0000000000 --- a/packages/medusa/src/repositories/__mocks__/cart.js +++ /dev/null @@ -1,461 +0,0 @@ -import { IdMap } from "medusa-test-utils" -import { discounts } from "./discount" - -export const carts = { - emptyCart: { - _id: IdMap.getId("emptyCart"), - title: "test", - region_id: IdMap.getId("testRegion"), - items: [], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - withShippingOptions: { - _id: IdMap.getId("withShippingOptions"), - title: "test", - region_id: IdMap.getId("region-france"), - items: [], - shipping_options: [ - { - _id: IdMap.getId("freeShipping"), - name: "Free Shipping", - region_id: IdMap.getId("testRegion"), - price: 10, - provider_id: "test_shipper", - }, - { - _id: IdMap.getId("expensiveShipping"), - name: "Expensive Shipping", - region_id: IdMap.getId("testRegion"), - price: 100, - provider_id: "test_shipper", - }, - ], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - cartWithPaySessionsDifRegion: { - _id: IdMap.getId("cartWithPaySessionsDifRegion"), - region_id: IdMap.getId("region-france"), - total: 1, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - payment_sessions: [ - { - provider_id: "default_provider", - data: { - id: "default_provider_session", - }, - }, - { - provider_id: "unregistered", - data: { - id: "unregistered_session", - }, - }, - ], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - cartWithPaySessions: { - _id: IdMap.getId("cartWithPaySessions"), - total: 1, - region_id: IdMap.getId("testRegion"), - shipping_methods: [], - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - payment_sessions: [ - { - provider_id: "default_provider", - data: { - id: "default_provider_session", - }, - }, - { - provider_id: "unregistered", - data: { - id: "unregistered_session", - }, - }, - ], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - cartWithLine: { - _id: IdMap.getId("cartWithLine"), - total: 1, - title: "test", - region_id: IdMap.getId("testRegion"), - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - }, - { - _id: IdMap.getId("itemToRemove"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 1, - }, - ], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - withGiftCard: { - _id: IdMap.getId("withGiftCard"), - region_id: IdMap.getId("region-france"), - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - is_giftcard: false, - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - }, - { - _id: IdMap.getId("giftline"), - title: "GiftCard", - description: "Gift card line", - thumbnail: "test-img-yeah.com/thumb", - metadata: { - name: "Test Name", - }, - is_giftcard: true, - content: { - unit_price: 100, - variant: { - _id: IdMap.getId("giftCardVar"), - }, - product: { - _id: IdMap.getId("giftCardProd"), - }, - quantity: 1, - }, - quantity: 1, - }, - ], - email: "test", - payment_sessions: [ - { - provider_id: "default_provider", - data: { - money_id: "success", - }, - }, - ], - payment_method: { - provider_id: "default_provider", - data: { - money_id: "success", - }, - }, - shipping_methods: [ - { - provider_id: "gls", - data: { - yes: "sir", - }, - }, - ], - shipping_address: { - first_name: "hi", - last_name: "you", - country_code: "DK", - city: "of lights", - address_1: "You bet street", - postal_code: "4242", - }, - billing_address: { - first_name: "hi", - last_name: "you", - country_code: "DK", - city: "of lights", - address_1: "You bet street", - postal_code: "4242", - }, - discounts: [], - customer_id: "", - }, - completeCart: { - _id: IdMap.getId("complete-cart"), - region_id: IdMap.getId("region-france"), - items: [{ data: "items" }], - email: "test", - payment_sessions: [ - { - provider_id: "default_provider", - data: { - money_id: "success", - }, - }, - ], - payment_method: { - provider_id: "default_provider", - data: { - money_id: "success", - }, - }, - shipping_methods: [ - { - provider_id: "gls", - data: { - yes: "sir", - }, - }, - ], - shipping_address: { - first_name: "hi", - last_name: "you", - country_code: "DK", - city: "of lights", - address_1: "You bet street", - postal_code: "4242", - }, - billing_address: { - first_name: "hi", - last_name: "you", - country_code: "DK", - city: "of lights", - address_1: "You bet street", - postal_code: "4242", - }, - discounts: [], - customer_id: "", - }, - frCart: { - _id: IdMap.getId("fr-cart"), - title: "test", - region_id: IdMap.getId("region-france"), - items: [ - { - _id: IdMap.getId("line"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: [ - { - unit_price: 8, - variant: { - _id: IdMap.getId("eur-8-us-10"), - }, - product: { - _id: IdMap.getId("product1"), - }, - quantity: 1, - }, - { - unit_price: 10, - variant: { - _id: IdMap.getId("eur-10-us-12"), - }, - product: { - _id: IdMap.getId("product1"), - }, - quantity: 1, - }, - ], - quantity: 10, - }, - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 10, - variant: { - _id: IdMap.getId("eur-10-us-12"), - }, - product: { - _id: IdMap.getId("product2"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - shipping_methods: [ - { - _id: IdMap.getId("freeShipping"), - profile_id: IdMap.getId("default_profile"), - }, - ], - shipping_options: [ - { - _id: IdMap.getId("freeShipping"), - profile_id: "default_profile", - }, - ], - shipping_address: {}, - billing_address: {}, - discounts: [], - customer_id: "", - }, - discountCartWithExisting: { - _id: IdMap.getId("discount-cart-with-existing"), - discounts: [discounts.item10Percent], - region_id: IdMap.getId("region-france"), - items: [ - { - _id: IdMap.getId("line"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: [ - { - unit_price: 8, - variant: { - _id: IdMap.getId("eur-8-us-10"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - { - unit_price: 10, - variant: { - _id: IdMap.getId("eur-10-us-12"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - ], - quantity: 10, - }, - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 10, - variant: { - _id: IdMap.getId("eur-10-us-12"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - }, -} - -export const CartModelMock = { - create: jest.fn().mockImplementation(data => Promise.resolve(data)), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve(update) - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("withShippingOptions")) { - return Promise.resolve(carts.withShippingOptions) - } - if (query._id === IdMap.getId("cartWithPaySessionsDifRegion")) { - return Promise.resolve(carts.cartWithPaySessionsDifRegion) - } - if (query._id === IdMap.getId("cartWithPaySessions")) { - return Promise.resolve(carts.cartWithPaySessions) - } - if (query._id === IdMap.getId("emptyCart")) { - return Promise.resolve(carts.emptyCart) - } - if (query._id === IdMap.getId("cartWithLine")) { - return Promise.resolve(carts.cartWithLine) - } - if (query._id === IdMap.getId("fr-cart")) { - return Promise.resolve(carts.frCart) - } - if (query._id === IdMap.getId("complete-cart")) { - return Promise.resolve(carts.completeCart) - } - if (query._id === IdMap.getId("discount-cart-with-existing")) { - return Promise.resolve(carts.discountCartWithExisting) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/customer.js b/packages/medusa/src/repositories/__mocks__/customer.js deleted file mode 100644 index 7fac374649..0000000000 --- a/packages/medusa/src/repositories/__mocks__/customer.js +++ /dev/null @@ -1,52 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const customers = { - testCustomer: { - _id: IdMap.getId("testCustomer"), - email: "oliver@medusa.com", - first_name: "Oliver", - last_name: "Juhl", - billingAddress: {}, - password_hash: "123456789", - }, - deleteCustomer: { - _id: IdMap.getId("deleteId"), - email: "oliver@medusa.com", - first_name: "Oliver", - last_name: "Juhl", - billingAddress: {}, - password_hash: "123456789", - }, - customerWithPhone: { - _id: IdMap.getId("customerWithPhone"), - email: "oliver@medusa.com", - first_name: "Oliver", - last_name: "Juhl", - billingAddress: {}, - password_hash: "123456789", - phone: "12345678", - }, -} - -export const CustomerModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query.email === "oliver@medusa.com") { - return Promise.resolve(customers.testCustomer) - } - if (query.phone === "12345678") { - return Promise.resolve(customers.customerWithPhone) - } - if (query._id === IdMap.getId("testCustomer")) { - return Promise.resolve(customers.testCustomer) - } - if (query._id === IdMap.getId("deleteId")) { - return Promise.resolve(customers.deleteCustomer) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/discount.js b/packages/medusa/src/repositories/__mocks__/discount.js deleted file mode 100644 index 632583477a..0000000000 --- a/packages/medusa/src/repositories/__mocks__/discount.js +++ /dev/null @@ -1,153 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const discounts = { - dynamic: { - _id: IdMap.getId("dynamic"), - code: "Something", - is_dynamic: true, - rule: { - type: "percentage", - allocation: "total", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - total10Percent: { - _id: IdMap.getId("total10"), - code: "10%OFF", - rule: { - type: "percentage", - allocation: "total", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - item10Percent: { - _id: IdMap.getId("item10Percent"), - code: "MEDUSA", - rule: { - type: "percentage", - allocation: "item", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - total10Fixed: { - _id: IdMap.getId("total10Fixed"), - code: "MEDUSA", - rule: { - type: "fixed", - allocation: "total", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - item9Fixed: { - _id: IdMap.getId("item9Fixed"), - code: "MEDUSA", - rule: { - type: "fixed", - allocation: "item", - value: 9, - }, - regions: [IdMap.getId("region-france")], - }, - item2Fixed: { - _id: IdMap.getId("item2Fixed"), - code: "MEDUSA", - rule: { - type: "fixed", - allocation: "item", - value: 2, - }, - regions: [IdMap.getId("region-france")], - }, - item10FixedNoVariants: { - _id: IdMap.getId("item10FixedNoVariants"), - code: "MEDUSA", - rule: { - type: "fixed", - allocation: "item", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - expiredDiscount: { - _id: IdMap.getId("expired"), - code: "MEDUSA", - ends_at: new Date("December 17, 1995 03:24:00"), - rule: { - type: "fixed", - allocation: "item", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - freeShipping: { - _id: IdMap.getId("freeshipping"), - code: "FREESHIPPING", - rule: { - type: "free_shipping", - allocation: "total", - value: 10, - }, - regions: [IdMap.getId("region-france")], - }, - USDiscount: { - _id: IdMap.getId("us-discount"), - code: "US10", - rule: { - type: "free_shipping", - allocation: "total", - value: 10, - }, - regions: [IdMap.getId("us")], - }, - alreadyExists: { - code: "ALREADYEXISTS", - rule: { - type: "percentage", - allocation: "total", - value: 20, - }, - regions: [IdMap.getId("fr-cart")], - }, -} - -export const DiscountModelMock = { - create: jest.fn().mockImplementation((data) => Promise.resolve(data)), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation((query) => { - if (query._id === IdMap.getId("dynamic")) { - return Promise.resolve(discounts.dynamic) - } - if (query._id === IdMap.getId("total10")) { - return Promise.resolve(discounts.total10Percent) - } - if (query._id === IdMap.getId("item10Percent")) { - return Promise.resolve(discounts.item10Percent) - } - if (query._id === IdMap.getId("total10Fixed")) { - return Promise.resolve(discounts.total10Fixed) - } - if (query._id === IdMap.getId("item2Fixed")) { - return Promise.resolve(discounts.item2Fixed) - } - if (query._id === IdMap.getId("item10FixedNoVariants")) { - return Promise.resolve(discounts.item10FixedNoVariants) - } - if (query._id === IdMap.getId("expired")) { - return Promise.resolve(discounts.expiredDiscount) - } - if (query.code === "10%OFF") { - return Promise.resolve(discounts.total10Percent) - } - if (query.code === "aLrEaDyExIsts") { - return Promise.resolve(discounts.alreadyExists) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/document.js b/packages/medusa/src/repositories/__mocks__/document.js deleted file mode 100644 index b020ee5b57..0000000000 --- a/packages/medusa/src/repositories/__mocks__/document.js +++ /dev/null @@ -1,15 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const documents = [ - { - _id: IdMap.getId("doc"), - name: "test doc", - base_64: "verylongstring", - }, -] - -export const DocumentModelMock = { - findOne: jest.fn().mockImplementation(query => { - return Promise.resolve(documents[0]) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/dynamic-discount-code.js b/packages/medusa/src/repositories/__mocks__/dynamic-discount-code.js deleted file mode 100644 index 5514633efe..0000000000 --- a/packages/medusa/src/repositories/__mocks__/dynamic-discount-code.js +++ /dev/null @@ -1,25 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const dynamicDiscounts = { - dynamicOff: { - _id: IdMap.getId("dynamicOff"), - discount_id: IdMap.getId("dynamic"), - code: "DYNAMICOFF", - disabled: false, - usage_count: 0, - }, -} - -export const DynamicDiscountCodeModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query.code === "DYNAMICOFF") { - return Promise.resolve(dynamicDiscounts.dynamicOff) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/money-amount.js b/packages/medusa/src/repositories/__mocks__/money-amount.js deleted file mode 100644 index 892d8e745a..0000000000 --- a/packages/medusa/src/repositories/__mocks__/money-amount.js +++ /dev/null @@ -1,31 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const moneyAmounts = { - amountOne: { - id: IdMap.getId("amountOne"), - currency_code: "USD", - amount: 1, - min_quantity: 1, - max_quantity: 10, - price_list_id: null, - } -} - -export const MoneyAmountModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("amountOne")) { - return Promise.resolve(moneyAmounts.amountOne) - } - return Promise.resolve(undefined) - }), - addToPriceList: jest.fn().mockImplementation((priceListId, prices, overrideExisting) => { - return Promise.resolve() - }), - deletePriceListPrices: jest.fn().mockImplementation((priceListId, moneyAmountIds) => { - return Promise.resolve() - }), - updatePriceListPrices: jest.fn().mockImplementation((priceListId, updates) => { - return Promise.resolve() - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/order.js b/packages/medusa/src/repositories/__mocks__/order.js deleted file mode 100644 index a0d019037b..0000000000 --- a/packages/medusa/src/repositories/__mocks__/order.js +++ /dev/null @@ -1,514 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const orders = { - testOrder: { - _id: IdMap.getId("test-order"), - email: "oliver@test.dk", - billing_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - shipping_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - }, - fulfilled_quantity: 0, - quantity: 10, - }, - ], - region_id: IdMap.getId("region-france"), - customer_id: IdMap.getId("test-customer"), - payment_method: { - provider_id: "default_provider", - }, - shipping_methods: [ - { - _id: IdMap.getId("expensiveShipping"), - name: "Expensive Shipping", - price: 100, - provider_id: "default_provider", - profile_id: IdMap.getId("default"), - data: { - extra: "hi", - }, - }, - ], - fulfillments: [ - { - _id: IdMap.getId("fulfillment"), - provider_id: "default_provider", - data: {}, - }, - ], - fulfillment_status: "not_fulfilled", - payment_status: "awaiting", - status: "pending", - metadata: { - cart_id: IdMap.getId("test-cart"), - }, - }, - processedOrder: { - _id: IdMap.getId("processed-order"), - email: "oliver@test.dk", - tax_rate: 0, - billing_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - shipping_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - returned_quantity: 0, - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - region_id: IdMap.getId("region-france"), - customer_id: IdMap.getId("test-customer"), - payment_method: { - provider_id: "default_provider", - data: { - hi: "hi", - }, - }, - shipping_methods: [ - { - _id: IdMap.getId("expensiveShipping"), - name: "Expensive Shipping", - price: 100, - provider_id: "default_provider", - profile_id: IdMap.getId("default"), - }, - { - _id: IdMap.getId("freeShipping"), - name: "Free Shipping", - price: 10, - provider_id: "default_provider", - profile_id: IdMap.getId("profile1"), - }, - ], - fulfillment_status: "fulfilled", - payment_status: "captured", - status: "completed", - }, - returnedOrder: { - _id: IdMap.getId("returned-order"), - email: "oliver@test.dk", - billing_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - shipping_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - returned_quantity: 0, - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - }, - quantity: 10, - }, - ], - region_id: IdMap.getId("region-france"), - customer_id: IdMap.getId("test-customer"), - payment_method: { - provider_id: "default_provider", - data: { - hi: "hi", - }, - }, - returns: [ - { - _id: IdMap.getId("return"), - status: "requested", - shipping_method: { - _id: IdMap.getId("return-shipping"), - is_return: true, - name: "Return Shipping", - region_id: IdMap.getId("region-france"), - profile_id: IdMap.getId("default-profile"), - data: { - id: "return_shipment", - }, - price: 2, - provider_id: "default_provider", - }, - shipping_data: { - id: "return_shipment", - shipped: true, - }, - documents: ["doc1234"], - items: [ - { - item_id: IdMap.getId("existingLine"), - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - }, - is_requested: true, - quantity: 10, - }, - ], - refund_amount: 1228, - }, - ], - shipping_methods: [ - { - _id: IdMap.getId("expensiveShipping"), - name: "Expensive Shipping", - price: 100, - provider_id: "default_provider", - profile_id: IdMap.getId("default"), - }, - { - _id: IdMap.getId("freeShipping"), - name: "Free Shipping", - price: 10, - provider_id: "default_provider", - profile_id: IdMap.getId("profile1"), - }, - ], - fulfillment_status: "fulfilled", - payment_status: "captured", - status: "completed", - }, - orderToRefund: { - _id: IdMap.getId("refund-order"), - email: "oliver@test.dk", - tax_rate: 0.25, - billing_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - shipping_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 100, - variant: { - _id: IdMap.getId("eur-8-us-10"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - returned_quantity: 0, - }, - { - _id: IdMap.getId("existingLine2"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 100, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - quantity: 10, - returned_quantity: 0, - metadata: {}, - }, - ], - region_id: IdMap.getId("region-france"), - customer_id: IdMap.getId("test-customer"), - payment_method: { - provider_id: "default_provider", - }, - returns: [ - { - _id: IdMap.getId("return"), - status: "requested", - shipping_method: { - _id: IdMap.getId("return-shipping"), - is_return: true, - name: "Return Shipping", - region_id: IdMap.getId("region-france"), - profile_id: IdMap.getId("default-profile"), - data: { - id: "return_shipment", - }, - price: 2, - provider_id: "default_provider", - }, - shipping_data: { - id: "return_shipment", - shipped: true, - }, - documents: ["doc1234"], - items: [ - { - item_id: IdMap.getId("existingLine"), - content: { - unit_price: 100, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("product"), - }, - quantity: 1, - }, - is_requested: true, - quantity: 2, - metadata: {}, - }, - ], - refund_amount: 246, - }, - ], - shipping_methods: [ - { - provider_id: "default_provider", - profile_id: IdMap.getId("default"), - data: {}, - items: {}, - }, - ], - discounts: [], - }, - shippedOrder: { - _id: IdMap.getId("shippedOrder"), - email: "oliver@test.dk", - billing_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - shipping_address: { - first_name: "Oli", - last_name: "Medusa", - address_1: "testaddress", - city: "LA", - country_code: "US", - postal_code: "90002", - }, - items: [ - { - _id: IdMap.getId("existingLine"), - title: "merge line", - description: "This is a new line", - thumbnail: "test-img-yeah.com/thumb", - content: { - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - }, - fulfilled_quantity: 10, - shipped_quantity: 0, - quantity: 10, - }, - ], - region_id: IdMap.getId("region-france"), - customer_id: IdMap.getId("test-customer"), - payment_method: { - provider_id: "default_provider", - }, - shipping_methods: [ - { - _id: IdMap.getId("expensiveShipping"), - name: "Expensive Shipping", - price: 100, - provider_id: "default_provider", - profile_id: IdMap.getId("default"), - data: { - extra: "hi", - }, - }, - ], - fulfillments: [ - { - _id: IdMap.getId("fulfillment"), - provider_id: "default_provider", - data: {}, - items: [ - { - _id: IdMap.getId("existingLine"), - content: { - product: { - _id: IdMap.getId("validId"), - }, - quantity: 1, - unit_price: 123, - variant: { - _id: IdMap.getId("can-cover"), - }, - }, - description: "This is a new line", - fulfilled_quantity: 10, - quantity: 10, - thumbnail: "test-img-yeah.com/thumb", - title: "merge line", - }, - ], - }, - ], - fulfillment_status: "not_fulfilled", - payment_status: "awaiting", - status: "pending", - metadata: { - cart_id: IdMap.getId("test-cart"), - }, - }, -} - -export const OrderModelMock = { - create: jest.fn().mockImplementation(data => Promise.resolve(data)), - updateOne: jest.fn().mockImplementation((query, update) => { - if (query._id === IdMap.getId("returned-order")) { - return Promise.resolve(orders.returnedOrder) - } - if (query._id === IdMap.getId("order-refund")) { - orders.orderToRefund.payment_status = "captured" - return Promise.resolve(orders.orderToRefund) - } - return Promise.resolve({ fulfillments: [] }) - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - startSession: jest.fn().mockReturnValue( - Promise.resolve({ - withTransaction: fn => fn(), - }) - ), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("test-order")) { - orders.testOrder.payment_status = "awaiting" - return Promise.resolve(orders.testOrder) - } - if (query._id === IdMap.getId("not-fulfilled-order")) { - orders.testOrder.fulfillment_status = "not_fulfilled" - orders.testOrder.payment_status = "awaiting" - return Promise.resolve(orders.testOrder) - } - if (query._id === IdMap.getId("fulfilled-order")) { - orders.testOrder.fulfillment_status = "fulfilled" - return Promise.resolve(orders.testOrder) - } - if (query._id === IdMap.getId("payed-order")) { - orders.testOrder.fulfillment_status = "not_fulfilled" - orders.testOrder.payment_status = "captured" - return Promise.resolve(orders.testOrder) - } - if (query._id === IdMap.getId("processed-order")) { - return Promise.resolve(orders.processedOrder) - } - if (query._id === IdMap.getId("returned-order")) { - return Promise.resolve(orders.returnedOrder) - } - if (query._id === IdMap.getId("order-refund")) { - orders.orderToRefund.payment_status = "captured" - return Promise.resolve(orders.orderToRefund) - } - if (query.cart_id === IdMap.getId("test-cart")) { - return Promise.resolve(orders.testOrder) - } - if (query._id === IdMap.getId("shippedOrder")) { - return Promise.resolve(orders.shippedOrder) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/price-list.js b/packages/medusa/src/repositories/__mocks__/price-list.js deleted file mode 100644 index 702ea4da46..0000000000 --- a/packages/medusa/src/repositories/__mocks__/price-list.js +++ /dev/null @@ -1,22 +0,0 @@ -export const PriceListModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query.email === "oliver@medusa.com") { - return Promise.resolve(customers.testCustomer) - } - if (query.phone === "12345678") { - return Promise.resolve(customers.customerWithPhone) - } - if (query._id === IdMap.getId("testCustomer")) { - return Promise.resolve(customers.testCustomer) - } - if (query._id === IdMap.getId("deleteId")) { - return Promise.resolve(customers.deleteCustomer) - } - return Promise.resolve(undefined) - }), -} \ No newline at end of file diff --git a/packages/medusa/src/repositories/__mocks__/product-category.ts b/packages/medusa/src/repositories/__mocks__/product-category.ts deleted file mode 100644 index b345f7e321..0000000000 --- a/packages/medusa/src/repositories/__mocks__/product-category.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { IdMap, MockRepository } from "medusa-test-utils" -import { tempReorderRank } from "../../types/product-category" - -export const validProdCategoryId = "skinny-jeans" -export const invalidProdCategoryId = "not-found" -export const validProdCategoryIdWithChildren = "with-children" -export const validProdCategoryWithSiblings = "with-siblings" -export const validProdCategoryRankChange = "rank-change" -export const validProdCategoryRankParent = "rank-parent" - -const findOneQuery = (query) => { - if (query.where.id === IdMap.getId(invalidProdCategoryId)) { - return null - } - - if (query.where.parent_category_id === IdMap.getId(validProdCategoryIdWithChildren)) { - return null - } - - if (query.where.id === IdMap.getId(validProdCategoryRankChange)) { - return Promise.resolve({ - id: IdMap.getId(validProdCategoryRankChange), - parent_category_id: IdMap.getId(validProdCategoryRankParent), - category_children: [], - rank: 1, - }) - } - - if (query.where.id === IdMap.getId(validProdCategoryWithSiblings)) { - return Promise.resolve({ - id: IdMap.getId(validProdCategoryWithSiblings), - parent_category_id: IdMap.getId(validProdCategoryIdWithChildren), - category_children: [], - }) - } - - if (query.where.id === IdMap.getId(validProdCategoryIdWithChildren)) { - return Promise.resolve({ - id: IdMap.getId(validProdCategoryIdWithChildren), - parent_category_id: null, - category_children: [{ - id: IdMap.getId(validProdCategoryId), - }] - }) - } - - return Promise.resolve({ - id: IdMap.getId(validProdCategoryId), - parent_category_id: null, - category_children: [] - }) -} - -export const productCategoryRepositoryMock = { - ...MockRepository({ - create: () => Promise.resolve({ - id: IdMap.getId(validProdCategoryId) - }), - - save: (record) => Promise.resolve(record), - - findOne: query => { - return findOneQuery(query) - }, - - find: query => { - if (query.where.parent_category_id === IdMap.getId(validProdCategoryRankParent)) { - return Promise.resolve([{ - id: IdMap.getId(validProdCategoryWithSiblings), - parent_category_id: IdMap.getId(validProdCategoryRankParent), - category_children: [], - rank: 0 - }, { - id: IdMap.getId(validProdCategoryRankChange), - parent_category_id: IdMap.getId(validProdCategoryRankParent), - category_children: [], - rank: 1 - }]) - } - - return Promise.resolve([{ - id: IdMap.getId(validProdCategoryWithSiblings), - parent_category_id: null, - category_children: [], - rank: 0 - }, { - id: IdMap.getId(validProdCategoryId), - parent_category_id: null, - category_children: [], - rank: 1 - }]) - }, - - findDescendantsTree: productCategory => { - return Promise.resolve(productCategory) - }, - }), - - findOneWithDescendants: jest.fn().mockImplementation((query) => { - return findOneQuery(query) - }), - - addProducts: jest.fn().mockImplementation((id, productIds) => { - return Promise.resolve() - }), - - removeProducts: jest.fn().mockImplementation((id, productIds) => { - return Promise.resolve() - }), - - getFreeTextSearchResultsAndCount: jest.fn().mockImplementation((query, q, treeSelector = {}) => { - if (q == IdMap.getId(invalidProdCategoryId)) { - return Promise.resolve([[], 0]) - } - - return Promise.resolve([[{ id: IdMap.getId(validProdCategoryId) }], 1]) - }), - - countBy: jest.fn().mockImplementation((args) => { - if (!args.parent_category_id) { - return Promise.resolve(0) - } - - if (args.parent_category_id === IdMap.getId(validProdCategoryRankParent)) { - return Promise.resolve(2) - } - - if (args.parent_category_id === IdMap.getId(validProdCategoryIdWithChildren)) { - return Promise.resolve(1) - } - - return Promise.resolve(1) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/product-variant.js b/packages/medusa/src/repositories/__mocks__/product-variant.js deleted file mode 100644 index e22e4e5a8b..0000000000 --- a/packages/medusa/src/repositories/__mocks__/product-variant.js +++ /dev/null @@ -1,107 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const ProductVariantModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("validId")) { - return Promise.resolve({ - _id: IdMap.getId("validId"), - title: "test", - }) - } - if (query._id === IdMap.getId("testVariant")) { - return Promise.resolve({ - _id: IdMap.getId("testVariant"), - title: "test", - }) - } - if (query._id === IdMap.getId("deleteId")) { - return Promise.resolve({ - _id: IdMap.getId("deleteId"), - title: "test", - }) - } - if (query._id === IdMap.getId("failId")) { - return Promise.reject(new Error("test error")) - } - if (query._id === IdMap.getId("inventory-test")) { - return Promise.resolve({ - _id: IdMap.getId("inventory-test"), - title: "inventory", - allow_backorder: false, - manage_inventory: true, - }) - } - if (query._id === IdMap.getId("no-inventory-test")) { - return Promise.resolve({ - _id: IdMap.getId("no-inventory-test"), - title: "inventory", - allow_backorder: false, - manage_inventory: false, - }) - } - if (query._id === IdMap.getId("backorder-test")) { - return Promise.resolve({ - _id: IdMap.getId("backorder-test"), - title: "inventory", - allow_backorder: true, - manage_inventory: true, - }) - } - - if (query._id === IdMap.getId("no-prices")) { - return Promise.resolve({ - _id: IdMap.getId("no-prices"), - title: "No Prices", - prices: [], - }) - } - - if (query._id === IdMap.getId("eur-prices")) { - return Promise.resolve({ - _id: IdMap.getId("eur-prices"), - title: "eur Prices", - prices: [ - { - currency_code: "eur", - amount: 1000, - }, - { - region_id: IdMap.getId("region-france"), - currency_code: "eur", - amount: 950, - }, - ], - }) - } - - if (query._id === IdMap.getId("france-prices")) { - return Promise.resolve({ - _id: IdMap.getId("france-prices"), - title: "France Prices", - prices: [ - { - currency_code: "eur", - amount: 1000, - }, - { - region_id: IdMap.getId("region-france"), - currency_code: "eur", - amount: 950, - }, - { - region_id: IdMap.getId("region-us"), - currency_code: "usd", - amount: 1200, - }, - ], - }) - } - - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/product.js b/packages/medusa/src/repositories/__mocks__/product.js deleted file mode 100644 index 5b55d53994..0000000000 --- a/packages/medusa/src/repositories/__mocks__/product.js +++ /dev/null @@ -1,117 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const ProductModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - if (query._id === IdMap.getId("productWithVariantsFail")) { - return Promise.reject() - } - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("fakeId")) { - return Promise.resolve({ - _id: IdMap.getId("fakeId"), - title: "Product With Variants", - variants: ["1", "2", "3"], - }) - } - if (query._id === IdMap.getId("productWithFourVariants")) { - return Promise.resolve({ - _id: IdMap.getId("productWithFourVariants"), - title: "Product With Variants", - variants: ["1", "2", "3", "4"], - options: [ - { - _id: IdMap.getId("color_id"), - title: "Color", - }, - { - _id: IdMap.getId("size_id"), - title: "Size", - }, - ], - }) - } - - if (query._id === IdMap.getId("productWithVariantsFail")) { - return Promise.resolve({ - _id: IdMap.getId("productWithVariantsFail"), - title: "Product With Variants", - variants: ["1", "3", "4"], - options: [ - { - _id: IdMap.getId("color_id"), - title: "Color", - }, - { - _id: IdMap.getId("size_id"), - title: "Size", - }, - ], - }) - } - if (query._id === IdMap.getId("productWithVariants")) { - return Promise.resolve({ - _id: IdMap.getId("productWithVariants"), - title: "Product With Variants", - variants: ["1", "3", "4"], - options: [ - { - _id: IdMap.getId("color_id"), - title: "Color", - }, - { - _id: IdMap.getId("size_id"), - title: "Size", - }, - ], - }) - } - - if (query._id === IdMap.getId("variantProductId")) { - return Promise.resolve({ - _id: IdMap.getId("variantProductId"), - title: "testtitle", - options: [ - { - _id: IdMap.getId("color_id"), - title: "Color", - }, - { - _id: IdMap.getId("size_id"), - title: "Size", - }, - ], - }) - } - - if (query._id === IdMap.getId("emptyVariantProductId")) { - return Promise.resolve({ - _id: IdMap.getId("emptyVariantProductId"), - title: "testtitle", - options: [], - }) - } - - if (query._id === IdMap.getId("deleteId")) { - return Promise.resolve({ - _id: IdMap.getId("deleteId"), - variants: ["1", "2"], - }) - } - - if (query._id === IdMap.getId("validId")) { - return Promise.resolve({ - _id: IdMap.getId("validId"), - title: "test", - }) - } - - if (query._id === IdMap.getId("failId")) { - return Promise.reject(new Error("test error")) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/region.js b/packages/medusa/src/repositories/__mocks__/region.js deleted file mode 100644 index 2a396091d2..0000000000 --- a/packages/medusa/src/repositories/__mocks__/region.js +++ /dev/null @@ -1,66 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const regions = { - testRegion: { - _id: IdMap.getId("testRegion"), - name: "Test Region", - countries: ["DK", "US", "DE"], - tax_rate: 0.25, - payment_providers: ["default_provider", "unregistered"], - fulfillment_providers: ["test_shipper"], - currency_code: "usd", - }, - regionFrance: { - _id: IdMap.getId("region-france"), - name: "France", - countries: ["FR"], - payment_providers: ["default_provider", "france-provider"], - currency_code: "eur", - }, - regionUs: { - _id: IdMap.getId("region-us"), - name: "USA", - countries: ["US"], - currency_code: "usd", - }, - regionGermany: { - _id: IdMap.getId("region-de"), - name: "Germany", - countries: ["DE"], - currency_code: "eur", - }, - regionSweden: { - _id: IdMap.getId("region-se"), - name: "Sweden", - countries: ["SE"], - payment_providers: ["sweden_provider"], - fulfillment_providers: ["sweden_provider"], - currency_code: "SEK", - }, -} - -export const RegionModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => {}), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query.countries === "SE") { - return Promise.resolve(regions.regionSweden) - } - - switch (query._id) { - case IdMap.getId("testRegion"): - return Promise.resolve(regions.testRegion) - case IdMap.getId("region-france"): - return Promise.resolve(regions.regionFrance) - case IdMap.getId("region-us"): - return Promise.resolve(regions.regionUs) - case IdMap.getId("region-de"): - return Promise.resolve(regions.regionGermany) - case IdMap.getId("region-se"): - return Promise.resolve(regions.regionSweden) - default: - return Promise.resolve(undefined) - } - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/shipping-option.js b/packages/medusa/src/repositories/__mocks__/shipping-option.js deleted file mode 100644 index 83aed0b9da..0000000000 --- a/packages/medusa/src/repositories/__mocks__/shipping-option.js +++ /dev/null @@ -1,61 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const options = { - validOption: { - _id: IdMap.getId("validId"), - name: "Default Option", - region_id: IdMap.getId("fr-region"), - provider_id: "default_provider", - data: { - id: "bonjour", - }, - requirements: [ - { - _id: "requirement_id", - type: "min_subtotal", - value: 100, - }, - ], - price: { - type: "flat_rate", - amount: 10, - }, - }, - noCalc: { - _id: IdMap.getId("noCalc"), - name: "No Calc", - region_id: IdMap.getId("fr-region"), - provider_id: "default_provider", - data: { - id: "bobo", - }, - requirements: [ - { - _id: "requirement_id", - type: "min_subtotal", - value: 100, - }, - ], - price: { - type: "flat_rate", - amount: 10, - }, - }, -} - -export const ShippingOptionModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("noCalc")) { - return Promise.resolve(options.noCalc) - } - if (query._id === IdMap.getId("validId")) { - return Promise.resolve(options.validOption) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/shipping-profile.js b/packages/medusa/src/repositories/__mocks__/shipping-profile.js deleted file mode 100644 index 1f7837a5fd..0000000000 --- a/packages/medusa/src/repositories/__mocks__/shipping-profile.js +++ /dev/null @@ -1,52 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const profiles = { - validProfile: { - _id: IdMap.getId("validId"), - name: "Default Profile", - products: [IdMap.getId("validId")], - shipping_options: [IdMap.getId("validId")], - }, - profile1: { - _id: IdMap.getId("profile1"), - name: "Profile One", - products: [IdMap.getId("product1")], - shipping_options: [IdMap.getId("shipping_1")], - }, - profile2: { - _id: IdMap.getId("profile2"), - name: "Profile two", - products: [IdMap.getId("product2")], - shipping_options: [IdMap.getId("shipping_2")], - }, -} - -export const ShippingProfileModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - find: jest.fn().mockImplementation(query => { - if (query.products && query.products.$in) { - return Promise.resolve([profiles.profile1, profiles.profile2]) - } - - return Promise.resolve([]) - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query.shipping_options === IdMap.getId("validId")) { - return Promise.resolve(profiles.validProfile) - } - if (query.products === IdMap.getId("validId")) { - return Promise.resolve(profiles.validProfile) - } - if (query._id === IdMap.getId("validId")) { - return Promise.resolve(profiles.validProfile) - } - if (query._id === IdMap.getId("profile1")) { - return Promise.resolve(profiles.profile1) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/store.js b/packages/medusa/src/repositories/__mocks__/store.js deleted file mode 100644 index 586a849be4..0000000000 --- a/packages/medusa/src/repositories/__mocks__/store.js +++ /dev/null @@ -1,17 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const store = { - _id: IdMap.getId("store"), - name: "test store", - currencies: ["DKK"], -} - -export const StoreModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - findOne: jest.fn().mockImplementation(query => { - return Promise.resolve(store) - }), -} diff --git a/packages/medusa/src/repositories/__mocks__/user.js b/packages/medusa/src/repositories/__mocks__/user.js deleted file mode 100644 index 25995dbee1..0000000000 --- a/packages/medusa/src/repositories/__mocks__/user.js +++ /dev/null @@ -1,31 +0,0 @@ -import { IdMap } from "medusa-test-utils" - -export const users = { - testUser: { - _id: IdMap.getId("test-user"), - email: "oliver@medusa.test", - password_hash: "123456789", - }, - permissionUser: { - _id: IdMap.getId("permissions-user"), - email: "oliver@medusa.com", - password_hash: "123456789", - }, -} - -export const UserModelMock = { - create: jest.fn().mockReturnValue(Promise.resolve()), - updateOne: jest.fn().mockImplementation((query, update) => { - return Promise.resolve() - }), - deleteOne: jest.fn().mockReturnValue(Promise.resolve()), - findOne: jest.fn().mockImplementation(query => { - if (query._id === IdMap.getId("test-user")) { - return Promise.resolve(users.testUser) - } - if (query._id === IdMap.getId("permission-user")) { - return Promise.resolve(users.permissionUser) - } - return Promise.resolve(undefined) - }), -} diff --git a/packages/medusa/src/repositories/idempotency-key.ts b/packages/medusa/src/repositories/idempotency-key.ts deleted file mode 100644 index 8521c21241..0000000000 --- a/packages/medusa/src/repositories/idempotency-key.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { IdempotencyKey } from "../models" -import { dataSource } from "../loaders/database" - -export const IdempotencyKeyRepository = dataSource.getRepository(IdempotencyKey) -export default IdempotencyKeyRepository diff --git a/packages/medusa/src/repositories/staged-job.ts b/packages/medusa/src/repositories/staged-job.ts deleted file mode 100644 index c7e88c55e1..0000000000 --- a/packages/medusa/src/repositories/staged-job.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" -import { dataSource } from "../loaders/database" -import { StagedJob } from "../models" - -export const StagedJobRepository = dataSource.getRepository(StagedJob).extend({ - async insertBulk(jobToCreates: QueryDeepPartialEntity[]) { - const queryBuilder = this.createQueryBuilder() - .insert() - .into(StagedJob) - .values(jobToCreates) - - if (!queryBuilder.connection.driver.isReturningSqlSupported("insert")) { - const rawStagedJobs = await queryBuilder.execute() - return rawStagedJobs.generatedMaps.map((d) => this.create(d)) - } - - const rawStagedJobs = await queryBuilder.returning("*").execute() - return rawStagedJobs.generatedMaps.map((d) => this.create(d)) - }, -}) - -export default StagedJobRepository diff --git a/packages/medusa/src/scripts/create-default-rule-types.ts b/packages/medusa/src/scripts/create-default-rule-types.ts deleted file mode 100644 index 10296687a7..0000000000 --- a/packages/medusa/src/scripts/create-default-rule-types.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { createDefaultRuleTypes } from "./utils/create-default-rule-types" -import dotenv from "dotenv" -import express from "express" -import loaders from "../loaders" -import Logger from "../loaders/logger" - -dotenv.config() - -const migrate = async function ({ directory }) { - const app = express() - const { container } = await loaders({ - directory, - expressApp: app, - isTest: false, - }) - - return await createDefaultRuleTypes(container) -} - -migrate({ directory: process.cwd() }) - .then(() => { - Logger.log("Created default rule types") - process.exit() - }) - .catch(() => { - Logger.log("Failed to create rule types") - process.exit(1) - }) diff --git a/packages/medusa/src/scripts/db-config.ts b/packages/medusa/src/scripts/db-config.ts deleted file mode 100644 index 6cab6b01ea..0000000000 --- a/packages/medusa/src/scripts/db-config.ts +++ /dev/null @@ -1,10 +0,0 @@ -export const typeormConfig = { - type: process.env.TYPEORM_CONNECTION, - url: process.env.TYPEORM_URL, - username: process.env.TYPEORM_USERNAME, - password: process.env.TYPEORM_PASSWORD, - database: process.env.TYPEORM_DATABASE, - migrations: [process.env.TYPEORM_MIGRATIONS as string], - entities: [process.env.TYPEORM_ENTITIES], - logging: true, -} diff --git a/packages/medusa/src/scripts/migrate-to-pricing-module.ts b/packages/medusa/src/scripts/migrate-to-pricing-module.ts deleted file mode 100644 index 2437b2bd81..0000000000 --- a/packages/medusa/src/scripts/migrate-to-pricing-module.ts +++ /dev/null @@ -1,218 +0,0 @@ -// TODO: we need to discuss this -/* -import { IPricingModuleService, PricingTypes } from "@medusajs/types" -import { promiseAll } from "@medusajs/utils" -import { AwilixContainer } from "awilix" -import dotenv from "dotenv" -import express from "express" -import loaders from "../loaders" -import Logger from "../loaders/logger" -import { PriceList } from "../models" -import { PriceListService } from "../services" -import { createDefaultRuleTypes } from "./utils/create-default-rule-types" -import { migrateProductVariantPricing } from "./utils/migrate-money-amounts-to-pricing-module" - -dotenv.config() - -const BATCH_SIZE = 1000 - -const migratePriceLists = async (container: AwilixContainer) => { - const pricingModuleService: IPricingModuleService = container.resolve( - "pricingModuleService" - ) - let offset = 0 - - const priceListCoreService: PriceListService = - container.resolve("priceListService") - - const remoteQuery = container.resolve("remoteQuery") - - const [_, totalCount] = await priceListCoreService.listAndCount( - {}, - { select: ["id"] } - ) - - while (offset < totalCount) { - const corePriceLists = await priceListCoreService.list( - {}, - { - take: BATCH_SIZE, - skip: offset, - relations: ["customer_groups", "prices", "prices.variants"], - } - ) - - const pricingModulePriceLists = await pricingModuleService.listPriceLists( - { id: corePriceLists.map(({ id }) => id) }, - { - take: BATCH_SIZE, - skip: offset, - select: ["id"], - } - ) - - const priceListIdsToUpdateSet = new Set( - pricingModulePriceLists.map(({ id }) => id) - ) - - const priceListsToCreate: PriceList[] = [] - const priceListsToUpdate: PriceList[] = [] - const variantIds: string[] = [] - - for (const corePriceList of corePriceLists) { - if (priceListIdsToUpdateSet.has(corePriceList.id)) { - priceListsToUpdate.push(corePriceList) - } else { - priceListsToCreate.push(corePriceList) - } - - const corePrices = corePriceList.prices || [] - - variantIds.push( - ...corePrices.map((corePrice) => corePrice.variants?.[0]?.id) - ) - } - - const query = { - product_variant_price_set: { - __args: { - variant_id: variantIds, - }, - fields: ["variant_id", "price_set_id"], - }, - } - - const variantPriceSets = await remoteQuery(query) - - const variantIdPriceSetIdMap = new Map( - variantPriceSets.map((vps) => [vps.variant_id, vps.price_set_id]) - ) - - const promises: Promise[] = [] - - if (priceListsToUpdate.length) { - await pricingModuleService.updatePriceLists( - priceListsToUpdate.map((priceList) => { - const updateData: PricingTypes.UpdatePriceListDTO = { - id: priceList.id, - } - - if (priceList?.customer_groups?.length) { - updateData.rules = { - customer_group_id: priceList.customer_groups.map(({ id }) => id), - } - } - - return updateData - }) - ) - - promises.push( - pricingModuleService.addPriceListPrices( - priceListsToUpdate.map((priceList) => { - return { - price_list_id: priceList.id, - prices: priceList.prices - .filter((price) => - variantIdPriceSetIdMap.has(price.variants?.[0]?.id) - ) - .map((price) => { - return { - price_set_id: variantIdPriceSetIdMap.get( - price.variants?.[0]?.id - )!, - currency_code: price.currency_code, - amount: price.amount, - min_quantity: price.min_quantity, - max_quantity: price.max_quantity, - } - }), - } - }) - ) - ) - } - - if (priceListsToCreate.length) { - promises.push( - pricingModuleService.createPriceLists( - priceListsToCreate.map( - ({ name: title, prices, customer_groups, ...priceList }) => { - const createData: any = { - ...priceList, - title, - } - - if (customer_groups?.length) { - createData.rules = { - customer_group_id: customer_groups.map(({ id }) => id), - } - } - - if (prices?.length) { - createData.prices = prices.map((price) => { - return { - price_set_id: variantIdPriceSetIdMap.get( - price.variants?.[0]?.id - )!, - currency_code: price.currency_code, - amount: price.amount, - min_quantity: price.min_quantity, - max_quantity: price.max_quantity, - } - }) - } - - return createData - } - ) - ) - ) - } - - await promiseAll(promises) - - offset += corePriceLists.length - - Logger.info(`Processed ${offset} of ${totalCount}`) - } -} - -const migrate = async function ({ directory }) { - const app = express() - - const { container } = await loaders({ - directory, - expressApp: app, - isTest: false, - }) - - Logger.info("-----------------------------------------------") - Logger.info("--------- Creating default rule types ---------") - Logger.info("-----------------------------------------------") - await createDefaultRuleTypes(container) - - Logger.info("-----------------------------------------------") - Logger.info("---------- Migrating Variant Prices -----------") - Logger.info("-----------------------------------------------") - - await migrateProductVariantPricing(container) - - Logger.info("-----------------------------------------------") - Logger.info("----------- Migrating Price Lists -------------") - Logger.info("-----------------------------------------------") - - return await migratePriceLists(container) -} - -migrate({ directory: process.cwd() }) - .then(() => { - Logger.info("Migrated price lists") - process.exit(0) - }) - .catch((error) => { - console.warn(error) - Logger.info("Failed to migrate price lists") - process.exit(1) - }) -*/ diff --git a/packages/medusa/src/scripts/utils/create-default-rule-types.ts b/packages/medusa/src/scripts/utils/create-default-rule-types.ts deleted file mode 100644 index 6403b98d03..0000000000 --- a/packages/medusa/src/scripts/utils/create-default-rule-types.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { AwilixContainer } from "awilix" -import { IPricingModuleService } from "@medusajs/types" - -export const createDefaultRuleTypes = async (container: AwilixContainer) => { - const pricingModuleService: IPricingModuleService = container.resolve( - "pricingModuleService" - ) - const existing = await pricingModuleService.listRuleTypes( - { rule_attribute: ["region_id", "customer_group_id"] }, - { take: 2 } - ) - - if (existing.length === 2) { - return - } - - if (existing.length === 0) { - await pricingModuleService.createRuleTypes([ - { name: "region_id", rule_attribute: "region_id" }, - { name: "customer_group_id", rule_attribute: "customer_group_id" }, - ]) - } else if (existing[0].rule_attribute === "region_id") { - await pricingModuleService.createRuleTypes([ - { name: "customer_group_id", rule_attribute: "customer_group_id" }, - ]) - } else { - await pricingModuleService.createRuleTypes([ - { name: "region_id", rule_attribute: "region_id" }, - ]) - } -} diff --git a/packages/medusa/src/scripts/utils/migrate-money-amounts-to-pricing-module.ts b/packages/medusa/src/scripts/utils/migrate-money-amounts-to-pricing-module.ts deleted file mode 100644 index 9198c17d98..0000000000 --- a/packages/medusa/src/scripts/utils/migrate-money-amounts-to-pricing-module.ts +++ /dev/null @@ -1,87 +0,0 @@ -// TODO: we need to discuss this -/* -import { IPricingModuleService, MedusaContainer } from "@medusajs/types" -import { MedusaError, promiseAll } from "@medusajs/utils" - -import { ProductVariantService } from "../../services" -import dotenv from "dotenv" -import Logger from "../../loaders/logger" - -dotenv.config() - -const BATCH_SIZE = 100 - -export const migrateProductVariantPricing = async function ( - container: MedusaContainer -) { - const variantService: ProductVariantService = await container.resolve( - "productVariantService" - ) - - const pricingService: IPricingModuleService = container.resolve( - "pricingModuleService" - ) - - const link = await container.resolve("remoteLink") - - if (!link) { - throw new MedusaError( - MedusaError.Types.NOT_ALLOWED, - "Can't migrate money_amounts: Pricing module is not configured correctly" - ) - } - - const [_, totalCount] = await variantService.listAndCount( - {}, - { take: BATCH_SIZE, order: { id: "ASC" }, relations: ["prices"] } - ) - - let processedCount = 0 - while (processedCount < totalCount) { - const [variants] = await variantService.listAndCount( - {}, - { - skip: processedCount, - take: BATCH_SIZE, - order: { id: "ASC" }, - relations: ["prices"], - } - ) - - const links: any[] = [] - - await promiseAll( - variants.map(async (variant) => { - const priceSet = await pricingService.create({ - rules: [{ rule_attribute: "region_id" }], - prices: - variant?.prices - ?.filter(({ price_list_id }) => !price_list_id) - .map((price) => ({ - rules: { - ...(price.region_id ? { region_id: price.region_id } : {}), - }, - currency_code: price.currency_code, - min_quantity: price.min_quantity, - max_quantity: price.max_quantity, - amount: price.amount, - })) ?? [], - }) - - links.push({ - productService: { - variant_id: variant.id, - }, - pricingService: { - price_set_id: priceSet.id, - }, - }) - }) - ) - await link.create(links) - - processedCount += variants.length - Logger.log(`Processed ${processedCount} of ${totalCount}`) - } -} -*/ diff --git a/packages/medusa/src/services/__mocks__/event-bus.js b/packages/medusa/src/services/__mocks__/event-bus.js deleted file mode 100644 index 19eeb4f943..0000000000 --- a/packages/medusa/src/services/__mocks__/event-bus.js +++ /dev/null @@ -1,13 +0,0 @@ -export const EventBusServiceMock = { - emit: jest.fn(), - subscribe: jest.fn(), - withTransaction: function() { - return this - }, -} - -const mock = jest.fn().mockImplementation(() => { - return EventBusServiceMock -}) - -export default mock diff --git a/packages/medusa/src/services/__mocks__/idempotency-key.js b/packages/medusa/src/services/__mocks__/idempotency-key.js deleted file mode 100644 index 3901fff025..0000000000 --- a/packages/medusa/src/services/__mocks__/idempotency-key.js +++ /dev/null @@ -1,42 +0,0 @@ -import { MockManager } from "medusa-test-utils" - -export const IdempotencyKeyService = { - withTransaction: function () { - return this - }, - initializeRequest: jest.fn().mockImplementation(() => { - return { - idempotency_key: "testkey", - recovery_point: "started", - } - }), - workStage: jest.fn().mockImplementation(async (key, fn) => { - const { recovery_point, response_code, response_body } = await fn( - MockManager - ) - - if (recovery_point) { - return { - recovery_point, - } - } else { - return { - recovery_point: "finished", - response_body, - response_code, - } - } - }), - update: jest.fn().mockImplementation(async (key, data) => { - return { - ...data, - idempotency_key: key, - } - }), -} - -const mock = jest.fn().mockImplementation(() => { - return IdempotencyKeyService -}) - -export default mock diff --git a/packages/medusa/src/services/__mocks__/middleware.js b/packages/medusa/src/services/__mocks__/middleware.js deleted file mode 100644 index ec2ffe5f81..0000000000 --- a/packages/medusa/src/services/__mocks__/middleware.js +++ /dev/null @@ -1,12 +0,0 @@ -export const MiddlewareServiceMock = { - usePostAuthentication: jest.fn(), - usePreAuthentication: jest.fn(), - usePreCartCreation: jest.fn().mockReturnValue([]), - getRouters: jest.fn().mockReturnValue([]), -} - -const mock = jest.fn().mockImplementation(() => { - return MiddlewareServiceMock -}) - -export default mock diff --git a/packages/medusa/src/services/__tests__/job-scheduler.js b/packages/medusa/src/services/__tests__/job-scheduler.js deleted file mode 100644 index af7d6f1936..0000000000 --- a/packages/medusa/src/services/__tests__/job-scheduler.js +++ /dev/null @@ -1,123 +0,0 @@ -import { Queue } from "bullmq" -import JobSchedulerService from "../job-scheduler" - -jest.genMockFromModule("bullmq") -jest.mock("bullmq") -jest.mock("ioredis") - -const loggerMock = { - info: jest.fn().mockReturnValue(console.log), - warn: jest.fn().mockReturnValue(console.log), - error: jest.fn().mockReturnValue(console.log), -} - -describe("JobSchedulerService", () => { - let scheduler - - describe("constructor", () => { - beforeAll(() => { - jest.clearAllMocks() - - scheduler = new JobSchedulerService( - { - logger: loggerMock, - }, - { - projectConfig: { - redis_url: "testhost", - }, - } - ) - }) - - it("creates bull queue", () => { - expect(Queue).toHaveBeenCalledTimes(1) - expect(Queue).toHaveBeenCalledWith("scheduled-jobs:queue", { - connection: expect.any(Object), - prefix: "JobSchedulerService", - }) - }) - }) - - describe("create", () => { - let jobScheduler - - beforeAll(async () => { - jest.resetAllMocks() - - jobScheduler = new JobSchedulerService( - { - logger: loggerMock, - }, - { - projectConfig: { - redis_url: "testhost", - }, - } - ) - - await jobScheduler.create( - "eventName", - { data: "test" }, - "* * * * *", - () => "test" - ) - }) - - it("added the handler to the job queue", () => { - expect(jobScheduler.handlers_.get("eventName").length).toEqual(1) - expect(jobScheduler.queue_.add).toHaveBeenCalledWith( - "eventName", - { - eventName: "eventName", - data: { data: "test" }, - }, - { - repeat: { pattern: "* * * * *" }, - } - ) - }) - }) - - describe("scheduledJobWorker", () => { - let jobScheduler - let result - - beforeAll(async () => { - jest.resetAllMocks() - - jobScheduler = new JobSchedulerService( - { - logger: loggerMock, - }, - { - projectConfig: { - redis_url: "testhost", - }, - } - ) - - await jobScheduler.create( - "eventName", - { data: "test" }, - "* * * * *", - () => Promise.resolve("hi") - ) - - result = await jobScheduler.scheduledJobsWorker({ - data: { eventName: "eventName", data: {} }, - }) - }) - - it("calls logger", () => { - expect(loggerMock.info).toHaveBeenCalled() - expect(loggerMock.info).toHaveBeenCalledWith( - "Processing scheduled job: eventName" - ) - }) - - it("returns array with hi", async () => { - expect(result).toEqual(["hi"]) - }) - }) -}) diff --git a/packages/medusa/src/services/__tests__/middleware.js b/packages/medusa/src/services/__tests__/middleware.js deleted file mode 100644 index dcbe724b54..0000000000 --- a/packages/medusa/src/services/__tests__/middleware.js +++ /dev/null @@ -1,79 +0,0 @@ -import MiddlewareService from "../middleware" - -describe("MiddlewareService", () => { - beforeEach(() => { - jest.clearAllMocks() - }) - - describe("addPostAuthentication", () => { - const middlewareService = new MiddlewareService() - - it("adds middleware function", () => { - middlewareService.addPostAuthentication(() => "post", {}) - expect(middlewareService.postAuthentication_.length).toEqual(1) - }) - - it("fails when no function", () => { - expect(() => middlewareService.addPostAuthentication("post", {})).toThrow( - "Middleware must be a function" - ) - }) - }) - - describe("addPreAuthentication", () => { - const middlewareService = new MiddlewareService() - - it("adds middleware function", () => { - middlewareService.addPreAuthentication(() => "pre", {}) - expect(middlewareService.preAuthentication_.length).toEqual(1) - }) - - it("fails when no function", () => { - expect(() => middlewareService.addPreAuthentication("pre", {})).toThrow( - "Middleware must be a function" - ) - }) - }) - - describe("usePostAuthentication", () => { - const middlewareService = new MiddlewareService() - - it("calls middleware", () => { - // This doesn't reflect how middleware works but does suffice in our - // testing situation - const mid = (args) => args - - middlewareService.addPostAuthentication(mid, { data: "yes" }) - - const app = { - use: jest.fn(), - } - - middlewareService.usePostAuthentication(app) - - expect(app.use).toHaveBeenCalledTimes(1) - expect(app.use).toHaveBeenCalledWith({ data: "yes" }) - }) - }) - - describe("usePreAuthentication", () => { - const middlewareService = new MiddlewareService() - - it("calls middleware", () => { - // This doesn't reflect how middleware works but does suffice in our - // testing situation - const mid = (args) => args - - middlewareService.addPreAuthentication(mid, { data: "yes" }) - - const app = { - use: jest.fn(), - } - - middlewareService.usePreAuthentication(app) - - expect(app.use).toHaveBeenCalledTimes(1) - expect(app.use).toHaveBeenCalledWith({ data: "yes" }) - }) - }) -}) diff --git a/packages/medusa/src/services/event-bus.ts b/packages/medusa/src/services/event-bus.ts deleted file mode 100644 index ef035c0c5d..0000000000 --- a/packages/medusa/src/services/event-bus.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { EmitData, EventBusTypes, Logger, Message } from "@medusajs/types" -import { DatabaseErrorCode, EventBusUtils } from "@medusajs/utils" -import { EOL } from "os" -import { EntityManager } from "typeorm" -import { TransactionBaseService } from "../interfaces" -import { StagedJob } from "../models" -import { FindConfig } from "../types/common" -import { ConfigModule } from "../types/global" -import { isString } from "../utils" -import { sleep } from "../utils/sleep" -import StagedJobService from "./staged-job" - -type InjectedDependencies = { - stagedJobService: StagedJobService - eventBusModuleService: EventBusUtils.AbstractEventBusModuleService - logger: Logger -} - -/** - * Can keep track of multiple subscribers to different events and run the - * subscribers when events happen. Events will run asynchronously. - */ -export default class EventBusService - extends TransactionBaseService - implements EventBusTypes.IEventBusService -{ - protected readonly config_: ConfigModule - protected readonly stagedJobService_: StagedJobService - // eslint-disable-next-line max-len - protected get eventBusModuleService_(): EventBusTypes.IEventBusModuleService { - return this.__container__.eventBusModuleService - } - - protected readonly logger_: Logger - - protected shouldEnqueuerRun: boolean - protected enqueue_: Promise - - constructor( - { stagedJobService, logger }: InjectedDependencies, - config: ConfigModule, - isSingleton = true - ) { - // eslint-disable-next-line prefer-rest-params - super(arguments[0]) - - this.logger_ = logger - this.config_ = config - this.stagedJobService_ = stagedJobService - - if (process.env.NODE_ENV !== "test" && isSingleton) { - this.startEnqueuer() - } - } - - withTransaction(transactionManager?: EntityManager): this { - if (!transactionManager) { - return this - } - - const cloned = new (this.constructor as any)( - { - manager: transactionManager, - stagedJobService: this.stagedJobService_, - eventBusModuleService: this.eventBusModuleService_, - }, - this.config_, - false - ) - - cloned.manager_ = transactionManager - cloned.transactionManager_ = transactionManager - - return cloned - } - - /** - * Adds a function to a list of event subscribers. - * @param event - the event that the subscriber will listen for. - * @param subscriber - the function to be called when a certain event - * happens. Subscribers must return a Promise. - * @param context - subscriber context - * @return this - */ - subscribe( - event: string | symbol, - subscriber: EventBusTypes.Subscriber, - context?: EventBusTypes.SubscriberContext - ): this { - if (typeof subscriber !== "function") { - throw new Error("Subscriber must be a function") - } - - this.eventBusModuleService_.subscribe(event, subscriber, context) - return this - } - - /** - * Removes function from the list of event subscribers. - * @param event - the event of the subcriber. - * @param subscriber - the function to be removed - * @param context - subscriber context - * @return this - */ - unsubscribe( - event: string | symbol, - subscriber: EventBusTypes.Subscriber, - context: EventBusTypes.SubscriberContext - ): this { - this.eventBusModuleService_.unsubscribe(event, subscriber, context) - return this - } - - /** - * Calls all subscribers when an event occurs. - * @param data - The data to use to process the events - * @return the jobs from our queue - */ - async emit(data: EventBusTypes.EmitData[]): Promise - - async emit(data: EventBusTypes.Message[]): Promise - - /** - * Calls all subscribers when an event occurs. - * @param {string} eventName - the name of the event to be process. - * @param data - the data to send to the subscriber. - * @param options - options to add the job with - * @return the job from our queue - */ - async emit( - eventName: string, - data: T, - options?: Record - ): Promise - - async emit< - T, - TInput extends - | string - | EventBusTypes.EmitData[] - | EventBusTypes.Message[] = string, - TResult = TInput extends EventBusTypes.EmitData[] - ? StagedJob[] - : StagedJob - >( - eventNameOrData: TInput, - data?: T, - options: Record = {} - ): Promise { - const manager = this.activeManager_ - const isBulkEmit = !isString(eventNameOrData) - const dataBody = isString(eventNameOrData) - ? data ?? (data as Message).body - : undefined - const events: EventBusTypes.EmitData[] = isBulkEmit - ? eventNameOrData.map((event) => ({ - eventName: event.eventName, - data: (event as EmitData).data ?? (event as Message).body.data, - options: event.options, - })) - : [ - { - eventName: eventNameOrData, - data: dataBody, - options: options, - }, - ] - - /** - * We store events in the database when in an ongoing transaction. - * - * If we are in a long-running transaction, the ACID properties of a - * transaction ensure, that events are kept invisible to the enqueuer - * until the transaction has committed. - * - * This patterns also gives us at-least-once delivery of events, as events - * are only removed from the database, if they are successfully delivered. - * - * In case of a failing transaction, jobs stored in the database are removed - * as part of the rollback. - */ - - const stagedJobs = await this.stagedJobService_ - .withTransaction(manager) - .create(events) - - return (!isBulkEmit ? stagedJobs[0] : stagedJobs) as unknown as TResult - } - - startEnqueuer(): void { - this.shouldEnqueuerRun = true - this.enqueue_ = this.enqueuer_() - } - - async stopEnqueuer(): Promise { - this.shouldEnqueuerRun = false - await this.enqueue_ - } - - async enqueuer_(): Promise { - const listConfig = { - relations: [], - skip: 0, - take: this.config_.projectConfig.jobs_batch_size ?? 1000, - } - - while (this.shouldEnqueuerRun) { - await sleep(3000) - - const jobs = await this.listJobs(listConfig) - - if (!jobs.length) { - continue - } - - const eventsData = jobs.map((job) => { - return { - eventName: job.event_name, - data: job.data, - options: { jobId: job.id, ...job.options }, - } - }) - - await this.eventBusModuleService_.emit(eventsData).then(async () => { - return await this.stagedJobService_.delete(jobs.map((j) => j.id)) - }) - } - } - - protected async listJobs(listConfig: FindConfig) { - return await this.stagedJobService_.list(listConfig).catch((err) => { - if (DatabaseErrorCode.connectionFailure === err.code) { - this.logger_.warn(`Database connection failure:${EOL}${err.message}`) - } else { - this.logger_.warn(`Failed to fetch jobs:${EOL}${err.message}`) - } - - return [] - }) - } -} diff --git a/packages/medusa/src/services/idempotency-key.ts b/packages/medusa/src/services/idempotency-key.ts deleted file mode 100644 index d50f24eae3..0000000000 --- a/packages/medusa/src/services/idempotency-key.ts +++ /dev/null @@ -1,221 +0,0 @@ -import { - CreateIdempotencyKeyInput, - IdempotencyCallbackResult, -} from "../types/idempotency-key" -import { DeepPartial, EntityManager } from "typeorm" -import { MedusaError, isDefined } from "medusa-core-utils" -import { buildQuery, isString } from "../utils" - -import { IdempotencyKey } from "../models" -import { IdempotencyKeyRepository } from "../repositories/idempotency-key" -import { Selector } from "../types/common" -import { TransactionBaseService } from "../interfaces" -import { v4 } from "uuid" - -const KEY_LOCKED_TIMEOUT = 1000 - -type InjectedDependencies = { - manager: EntityManager - idempotencyKeyRepository: typeof IdempotencyKeyRepository -} - -class IdempotencyKeyService extends TransactionBaseService { - protected readonly idempotencyKeyRepository_: typeof IdempotencyKeyRepository - - constructor({ idempotencyKeyRepository }: InjectedDependencies) { - // eslint-disable-next-line prefer-rest-params - super(arguments[0]) - - this.idempotencyKeyRepository_ = idempotencyKeyRepository - } - - /** - * Execute the initial steps in a idempotent request. - * @param headerKey - potential idempotency key from header - * @param reqMethod - method of request - * @param reqParams - params of request - * @param reqPath - path of request - * @return the existing or created idempotency key - */ - async initializeRequest( - headerKey: string, - reqMethod: string, - reqParams: Record, - reqPath: string - ): Promise { - return await this.atomicPhase_(async () => { - if (headerKey) { - const key = await this.retrieve(headerKey).catch(() => void 0) - if (key) { - return key - } - } - return await this.create({ - request_method: reqMethod, - request_params: reqParams, - request_path: reqPath, - }) - }, "SERIALIZABLE") - } - - /** - * Creates an idempotency key for a request. - * If no idempotency key is provided in request, we will create a unique - * identifier. - * @param payload - payload of request to create idempotency key for - * @return the created idempotency key - */ - async create(payload: CreateIdempotencyKeyInput): Promise { - return await this.atomicPhase_(async (manager) => { - const idempotencyKeyRepo = manager.withRepository( - this.idempotencyKeyRepository_ - ) - - payload.idempotency_key = payload.idempotency_key ?? v4() - - const created = idempotencyKeyRepo.create(payload) - return await idempotencyKeyRepo.save(created) - }) - } - - /** - * Retrieves an idempotency key - * @param idempotencyKeyOrSelector - key or selector to retrieve - * @return idempotency key - */ - async retrieve( - idempotencyKeyOrSelector: string | Selector - ): Promise { - if (!isDefined(idempotencyKeyOrSelector)) { - throw new MedusaError( - MedusaError.Types.NOT_FOUND, - `"idempotencyKeyOrSelector" must be defined` - ) - } - - const idempotencyKeyRepo = this.activeManager_.withRepository( - this.idempotencyKeyRepository_ - ) - - const selector = isString(idempotencyKeyOrSelector) - ? { idempotency_key: idempotencyKeyOrSelector } - : idempotencyKeyOrSelector - const query = buildQuery(selector) - - const iKeys = await idempotencyKeyRepo.find(query) - - if (iKeys.length > 1) { - throw new Error( - `Multiple keys were found for constraints: ${JSON.stringify( - idempotencyKeyOrSelector - )}. There should only be one.` - ) - } - - const iKey = iKeys[0] - - if (!iKey) { - let message - if (isString(idempotencyKeyOrSelector)) { - message = `Idempotency key ${idempotencyKeyOrSelector} was not found` - } else { - message = `Idempotency key with constraints ${JSON.stringify( - idempotencyKeyOrSelector - )} was not found` - } - - throw new MedusaError(MedusaError.Types.NOT_FOUND, message) - } - - return iKey - } - - /** - * Locks an idempotency. - * @param idempotencyKey - key to lock - * @return result of the update operation - */ - async lock(idempotencyKey: string): Promise { - return await this.atomicPhase_(async (manager) => { - const idempotencyKeyRepo = manager.withRepository( - this.idempotencyKeyRepository_ - ) - - const key = await this.retrieve(idempotencyKey) - - const isLocked = - key.locked_at && - new Date(key.locked_at).getTime() > Date.now() - KEY_LOCKED_TIMEOUT - - if (isLocked) { - throw new MedusaError(MedusaError.Types.CONFLICT, "Key already locked") - } - - return await idempotencyKeyRepo.save({ - ...key, - locked_at: Date.now(), - }) - }) - } - - /** - * Locks an idempotency. - * @param {string} idempotencyKey - key to update - * @param {object} update - update object - * @return {Promise} result of the update operation - */ - async update( - idempotencyKey: string, - update: DeepPartial - ): Promise { - return await this.atomicPhase_(async (manager) => { - const idempotencyKeyRepo = manager.withRepository( - this.idempotencyKeyRepository_ - ) - - const iKey = await this.retrieve(idempotencyKey) - - for (const [key, value] of Object.entries(update)) { - iKey[key] = value - } - - return await idempotencyKeyRepo.save(iKey) - }) - } - - /** - * 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". - * @param idempotencyKey - current idempotency key - * @param callback - functionality to execute within the phase - * @return new updated idempotency key - */ - async workStage( - idempotencyKey: string, - callback: ( - transactionManager: EntityManager - ) => Promise - ): Promise { - return await this.atomicPhase_(async (manager) => { - const { recovery_point, response_code, response_body } = await callback( - manager - ) - - const data: DeepPartial = { - recovery_point: recovery_point ?? "finished", - } - - if (!recovery_point) { - data.response_body = response_body - data.response_code = response_code - } - - return await this.update(idempotencyKey, data) - }) - } -} - -export default IdempotencyKeyService diff --git a/packages/medusa/src/services/index.ts b/packages/medusa/src/services/index.ts deleted file mode 100644 index e4395133dc..0000000000 --- a/packages/medusa/src/services/index.ts +++ /dev/null @@ -1,5 +0,0 @@ -export { default as EventBusService } from "./event-bus" -export { default as MiddlewareService } from "./middleware" -export { default as StagedJobService } from "./staged-job" -export { default as IdempotencyKeyService } from "./idempotency-key" -export { default as JobSchedulerService } from "./job-scheduler" diff --git a/packages/medusa/src/services/job-scheduler.ts b/packages/medusa/src/services/job-scheduler.ts deleted file mode 100644 index 36bf7454ba..0000000000 --- a/packages/medusa/src/services/job-scheduler.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { Job, Queue, Worker } from "bullmq" -import Redis from "ioredis" -import { ConfigModule, Logger } from "../types/global" -import { promiseAll } from "@medusajs/utils" - -type InjectedDependencies = { - logger: Logger -} - -type ScheduledJobHandler = ( - data: T, - eventName: string -) => Promise - -export type CreateJobOptions = { - keepExisting?: boolean -} - -export default class JobSchedulerService { - protected readonly config_: ConfigModule - protected readonly logger_: Logger - protected readonly handlers_: Map = - new Map() - protected readonly queue_: Queue - - constructor( - { logger }: InjectedDependencies, - config: ConfigModule, - singleton = true - ) { - this.config_ = config - this.logger_ = logger - - const prefix = `${config?.projectConfig?.redis_prefix ?? ""}${ - this.constructor.name - }` - - if (singleton && config?.projectConfig?.redis_url) { - // Required config - // See: https://github.com/OptimalBits/bull/blob/develop/CHANGELOG.md#breaking-changes - const connection = new Redis(config.projectConfig.redis_url, { - maxRetriesPerRequest: null, - enableReadyCheck: false, - ...(config.projectConfig.redis_options ?? {}), - }) - - this.queue_ = new Queue(`scheduled-jobs:queue`, { - connection, - prefix, - }) - - // Register scheduled job worker - new Worker("scheduled-jobs:queue", this.scheduledJobsWorker, { - connection, - prefix, - }) - } - } - - /** - * Adds a function to a list of event subscribers. - * @param event - the event that the subscriber will listen for. - * @param subscriber - the function to be called when a certain event - * happens. Subscribers must return a Promise. - * @return this - */ - protected registerHandler( - event: string | symbol, - handler: ScheduledJobHandler - ): void { - if (typeof handler !== "function") { - throw new Error("Handler must be a function") - } - - const handlers = this.handlers_.get(event) ?? [] - this.handlers_.set(event, [...handlers, handler]) - } - - /** - * Handles incoming scheduled jobs. - * @param job The job object - * @return resolves to the results of the subscriber calls. - */ - protected scheduledJobsWorker = async (job: { - data: { eventName: string; data: T } - }): Promise => { - const { eventName, data } = job.data - const observers = this.handlers_.get(eventName) || [] - this.logger_.info(`Processing scheduled job: ${eventName}`) - - return await promiseAll( - observers.map(async (subscriber) => { - return subscriber(data, eventName).catch((err) => { - this.logger_.warn( - `An error occured while processing ${eventName}: ${err}` - ) - return err - }) - }) - ) - } - - /** - * Registers a scheduled job. - * @param eventName - the name of the event - * @param data - the data to be sent with the event - * @param schedule - the schedule expression - * @param handler - the handler to call on the job - * @return void - */ - async create( - eventName: string, - data: T, - schedule: string, - handler: ScheduledJobHandler, - options: CreateJobOptions - ): Promise { - this.logger_.info(`Registering ${eventName}`) - this.registerHandler(eventName, handler) - - const jobToCreate = { - eventName, - data, - } - const repeatOpts = { repeat: { pattern: schedule } } - - if (options?.keepExisting) { - return await this.queue_.add(eventName, jobToCreate, repeatOpts) - } - - const existingJobs = (await this.queue_.getRepeatableJobs()) ?? [] - - const existingJob = existingJobs.find((job) => job.name === eventName) - - if (existingJob) { - await this.queue_.removeRepeatableByKey(existingJob.key) - } - - return await this.queue_.add(eventName, jobToCreate, repeatOpts) - } -} diff --git a/packages/medusa/src/services/middleware.ts b/packages/medusa/src/services/middleware.ts deleted file mode 100644 index 103e1c77f0..0000000000 --- a/packages/medusa/src/services/middleware.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { RequestHandler, Router } from "express" -import { MedusaError } from "medusa-core-utils" - -type middlewareHandlerType = ( - options: Record -) => RequestHandler - -type middlewareType = { - middleware: middlewareHandlerType - options: Record -} - -/** - * Orchestrates dynamic middleware registered through the Medusa Middleware API - */ -class MiddlewareService { - protected readonly postAuthentication_: middlewareType[] - protected readonly preAuthentication_: middlewareType[] - protected readonly preCartCreation_: RequestHandler[] - protected readonly routers: Record - - constructor() { - this.postAuthentication_ = [] - this.preAuthentication_ = [] - this.preCartCreation_ = [] - this.routers = {} - } - - addRouter(path: string, router: Router): void { - const existing = this.routers[path] || [] - this.routers[path] = [...existing, router] - } - - getRouters(path: string): Router[] { - return this.routers[path] || [] - } - - /** - * Validates a middleware function, throws if fn is not of type function. - * @param {function} fn - the middleware function to validate. - * @returns nothing if the middleware is a function - */ - validateMiddleware_(fn: unknown): void { - if (typeof fn !== "function") { - throw new MedusaError( - MedusaError.Types.NOT_ALLOWED, - "Middleware must be a function" - ) - } - } - - /** - * Adds a middleware function to be called after authentication is completed. - * @param {function} middleware - the middleware function. Should return a - * middleware function. - * @param {object} options - the arguments that will be passed to the - * middleware - * @return void - */ - addPostAuthentication( - middleware: middlewareHandlerType, - options: Record - ): void { - this.validateMiddleware_(middleware) - this.postAuthentication_.push({ - middleware, - options: options || {}, - }) - } - - /** - * Adds a middleware function to be called before authentication is completed. - * @param {function} middleware - the middleware function. Should return a - * middleware function. - * @param {object} options - the arguments that will be passed to the - * middleware - * @return void - */ - addPreAuthentication( - middleware: middlewareHandlerType, - options: Record - ): void { - this.validateMiddleware_(middleware) - this.preAuthentication_.push({ - middleware, - options: options || {}, - }) - } - - /** - * Adds a middleware function to be called before cart creation - * @param {function} middleware - the middleware function. Should return a - * middleware function. - * @return {void} - */ - addPreCartCreation(middleware: RequestHandler): void { - this.validateMiddleware_(middleware) - this.preCartCreation_.push(middleware) - } - - /** - * Adds post authentication middleware to an express app. - * @param {ExpressApp} app - the express app to add the middleware to - * @return {void} - */ - usePostAuthentication(app: Router): void { - for (const object of this.postAuthentication_) { - app.use(object.middleware(object.options)) - } - } - - /** - * Adds pre authentication middleware to an express app. - * @param {ExpressApp} app - the express app to add the middleware to - * @return {void} - */ - usePreAuthentication(app: Router): void { - for (const object of this.preAuthentication_) { - app.use(object.middleware(object.options)) - } - } - - usePreCartCreation(): RequestHandler[] { - return this.preCartCreation_ - } -} - -export default MiddlewareService diff --git a/packages/medusa/src/services/staged-job.ts b/packages/medusa/src/services/staged-job.ts deleted file mode 100644 index 5a77c42e6b..0000000000 --- a/packages/medusa/src/services/staged-job.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { DeepPartial, EntityManager, In } from "typeorm" - -import { EventBusTypes } from "@medusajs/types" -import { FindConfig } from "../types/common" -import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" -import { StagedJob } from "../models" -import { StagedJobRepository } from "../repositories/staged-job" -import { TransactionBaseService } from "../interfaces" -import { isString } from "../utils" - -type StagedJobServiceProps = { - manager: EntityManager - stagedJobRepository: typeof StagedJobRepository -} - -/** - * Provides layer to manipulate users. - */ -class StagedJobService extends TransactionBaseService { - protected stagedJobRepository_: typeof StagedJobRepository - - constructor({ stagedJobRepository }: StagedJobServiceProps) { - // eslint-disable-next-line prefer-rest-params - super(arguments[0]) - - this.stagedJobRepository_ = stagedJobRepository - } - - async list(config: FindConfig) { - const stagedJobRepo = this.activeManager_.withRepository( - this.stagedJobRepository_ - ) - - return await stagedJobRepo.find(config) - } - - async delete(stagedJobIds: string | string[]): Promise { - const manager = this.activeManager_ - const stagedJobRepo = manager.withRepository(this.stagedJobRepository_) - const sjIds = isString(stagedJobIds) ? [stagedJobIds] : stagedJobIds - - await stagedJobRepo.delete({ id: In(sjIds) }) - } - - async create(data: EventBusTypes.EmitData[] | EventBusTypes.EmitData) { - const stagedJobRepo = this.activeManager_.withRepository(this.stagedJobRepository_) - - const data_ = Array.isArray(data) ? data : [data] - - const stagedJobs = data_.map((job) => - stagedJobRepo.create({ - event_name: job.eventName, - data: job.data, - options: job.options, - } as DeepPartial) - ) as QueryDeepPartialEntity[] - - return await stagedJobRepo.insertBulk(stagedJobs) - } -} - -export default StagedJobService diff --git a/packages/medusa/src/subscribers/batch-job.ts b/packages/medusa/src/subscribers/batch-job.ts deleted file mode 100644 index 9cc448e39e..0000000000 --- a/packages/medusa/src/subscribers/batch-job.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* -import { EntityManager } from "typeorm" -import { - BatchJobService, - EventBusService, - StrategyResolverService, -} from "../services" - -type InjectedDependencies = { - eventBusService: EventBusService - batchJobService: BatchJobService - strategyResolverService: StrategyResolverService - manager: EntityManager -} - -class BatchJobSubscriber { - private readonly eventBusService_: EventBusService - private readonly batchJobService_: BatchJobService - private readonly strategyResolver_: StrategyResolverService - private readonly manager_: EntityManager - - constructor({ - eventBusService, - batchJobService, - strategyResolverService, - manager, - }: InjectedDependencies) { - this.eventBusService_ = eventBusService - this.batchJobService_ = batchJobService - this.strategyResolver_ = strategyResolverService - this.manager_ = manager - - this.eventBusService_.subscribe( - BatchJobService.Events.CREATED, - this.preProcessBatchJob - ) as EventBusService - - this.eventBusService_.subscribe( - BatchJobService.Events.CONFIRMED, - this.processBatchJob - ) as EventBusService - } - - preProcessBatchJob = async (data): Promise => { - try { - await this.manager_.transaction(async (manager) => { - const batchJobServiceTx = this.batchJobService_.withTransaction(manager) - const batchJob = await batchJobServiceTx.retrieve(data.id) - - const batchJobStrategy = this.strategyResolver_.resolveBatchJobByType( - batchJob.type - ) - - await batchJobStrategy - .withTransaction(manager) - .preProcessBatchJob(batchJob.id) - await batchJobServiceTx.setPreProcessingDone(batchJob.id) - }) - } catch (e) { - await this.batchJobService_.setFailed(data.id, e.message) - throw e - } - } - - processBatchJob = async (data): Promise => { - try { - await this.manager_.transaction(async (manager) => { - const batchJobServiceTx = this.batchJobService_.withTransaction(manager) - const batchJob = await batchJobServiceTx.retrieve(data.id) - - const batchJobStrategy = this.strategyResolver_.resolveBatchJobByType( - batchJob.type - ) - - await batchJobServiceTx.setProcessing(batchJob.id) - await batchJobStrategy.withTransaction(manager).processJob(batchJob.id) - await batchJobServiceTx.complete(batchJob.id) - }) - } catch (e) { - await this.batchJobService_.setFailed(data.id, e.message) - throw e - } - } -} - -export default BatchJobSubscriber -*/ diff --git a/packages/medusa/src/subscribers/cart.ts b/packages/medusa/src/subscribers/cart.ts deleted file mode 100644 index 421a4ce42d..0000000000 --- a/packages/medusa/src/subscribers/cart.ts +++ /dev/null @@ -1,52 +0,0 @@ -// TODO: we need to discuss this -/* -import { EntityManager } from "typeorm" -import { CartService, EventBusService } from "../services" - -type InjectedDependencies = { - eventBusService: EventBusService - cartService: CartService - manager: EntityManager -} - -class CartSubscriber { - protected readonly manager_: EntityManager - protected readonly cartService_: CartService - protected readonly eventBus_: EventBusService - - constructor({ manager, cartService, eventBusService }: InjectedDependencies) { - this.cartService_ = cartService - this.eventBus_ = eventBusService - this.manager_ = manager - - this.eventBus_.subscribe( - CartService.Events.CUSTOMER_UPDATED, - async (cartId) => { - await this.onCustomerUpdated(cartId) - } - ) - } - - async onCustomerUpdated(cartId) { - await this.manager_.transaction( - "SERIALIZABLE", - async (transactionManager) => { - const cartServiceTx = - this.cartService_.withTransaction(transactionManager) - - const cart = await cartServiceTx.retrieve(cartId, { - relations: ["payment_sessions"], - }) - - if (!cart.payment_sessions?.length) { - return - } - - return await cartServiceTx.setPaymentSessions(cart.id) - } - ) - } -} - -export default CartSubscriber -*/ diff --git a/packages/medusa/src/subscribers/notification.js b/packages/medusa/src/subscribers/notification.js deleted file mode 100644 index a251129321..0000000000 --- a/packages/medusa/src/subscribers/notification.js +++ /dev/null @@ -1,15 +0,0 @@ -class NotificationSubscriber { - constructor({ eventBusService, notificationService }) { - this.notificationService_ = notificationService - - this.eventBus_ = eventBusService - - this.eventBus_.subscribe("*", this.onEvent) - } - - onEvent = (data, eventName) => { - return this.notificationService_.handleEvent(eventName, data) - } -} - -export default NotificationSubscriber diff --git a/packages/medusa/src/subscribers/order.js b/packages/medusa/src/subscribers/order.js deleted file mode 100644 index cc51236966..0000000000 --- a/packages/medusa/src/subscribers/order.js +++ /dev/null @@ -1,67 +0,0 @@ -// TODO: we need to discuss this -/* -import { promiseAll } from "@medusajs/utils" - -class OrderSubscriber { - constructor({ - manager, - eventBusService, - discountService, - giftCardService, - totalsService, - orderService, - draftOrderService, - regionService, - }) { - this.manager_ = manager - this.totalsService_ = totalsService - - this.discountService_ = discountService - - this.giftCardService_ = giftCardService - - this.orderService_ = orderService - - this.draftOrderService_ = draftOrderService - - this.regionService_ = regionService - - this.eventBus_ = eventBusService - - this.eventBus_.subscribe("order.placed", this.handleOrderPlaced) - - this.eventBus_.subscribe("order.placed", this.updateDraftOrder) - } - - handleOrderPlaced = async (data) => { - const order = await this.orderService_.retrieveWithTotals(data.id, { - relations: ["discounts", "discounts.rule"], - }) - - await promiseAll( - order.discounts.map(async (d) => { - const usageCount = d?.usage_count || 0 - return this.discountService_.update(d.id, { - usage_count: usageCount + 1, - }) - }) - ) - } - - updateDraftOrder = async (data) => { - const order = await this.orderService_.retrieve(data.id) - const draftOrder = await this.draftOrderService_ - .retrieveByCartId(order.cart_id) - .catch((_) => null) - - if (draftOrder) { - await this.draftOrderService_.registerCartCompletion( - draftOrder.id, - order.id - ) - } - } -} - -export default OrderSubscriber -*/ diff --git a/packages/medusa/src/subscribers/payment-webhook.ts b/packages/medusa/src/subscribers/payment-webhook.ts index f71d31c9c9..3863b603ed 100644 --- a/packages/medusa/src/subscribers/payment-webhook.ts +++ b/packages/medusa/src/subscribers/payment-webhook.ts @@ -6,7 +6,6 @@ import { ProviderWebhookPayload, Subscriber, } from "@medusajs/types" -import { EventBusService } from "../services" type SerializedBuffer = { data: ArrayBuffer @@ -15,7 +14,7 @@ type SerializedBuffer = { type InjectedDependencies = { paymentModuleService: IPaymentModuleService - eventBusService: EventBusService + eventBusService: IEventBusService } class PaymentWebhookSubscriber { diff --git a/packages/medusa/src/subscribers/product.ts b/packages/medusa/src/subscribers/product.ts deleted file mode 100644 index 4ac17cc2bf..0000000000 --- a/packages/medusa/src/subscribers/product.ts +++ /dev/null @@ -1,122 +0,0 @@ -// TODO: we need to discuss this -/* -import { IEventBusService, ISearchService } from "@medusajs/types" -import { defaultSearchIndexingProductRelations, FlagRouter } from "@medusajs/utils" -import { indexTypes } from "medusa-core-utils" -import { isSearchEngineInstalledResolutionKey } from "../loaders/plugins" -import ProductService from "../services/product" -import ProductVariantService from "../services/product-variant" -import ProductCategoryFeatureFlag from "../loaders/feature-flags/product-categories"; - -type InjectedDependencies = { - eventBusService: IEventBusService - searchService: ISearchService - productService: ProductService - featureFlagRouter: FlagRouter -} - -class ProductSearchSubscriber { - private readonly eventBusService_: IEventBusService - private readonly searchService_: ISearchService - private readonly productService_: ProductService - private readonly featureFlagRouter_: FlagRouter - - constructor(container: InjectedDependencies) { - this.eventBusService_ = container.eventBusService - this.searchService_ = container.searchService - this.productService_ = container.productService - this.featureFlagRouter_ = container.featureFlagRouter - - /!** - * Do not subscribe to any event in case no search engine have been installed. - * If some events need to be subscribed out of the search engine reason, they can be subscribed above this comment - *!/ - - try { - container[isSearchEngineInstalledResolutionKey] - } catch (e) { - return this - } - - this.eventBusService_ - .subscribe(ProductService.Events.CREATED, this.handleProductCreation) - .subscribe(ProductService.Events.UPDATED, this.handleProductUpdate) - .subscribe(ProductService.Events.DELETED, this.handleProductDeletion) - .subscribe( - ProductVariantService.Events.CREATED, - this.handleProductVariantChange - ) - .subscribe( - ProductVariantService.Events.UPDATED, - this.handleProductVariantChange - ) - .subscribe( - ProductVariantService.Events.DELETED, - this.handleProductVariantChange - ) - } - - handleProductCreation = async (data) => { - const relations = [...defaultSearchIndexingProductRelations] - if ( - this.featureFlagRouter_.isFeatureEnabled(ProductCategoryFeatureFlag.key) - ) { - relations.push("categories") - } - - const product = await this.productService_.retrieve(data.id, { - relations, - }) - - await this.searchService_.addDocuments( - ProductService.IndexName, - [product], - indexTypes.products - ) - } - - handleProductUpdate = async (data) => { - const relations = [...defaultSearchIndexingProductRelations] - if ( - this.featureFlagRouter_.isFeatureEnabled(ProductCategoryFeatureFlag.key) - ) { - relations.push("categories") - } - - const product = await this.productService_.retrieve(data.id, { - relations, - }) - - await this.searchService_.addDocuments( - ProductService.IndexName, - [product], - indexTypes.products - ) - } - - handleProductDeletion = async (data) => { - await this.searchService_.deleteDocument(ProductService.IndexName, data.id) - } - - handleProductVariantChange = async (data) => { - const relations = [...defaultSearchIndexingProductRelations] - if ( - this.featureFlagRouter_.isFeatureEnabled(ProductCategoryFeatureFlag.key) - ) { - relations.push("categories") - } - - const product = await this.productService_.retrieve(data.product_id, { - relations, - }) - - await this.searchService_.addDocuments( - ProductService.IndexName, - [product], - indexTypes.products - ) - } -} - -export default ProductSearchSubscriber -*/ diff --git a/packages/medusa/src/subscribers/search-indexing.ts b/packages/medusa/src/subscribers/search-indexing.ts deleted file mode 100644 index ac98953cc0..0000000000 --- a/packages/medusa/src/subscribers/search-indexing.ts +++ /dev/null @@ -1,83 +0,0 @@ -// TODO: we need to discuss this -/* -import { IEventBusService, ISearchService } from "@medusajs/types" -import { FlagRouter, defaultSearchIndexingProductRelations } from "@medusajs/utils" -import { indexTypes } from "medusa-core-utils" -import ProductCategoryFeatureFlag from "../loaders/feature-flags/product-categories" -import { SEARCH_INDEX_EVENT } from "../loaders/search-index" -import { Product } from "../models" -import ProductService from "../services/product" - -type InjectedDependencies = { - eventBusService: IEventBusService - searchService: ISearchService - productService: ProductService - featureFlagRouter: FlagRouter -} - -class SearchIndexingSubscriber { - private readonly eventBusService_: IEventBusService - private readonly searchService_: ISearchService - private readonly productService_: ProductService - private readonly featureFlagRouter_: FlagRouter - - constructor({ - eventBusService, - searchService, - productService, - featureFlagRouter, - }: InjectedDependencies) { - this.eventBusService_ = eventBusService - this.searchService_ = searchService - this.productService_ = productService - this.featureFlagRouter_ = featureFlagRouter - - this.eventBusService_.subscribe(SEARCH_INDEX_EVENT, this.indexDocuments) - } - - indexDocuments = async (): Promise => { - const TAKE = (this.searchService_?.options?.batch_size as number) ?? 1000 - let hasMore = true - - let lastSeenId = "" - - while (hasMore) { - const products = await this.retrieveNextProducts(lastSeenId, TAKE) - - if (products.length > 0) { - await this.searchService_.addDocuments( - ProductService.IndexName, - products, - indexTypes.products - ) - lastSeenId = products[products.length - 1].id - } else { - hasMore = false - } - } - } - - protected async retrieveNextProducts( - lastSeenId: string, - take: number - ): Promise { - const relations = [...defaultSearchIndexingProductRelations] - if ( - this.featureFlagRouter_.isFeatureEnabled(ProductCategoryFeatureFlag.key) - ) { - relations.push("categories") - } - - return await this.productService_.list( - { id: { gt: lastSeenId } }, - { - relations, - take: take, - order: { id: "ASC" }, - } - ) - } -} - -export default SearchIndexingSubscriber -*/ diff --git a/packages/medusa/src/types/analytics-config.ts b/packages/medusa/src/types/analytics-config.ts deleted file mode 100644 index 24f71b8530..0000000000 --- a/packages/medusa/src/types/analytics-config.ts +++ /dev/null @@ -1,9 +0,0 @@ -export type CreateAnalyticsConfig = { - opt_out: boolean - anonymize: boolean -} - -export type UpdateAnalyticsConfig = { - opt_out?: boolean - anonymize?: boolean -} diff --git a/packages/medusa/src/types/batch-job.ts b/packages/medusa/src/types/batch-job.ts deleted file mode 100644 index c9b619a077..0000000000 --- a/packages/medusa/src/types/batch-job.ts +++ /dev/null @@ -1,77 +0,0 @@ -/* -import { Type } from "class-transformer" -import { - IsArray, - IsEnum, - IsOptional, - IsString, - ValidateNested, -} from "class-validator" -import { IsType } from "../utils/validators/is-type" -import { DateComparisonOperator } from "./common" -import { BatchJob } from "../models" - -export enum BatchJobStatus { - CREATED = "created", - PRE_PROCESSED = "pre_processed", - CONFIRMED = "confirmed", - PROCESSING = "processing", - COMPLETED = "completed", - CANCELED = "canceled", - FAILED = "failed", -} - -export type BatchJobUpdateProps = Partial> - -export type CreateBatchJobInput = { - type: string - context: BatchJob["context"] - dry_run: boolean -} - -export type BatchJobResultError = { - message: string - code: string | number - [key: string]: unknown -} - -export type BatchJobResultStatDescriptor = { - key: string - name: string - message: string -} - -export class FilterableBatchJobProps { - @IsOptional() - @IsType([String, [String]]) - id?: string | string[] - - @IsOptional() - @IsEnum(BatchJobStatus, { each: true }) - status?: BatchJobStatus[] - - @IsArray() - @IsOptional() - type?: string[] - - @IsString() - @IsOptional() - @IsType([String, [String]]) - created_by?: string | string[] - - @IsOptional() - @ValidateNested() - @Type(() => DateComparisonOperator) - created_at?: DateComparisonOperator - - @IsOptional() - @ValidateNested() - @Type(() => DateComparisonOperator) - updated_at?: DateComparisonOperator -} - -export type BatchJobCreateProps = Pick< - BatchJob, - "context" | "type" | "created_by" | "dry_run" -> -*/ diff --git a/packages/medusa/src/types/common.ts b/packages/medusa/src/types/common.ts index ccab0a34c0..bf5d1d76e8 100644 --- a/packages/medusa/src/types/common.ts +++ b/packages/medusa/src/types/common.ts @@ -1,13 +1,4 @@ import "reflect-metadata" - -import { Transform, Type } from "class-transformer" -import { - IsDate, - IsNumber, - IsObject, - IsOptional, - IsString, -} from "class-validator" import { FindManyOptions, FindOneOptions, @@ -19,9 +10,6 @@ import { import { FindOptionsOrder } from "typeorm/find-options/FindOptionsOrder" import { FindOptionsRelations } from "typeorm/find-options/FindOptionsRelations" -import { BaseEntity } from "../interfaces" -import { transformDate } from "../utils/validators/date-transform" -import { ClassConstructor } from "./global" /** * Utility type used to remove some optional attributes (coming from K) from a type T @@ -72,9 +60,6 @@ type InnerSelector = { [key in keyof TEntity]?: | TEntity[key] | TEntity[key][] - | DateComparisonOperator - | StringComparisonOperator - | NumericalComparisonOperator | FindOperator } @@ -103,7 +88,7 @@ export interface CustomFindOptions { take?: number } -export type QueryConfig = { +export type QueryConfig = { /** * Default fields and relations to return */ @@ -171,422 +156,3 @@ export type DeleteResponse = { */ deleted: boolean } - -export class EmptyQueryParams {} - -/** - * Fields used to apply flexible filters on dates. - */ -export class DateComparisonOperator { - /** - * The filtered date must be less than this value. - */ - @IsOptional() - @IsDate() - @Transform(transformDate) - lt?: Date - - /** - * The filtered date must be greater than this value. - */ - @IsOptional() - @IsDate() - @Transform(transformDate) - gt?: Date - - /** - * The filtered date must be greater than or equal to this value. - */ - @IsOptional() - @IsDate() - @Transform(transformDate) - gte?: Date - - /** - * The filtered date must be less than or equal to this value. - */ - @IsOptional() - @IsDate() - @Transform(transformDate) - lte?: Date -} - -/** - * Fields used to apply flexible filters on strings. - */ -export class StringComparisonOperator { - /** - * The filtered string must be less than this value. - */ - @IsString() - @IsOptional() - lt?: string - - /** - * The filtered string must be greater than this value. - */ - @IsString() - @IsOptional() - gt?: string - - /** - * The filtered string must be greater than or equal to this value. - */ - @IsString() - @IsOptional() - gte?: string - - /** - * The filtered string must be less than or equal to this value. - */ - @IsString() - @IsOptional() - lte?: string - - /** - * The filtered string must contain this value. - */ - @IsString() - @IsOptional() - contains?: string - - /** - * The filtered string must start with this value. - */ - @IsString() - @IsOptional() - starts_with?: string - - /** - * The filtered string must end with this value. - */ - @IsString() - @IsOptional() - ends_with?: string -} - -/** - * Fields used to apply flexible filters on numbers. - */ -export class NumericalComparisonOperator { - /** - * The filtered number must be less than this value. - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - lt?: number - - /** - * The filtered number must be greater than this value. - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - gt?: number - - /** - * The filtered number must be greater than or equal to this value. - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - gte?: number - - /** - * The filtered number must be less than or equal to this value. - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - lte?: number -} - -/** - * @schema AddressPayload - * type: object - * description: "Address fields used when creating/updating an address." - * properties: - * first_name: - * description: First name - * type: string - * example: Arno - * last_name: - * description: Last name - * type: string - * example: Willms - * phone: - * type: string - * description: Phone Number - * example: 16128234334802 - * company: - * type: string - * description: Company - * address_1: - * description: Address line 1 - * type: string - * example: 14433 Kemmer Court - * address_2: - * description: Address line 2 - * type: string - * example: Suite 369 - * city: - * description: City - * type: string - * example: South Geoffreyview - * country_code: - * description: The 2 character ISO code of the country in lower case - * type: string - * externalDocs: - * url: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements - * description: See a list of codes. - * example: st - * province: - * description: Province - * type: string - * example: Kentucky - * postal_code: - * description: Postal Code - * type: string - * example: 72093 - * metadata: - * type: object - * example: {car: "white"} - * description: An optional key-value map with additional details - */ -export class AddressPayload { - @IsOptional() - @IsString() - first_name?: string - - @IsOptional() - @IsString() - last_name?: string - - @IsOptional() - @IsString() - phone?: string - - @IsOptional() - @IsObject() - metadata?: Record - - @IsOptional() - @IsString() - company?: string - - @IsOptional() - @IsString() - address_1?: string - - @IsOptional() - @IsString() - address_2?: string - - @IsOptional() - @IsString() - city?: string - - @IsOptional() - @IsString() - country_code?: string - - @IsOptional() - @IsString() - province?: string - - @IsOptional() - @IsString() - postal_code?: string -} - -/** - * @schema AddressCreatePayload - * type: object - * description: "Address fields used when creating an address." - * required: - * - first_name - * - last_name - * - address_1 - * - city - * - country_code - * - postal_code - * properties: - * first_name: - * description: First name - * type: string - * example: Arno - * last_name: - * description: Last name - * type: string - * example: Willms - * phone: - * type: string - * description: Phone Number - * example: 16128234334802 - * company: - * type: string - * address_1: - * description: Address line 1 - * type: string - * example: 14433 Kemmer Court - * address_2: - * description: Address line 2 - * type: string - * example: Suite 369 - * city: - * description: City - * type: string - * example: South Geoffreyview - * country_code: - * description: The 2 character ISO code of the country in lower case - * type: string - * externalDocs: - * url: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements - * description: See a list of codes. - * example: st - * province: - * description: Province - * type: string - * example: Kentucky - * postal_code: - * description: Postal Code - * type: string - * example: 72093 - * metadata: - * type: object - * example: {car: "white"} - * description: An optional key-value map with additional details - */ -export class AddressCreatePayload { - @IsString() - first_name: string - - @IsString() - last_name: string - - @IsOptional() - @IsString() - phone: string - - @IsOptional() - metadata: object - - @IsOptional() - @IsString() - company: string - - @IsString() - address_1: string - - @IsOptional() - @IsString() - address_2: string - - @IsString() - city: string - - @IsString() - country_code: string - - @IsOptional() - @IsString() - province: string - - @IsString() - postal_code: string -} - -/** - * Parameters that can be used to configure how data is retrieved. - */ -export class FindParams { - /** - * {@inheritDoc RequestQueryFields.expand} - * @deprecated - */ - @IsString() - @IsOptional() - expand?: string - - /** - * {@inheritDoc RequestQueryFields.fields} - */ - @IsString() - @IsOptional() - fields?: string -} - -/** - * Parameters that can be used to configure how a list of data is paginated. - */ -export class FindPaginationParams { - /** - * {@inheritDoc RequestQueryFields.offset} - * @defaultValue 0 - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - offset?: number = 0 - - /** - * {@inheritDoc RequestQueryFields.limit} - * @defaultValue 20 - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - limit?: number = 20 - - /** - * {@inheritDoc RequestQueryFields.order} - */ - @IsString() - @IsOptional() - @Type(() => String) - order?: string -} - -export function extendedFindParamsMixin({ - limit, - offset, - order, -}: { - limit?: number - offset?: number - order?: string -} = {}): ClassConstructor { - /** - * {@inheritDoc FindParams} - */ - class FindExtendedPaginationParams extends FindParams { - /** - * {@inheritDoc FindPaginationParams.offset} - * @defaultValue 0 - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - offset?: number = offset ?? 0 - - /** - * {@inheritDoc FindPaginationParams.limit} - * @defaultValue 20 - */ - @IsNumber() - @IsOptional() - @Type(() => Number) - limit?: number = limit ?? 20 - - /** - * {@inheritDoc FindPaginationParams.order} - */ - @IsString() - @IsOptional() - @Type(() => String) - order?: string = order - } - - return FindExtendedPaginationParams -} diff --git a/packages/medusa/src/types/idempotency-key.ts b/packages/medusa/src/types/idempotency-key.ts deleted file mode 100644 index ff20e9d0e1..0000000000 --- a/packages/medusa/src/types/idempotency-key.ts +++ /dev/null @@ -1,12 +0,0 @@ -export type CreateIdempotencyKeyInput = { - request_method?: string - request_params?: Record - request_path?: string - idempotency_key?: string -} - -export type IdempotencyCallbackResult = { - recovery_point?: string - response_code?: number - response_body?: Record -} diff --git a/packages/medusa/src/types/scheduled-jobs.ts b/packages/medusa/src/types/scheduled-jobs.ts deleted file mode 100644 index 591e6e3664..0000000000 --- a/packages/medusa/src/types/scheduled-jobs.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { MedusaContainer } from "@medusajs/types" - -export type ScheduledJobConfig = { - /** - * The name of the job - */ - name: string - /** - * The cron schedule of the job, e.g. `0 0 * * *` for running every day at midnight. - */ - schedule: string - /** - * An optional data object to pass to the job handler - */ - data?: T -} - -export type ScheduledJobArgs = { - container: MedusaContainer - data?: T - pluginOptions?: Record -} diff --git a/packages/medusa/src/types/validators/exactly-one.ts b/packages/medusa/src/types/validators/exactly-one.ts deleted file mode 100644 index f76b5ffdf9..0000000000 --- a/packages/medusa/src/types/validators/exactly-one.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { - isDefined, - ValidationArguments, - ValidatorConstraint, - ValidatorConstraintInterface, -} from "class-validator" - -// Defines constraint that ensures exactly one of given properties -// It simply checks if any of the values provided is defined as -// a property on the class along side the property which is decorated -// -// Inspiration: https://github.com/typestack/class-validator/issues/245 -@ValidatorConstraint({ async: false }) -export class ExactlyOne implements ValidatorConstraintInterface { - validate(propertyValue: string, args: ValidationArguments): boolean { - if (isDefined(propertyValue)) { - return this.getFailedConstraints(args).length === 0 - } - return true - } - - defaultMessage(args: ValidationArguments): string { - return `Only one of ${args.property}, ${this.getFailedConstraints( - args - ).join(", ")} is allowed` - } - - getFailedConstraints(args: ValidationArguments): boolean[] { - return args.constraints.filter((prop) => isDefined(args.object[prop])) - } -} diff --git a/packages/medusa/src/types/validators/operator-map.ts b/packages/medusa/src/types/validators/operator-map.ts deleted file mode 100644 index 82f50cfc73..0000000000 --- a/packages/medusa/src/types/validators/operator-map.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { IsArray, IsBoolean, IsOptional, IsString } from "class-validator" - -export class OperatorMapValidator { - @IsOptional() - @IsString() - $eq?: string | string[] - - @IsOptional() - @IsString() - $ne?: string - - @IsOptional() - @IsArray() - $in?: string[] - - @IsOptional() - @IsArray() - $nin?: string[] - - @IsOptional() - @IsString() - $like?: string - - @IsOptional() - @IsString() - $re?: string - - @IsOptional() - @IsString() - $ilike?: string - - @IsOptional() - @IsString() - $fulltext?: string - - @IsOptional() - @IsArray() - $overlap?: string[] - - @IsOptional() - @IsString() - $contains?: string - - @IsOptional() - @IsArray() - $contained?: string[] - - @IsOptional() - @IsBoolean() - $exists?: boolean - - @IsOptional() - @IsString() - $gt?: string - - @IsOptional() - @IsString() - $gte?: string - - @IsOptional() - @IsString() - $lt?: string - - @IsOptional() - @IsString() - $lte?: string -} diff --git a/packages/medusa/src/types/validators/xor.ts b/packages/medusa/src/types/validators/xor.ts deleted file mode 100644 index 7117df584d..0000000000 --- a/packages/medusa/src/types/validators/xor.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { - ValidationArguments, - ValidatorConstraint, - ValidatorConstraintInterface, -} from "class-validator" - -// returns true if it has xor relation with the specified key in the constraint -// stolen from: https://github.com/typestack/class-validator/issues/168#issuecomment-373944641 -@ValidatorConstraint({ name: "xorConstraint", async: false }) -export class XorConstraint implements ValidatorConstraintInterface { - validate(propertyValue: string, args: ValidationArguments): boolean { - return ( - (!!propertyValue && !args.object[args.constraints[0]]) || - (!propertyValue && !!args.object[args.constraints[0]]) - ) - } - - defaultMessage(args: ValidationArguments): string { - return `Failed XOR relation between "${args.property}" and "${args.constraints[0]}".` - } -} diff --git a/packages/medusa/src/utils/__tests__/build-query.spec.ts b/packages/medusa/src/utils/__tests__/build-query.spec.ts deleted file mode 100644 index b1ff6795cf..0000000000 --- a/packages/medusa/src/utils/__tests__/build-query.spec.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { - And, - FindOptionsOrder, - FindOptionsSelect, - In, - LessThanOrEqual, - MoreThan, - MoreThanOrEqual, - Not, -} from "typeorm" -import { - addOrderToSelect, - buildLegacyFieldsListFrom, - buildQuery, -} from "../build-query" - -describe("buildQuery", () => { - it("successfully creates query", () => { - const date = new Date() - - const q = buildQuery( - { - id: "1234", - test1: ["123", "12", "1"], - test2: Not("this"), - date: { gt: date }, - amount: { gt: 10 }, - rule: { - type: "fixed", - }, - updated_at: { - gte: "value", - lte: "value", - }, - }, - { - select: [ - "order", - "order.items", - "order.swaps", - "order.swaps.additional_items", - "order.discounts", - "order.discounts.rule", - "order.claims", - "order.claims.additional_items", - "additional_items", - "additional_items.variant", - "return_order", - "return_order.items", - "return_order.shipping_method", - "return_order.shipping_method.tax_lines", - ], - relations: [ - "order", - "order.items", - "order.swaps", - "order.swaps.additional_items", - "order.discounts", - "order.discounts.rule", - "order.claims", - "order.claims.additional_items", - "additional_items", - "additional_items.variant", - "return_order", - "return_order.items", - "return_order.shipping_method", - "return_order.shipping_method.tax_lines", - "items.variants", - "items.variants.product", - "items", - "items.tax_lines", - "items.adjustments", - ], - order: { - id: "ASC", - "items.id": "ASC", - "items.variant.id": "ASC", - }, - } - ) - - expect(q).toEqual({ - where: { - id: "1234", - test1: In(["123", "12", "1"]), - test2: Not("this"), - date: MoreThan(date), - amount: MoreThan(10), - rule: { - type: "fixed", - }, - updated_at: And(MoreThanOrEqual("value"), LessThanOrEqual("value")), - }, - select: { - order: { - items: true, - swaps: { - additional_items: true, - }, - discounts: { - rule: true, - }, - claims: { - additional_items: true, - }, - }, - additional_items: { - variant: true, - }, - return_order: { - items: true, - shipping_method: { - tax_lines: true, - }, - }, - }, - relations: { - order: { - items: true, - swaps: { - additional_items: true, - }, - discounts: { - rule: true, - }, - claims: { - additional_items: true, - }, - }, - additional_items: { - variant: true, - }, - return_order: { - items: true, - shipping_method: { - tax_lines: true, - }, - }, - items: { - variants: { - product: true, - }, - tax_lines: true, - adjustments: true, - }, - }, - order: { - id: "ASC", - items: { - id: "ASC", - variant: { - id: "ASC", - }, - }, - }, - }) - }) -}) - -describe("buildLegacyFieldsListFrom", () => { - it("successfully build back select object shape to list", () => { - const q = buildLegacyFieldsListFrom({ - order: { - items: true, - swaps: { - additional_items: true, - }, - discounts: { - rule: true, - }, - claims: { - additional_items: true, - }, - }, - additional_items: { - variant: true, - }, - return_order: { - items: true, - shipping_method: { - tax_lines: true, - }, - }, - }) - - expect(q.length).toBe(14) - expect(q).toEqual( - expect.arrayContaining([ - "order", - "order.items", - "order.swaps", - "order.swaps.additional_items", - "order.discounts", - "order.discounts.rule", - "order.claims", - "order.claims.additional_items", - "additional_items", - "additional_items.variant", - "return_order", - "return_order.items", - "return_order.shipping_method", - "return_order.shipping_method.tax_lines", - ]) - ) - }) - - it("successfully build back relation object shape to list", () => { - const q = buildLegacyFieldsListFrom({ - order: { - items: true, - swaps: { - additional_items: true, - }, - discounts: { - rule: true, - }, - claims: { - additional_items: true, - }, - }, - additional_items: { - variant: true, - }, - return_order: { - items: true, - shipping_method: { - tax_lines: true, - }, - }, - items: { - variants: { - product: true, - }, - tax_lines: true, - adjustments: true, - }, - }) - - expect(q.length).toBe(19) - expect(q).toEqual( - expect.arrayContaining([ - "order", - "order.items", - "order.swaps", - "order.swaps.additional_items", - "order.discounts", - "order.discounts.rule", - "order.claims", - "order.claims.additional_items", - "additional_items", - "additional_items.variant", - "return_order", - "return_order.items", - "return_order.shipping_method", - "return_order.shipping_method.tax_lines", - "items.variants", - "items.variants.product", - "items", - "items.tax_lines", - "items.adjustments", - ]) - ) - }) - - it("successfully build back order object shape to list", () => { - const q = buildLegacyFieldsListFrom({ - id: "ASC", - items: { - id: "ASC", - variant: { - id: "ASC", - }, - }, - }) - - expect(q.length).toBe(5) - expect(q).toEqual( - expect.arrayContaining([ - "id", - "items", - "items.id", - "items.variant", - "items.variant.id", - ]) - ) - }) - - describe("addOrderToSelect", function () { - it("successfully add the order fields to the select object", () => { - const select: FindOptionsSelect = { - item: { - variant: { - id: true, - }, - }, - } - - const order: FindOptionsOrder = { - item: { - variant: { - rank: "ASC", - }, - }, - } - - addOrderToSelect(order, select) - - expect(select).toEqual({ - item: { - variant: { - id: true, - rank: true, - }, - }, - }) - }) - }) -}) diff --git a/packages/medusa/src/utils/__tests__/calculate-price-tax-amount.ts b/packages/medusa/src/utils/__tests__/calculate-price-tax-amount.ts deleted file mode 100644 index 95ef87f310..0000000000 --- a/packages/medusa/src/utils/__tests__/calculate-price-tax-amount.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { FlagRouter } from "@medusajs/utils" -import { calculatePriceTaxAmount } from "../calculate-price-tax-amount" - -describe("calculatePriceTaxAmount", () => { - describe("Calculate taxes from a given price", () => { - beforeAll(() => { - jest.spyOn(FlagRouter.prototype, "isFeatureEnabled").mockReturnValue(true) - }) - - it("Tax NOT included", () => { - const tax = calculatePriceTaxAmount({ - price: 150, - taxRate: 0.19, - includesTax: false, - }) - - expect(tax).toBeCloseTo(28.5, 2) - - const tax2 = calculatePriceTaxAmount({ - price: 120, - taxRate: 0.17, - }) - - expect(tax2).toBeCloseTo(20.4, 2) - }) - - it("Tax included", () => { - const tax = calculatePriceTaxAmount({ - price: 115, - taxRate: 0.15, - includesTax: true, - }) - - expect(tax).toBeCloseTo(15, 2) - - const tax2 = calculatePriceTaxAmount({ - price: 2150, - taxRate: 0.17, - includesTax: true, - }) - - expect(tax2).toBeCloseTo(312.39, 2) - }) - }) -}) diff --git a/packages/medusa/src/utils/__tests__/csv-cell-content-formatter.spec.ts b/packages/medusa/src/utils/__tests__/csv-cell-content-formatter.spec.ts deleted file mode 100644 index 9358d9a730..0000000000 --- a/packages/medusa/src/utils/__tests__/csv-cell-content-formatter.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { csvCellContentFormatter } from "../csv-cell-content-formatter" - -type Case = { - str: string - expected: string -} - -const cases: [string, Case][] = [ - [ - "should return a the exact input content", - { - str: "Hello my name is Adrien and I like writing single line content.", - expected: - 'Hello my name is Adrien and I like writing single line content.', - }, - ], - [ - "should return a formatted string escaping the coma", - { - str: "Hello, my name is Adrien and I like writing single line content.", - expected: - '"Hello, my name is Adrien and I like writing single line content."', - }, - ], - [ - "should return a formatted string escaping the semicolon", - { - str: "Hello; my name is Adrien and I like writing single line content.", - expected: - '"Hello; my name is Adrien and I like writing single line content."', - }, - ], - [ - "should return a formatted string escaping new line when there is new line chars", - { - str: `Hello, -my name is Adrien and -I like writing multiline content -in a template string`, - expected: - '"Hello,\nmy name is Adrien and\nI like writing multiline content\nin a template string"', - }, - ], - [ - "should return a formatted string escaping new line when there is new line chars and escape the double quote when there is double quotes", - { - str: 'Hello,\nmy name is "Adrien" and\nI like writing multiline content\nin a string', - expected: - '"Hello,\nmy name is ""Adrien"" and\nI like writing multiline content\nin a string"', - }, - ], -] - -describe("csvCellContentFormatter", function () { - it.each(cases)("%s", (title: string, { str, expected }: Case) => { - const formattedStr = csvCellContentFormatter(str) - expect(formattedStr).toBe(expected) - }) -}) diff --git a/packages/medusa/src/utils/__tests__/generate-entity-id.ts b/packages/medusa/src/utils/__tests__/generate-entity-id.ts deleted file mode 100644 index 58b42daca1..0000000000 --- a/packages/medusa/src/utils/__tests__/generate-entity-id.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { generateEntityId } from "../generate-entity-id" -import { Entity, PrimaryColumn } from "typeorm" - -@Entity() -class GenerateIdSpecEntity { - @PrimaryColumn() - id: string -} - -describe("generateAndApplyEntityId", () => { - it('should return the id if already set', () => { - const entity = new GenerateIdSpecEntity() - entity.id = "fakeId" - - const generatedId = generateEntityId(entity.id, "prefix") - expect(generatedId).toBe(entity.id) - }) - - it('should return the new generated id if not set already', () => { - const entity = new GenerateIdSpecEntity() - - entity.id = generateEntityId(entity.id, "prefix") - expect(entity.id).toBeTruthy() - expect(entity.id).toEqual(expect.stringMatching(/prefix_*/)) - }) -}) diff --git a/packages/medusa/src/utils/__tests__/has-changes.spec.ts b/packages/medusa/src/utils/__tests__/has-changes.spec.ts deleted file mode 100644 index ac543f5fe5..0000000000 --- a/packages/medusa/src/utils/__tests__/has-changes.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { hasChanges } from "../has-changes" - -describe("hasChanges", function () { - it("should return true the data differ and false otherwise", () => { - const objToCompareTo = { - prop1: "test", - prop2: "test", - prop3: "test", - prop4: { - prop4_1: "test", - prop4_2: "test", - prop4_3: "test", - }, - } - - const obj = { - prop1: "test", - prop2: "test", - prop3: "test", - prop4: { - prop4_1: "test", - prop4_2: "test", - prop4_3: "test", - }, - } - - let res = hasChanges(objToCompareTo, obj) - expect(res).toBeFalsy() - - const obj2 = { - ...obj, - prop3: "tes", - } - - res = hasChanges(objToCompareTo, obj2) - expect(res).toBeTruthy() - - const obj3 = { - ...obj, - prop4: { - prop4_1: "", - prop4_2: "test", - prop4_3: "test", - }, - } - - res = hasChanges(objToCompareTo, obj3) - expect(res).toBeTruthy() - - const obj4 = { - ...obj, - } - /* @ts-ignore */ - delete obj4.prop4 - - res = hasChanges(objToCompareTo, obj4) - expect(res).toBeFalsy() - }) -}) diff --git a/packages/medusa/src/utils/build-query.ts b/packages/medusa/src/utils/build-query.ts deleted file mode 100644 index 7a6cda5cb4..0000000000 --- a/packages/medusa/src/utils/build-query.ts +++ /dev/null @@ -1,243 +0,0 @@ -import { - And, - FindManyOptions, - FindOperator, - FindOptionsRelations, - FindOptionsSelect, - FindOptionsWhere, - ILike, - In, - IsNull, - LessThan, - LessThanOrEqual, - MoreThan, - MoreThanOrEqual, -} from "typeorm" -import { ExtendedFindConfig, FindConfig } from "../types/common" - -import { FindOptionsOrder } from "typeorm/find-options/FindOptionsOrder" -import { isObject } from "./is-object" -import { buildOrder, buildRelations, buildSelects } from "@medusajs/utils" - -const operatorsMap = { - lt: (value) => LessThan(value), - gt: (value) => MoreThan(value), - lte: (value) => LessThanOrEqual(value), - gte: (value) => MoreThanOrEqual(value), - contains: (value) => ILike(`%${value}%`), - starts_with: (value) => ILike(`${value}%`), - ends_with: (value) => ILike(`%${value}`), -} - -/** - * Used to build TypeORM queries. - * @param selector The selector - * @param config The config - * @return The QueryBuilderConfig - */ -export function buildQuery( - selector: TWhereKeys, - config: FindConfig = {} -) { - const query: ExtendedFindConfig = { - where: buildWhere(selector), - } - - if ("deleted_at" in selector) { - query.withDeleted = true - } - - if ("skip" in config) { - ;(query as FindManyOptions).skip = config.skip ?? undefined - } - - if ("take" in config) { - ;(query as FindManyOptions).take = config.take ?? undefined - } - - if (config.relations) { - query.relations = buildRelations( - config.relations - ) as FindOptionsRelations - } - - if (config.select) { - query.select = buildSelects( - config.select as string[] - ) as FindOptionsSelect - } - - if (config.order) { - query.order = buildOrder(config.order) as FindOptionsOrder - } - - return query -} - -/** - * @param constraints - * - * @example - * const q = buildWhere( - * { - * id: "1234", - * test1: ["123", "12", "1"], - * test2: Not("this"), - * date: { gt: date }, - * amount: { gt: 10 }, - * }, - *) - * - * // Output - * { - * id: "1234", - * test1: In(["123", "12", "1"]), - * test2: Not("this"), - * date: MoreThan(date), - * amount: MoreThan(10) - * } - */ -function buildWhere( - constraints: TWhereKeys -): FindOptionsWhere | FindOptionsWhere[] { - let where: FindOptionsWhere | FindOptionsWhere[] = {} - - if (Array.isArray(constraints)) { - where = [] - constraints.forEach((constraint) => { - ;(where as FindOptionsWhere[]).push( - buildWhere(constraint) as FindOptionsWhere - ) - }) - - return where - } - - for (const [key, value] of Object.entries(constraints)) { - if (value === undefined) { - continue - } - - if (value === null) { - where[key] = IsNull() - continue - } - - if (value instanceof FindOperator) { - where[key] = value - continue - } - - if (Array.isArray(value)) { - where[key] = In(value) - continue - } - - if (typeof value === "object") { - Object.entries(value).forEach(([objectKey, objectValue]) => { - where[key] = where[key] || [] - if (operatorsMap[objectKey]) { - where[key].push(operatorsMap[objectKey](objectValue)) - } else { - if (objectValue != undefined && typeof objectValue === "object") { - where[key] = buildWhere(objectValue) - return - } - where[key] = value - } - return - }) - - if (!Array.isArray(where[key])) { - continue - } - - if (where[key].length === 1) { - where[key] = where[key][0] - } else { - where[key] = And(...where[key]) - } - - continue - } - - where[key] = value - } - - return where -} - -/** - * Revert new object structure of find options to the legacy structure of previous version - * @deprecated in favor of import { objectToStringPath } from "@medusajs/utils" - * @example - * input: { - * test: { - * test1: true, - * test2: true, - * test3: { - * test4: true - * }, - * }, - * test2: true - * } - * output: ['test.test1', 'test.test2', 'test.test3.test4', 'test2'] - * @param input - */ -export function buildLegacyFieldsListFrom( - input: - | FindOptionsWhere - | FindOptionsSelect - | FindOptionsOrder - | FindOptionsRelations = {} -): (keyof TEntity)[] { - if (!Object.keys(input).length) { - return [] - } - - const output: Set = new Set(Object.keys(input)) - - for (const key of Object.keys(input)) { - if (input[key] != undefined && typeof input[key] === "object") { - const deepRes = buildLegacyFieldsListFrom(input[key]) - - const items = deepRes.reduce((acc, val) => { - acc.push(`${key}.${val}`) - return acc - }, [] as string[]) - - items.forEach((item) => output.add(item)) - continue - } - - output.add(key) - } - - return Array.from(output) as (keyof TEntity)[] -} - -export function addOrderToSelect( - order: FindOptionsOrder, - select: FindOptionsSelect -): void { - for (const orderBy of Object.keys(order)) { - if (isObject(order[orderBy])) { - select[orderBy] = - select[orderBy] && isObject(select[orderBy]) ? select[orderBy] : {} - addOrderToSelect(order[orderBy], select[orderBy]) - continue - } - - select[orderBy] = isObject(select[orderBy]) - ? { ...select[orderBy], id: true, [orderBy]: true } - : true - } -} - -export function nullableValue(value: any): FindOperator { - if (value === null) { - return IsNull() - } else { - return value - } -} diff --git a/packages/medusa/src/utils/calculate-price-tax-amount.ts b/packages/medusa/src/utils/calculate-price-tax-amount.ts deleted file mode 100644 index 396f3322d7..0000000000 --- a/packages/medusa/src/utils/calculate-price-tax-amount.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Return the tax amount that - * - * - is includes in the price if it is tax inclusive - * - will be applied on to the price if it is tax exclusive - */ -export function calculatePriceTaxAmount({ - price, - includesTax, - taxRate, -}: { - price: number - includesTax?: boolean - taxRate: number -}): number { - if (includesTax) { - return (taxRate * price) / (1 + taxRate) - } - - return price * taxRate -} diff --git a/packages/medusa/src/utils/countries.ts b/packages/medusa/src/utils/countries.ts deleted file mode 100644 index 66af48e31f..0000000000 --- a/packages/medusa/src/utils/countries.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { defaultCountries, Country } from "@medusajs/utils" -export const countries: Country[] = defaultCountries diff --git a/packages/medusa/src/utils/csv-cell-content-formatter.ts b/packages/medusa/src/utils/csv-cell-content-formatter.ts deleted file mode 100644 index f7a1dc5989..0000000000 --- a/packages/medusa/src/utils/csv-cell-content-formatter.ts +++ /dev/null @@ -1,24 +0,0 @@ -export function csvCellContentFormatter(str: string): string { - const newLineRegexp = new RegExp(/\n/g) - const doubleQuoteRegexp = new RegExp(/"/g) - const comaRegexp = new RegExp(/,/g) - const semicolonRegexp = new RegExp(/;/g) - - const hasNewLineChar = !!str.match(newLineRegexp) - const hasComaChar = !!str.match(comaRegexp) - const hasSemicolonChar = !!str.match(semicolonRegexp) - if (!hasNewLineChar && !hasComaChar && !hasSemicolonChar) { - return str - } - - const formatterStr = str.replace(doubleQuoteRegexp, `""`) - - return `"${formatterStr}"` -} - -export function csvRevertCellContentFormatter(str: string): string { - if (str.startsWith(`"`)) { - str = str.substring(1, str.length - 1) - } - return str -} diff --git a/packages/medusa/src/utils/currencies.ts b/packages/medusa/src/utils/currencies.ts deleted file mode 100644 index 158a52cb95..0000000000 --- a/packages/medusa/src/utils/currencies.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { defaultCurrencies, Currency } from "@medusajs/utils" -export const currencies: Record = defaultCurrencies diff --git a/packages/medusa/src/utils/db-aware-column.ts b/packages/medusa/src/utils/db-aware-column.ts deleted file mode 100644 index 9dc7e740a1..0000000000 --- a/packages/medusa/src/utils/db-aware-column.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Column, ColumnOptions, ColumnType } from "typeorm" - -export function resolveDbType(pgSqlType: ColumnType): ColumnType { - return pgSqlType -} - -export function resolveDbGenerationStrategy( - pgSqlType: "increment" | "uuid" | "rowid" -): "increment" | "uuid" | "rowid" { - return pgSqlType -} - -export function DbAwareColumn(columnOptions: ColumnOptions): PropertyDecorator { - const pre = columnOptions.type - if (columnOptions.type) { - columnOptions.type = resolveDbType(columnOptions.type) - } - - if (pre === "jsonb" && pre !== columnOptions.type) { - if ("default" in columnOptions) { - columnOptions.default = JSON.stringify(columnOptions.default) - } - } - - return Column(columnOptions) -} diff --git a/packages/medusa/src/utils/feature-flag-decorators.ts b/packages/medusa/src/utils/feature-flag-decorators.ts deleted file mode 100644 index 8a741c8dff..0000000000 --- a/packages/medusa/src/utils/feature-flag-decorators.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Column, ColumnOptions, Entity, EntityOptions } from "typeorm" -import { featureFlagRouter } from "../loaders/feature-flags" -import { Equals, ValidateIf } from "class-validator" -import { isDefined } from "@medusajs/utils" - -/** - * If that file is required in a non node environment then the setImmediate timer does not exists. - * This can happen when a client package require a server based package and that one of the import - * require to import that file which is using the setImmediate. - * In order to take care of those cases, the setImmediate timer will use the one provided by the api (node) - * if possible and will provide a mock in a browser like environment. - */ -let setImmediate_ -try { - setImmediate_ = setImmediate -} catch (e) { - console.warn( - "[feature-flag-decorator.ts] setImmediate will use a mock, this happen when this file is required in a browser environment and should not impact you" - ) - setImmediate_ = async (callback: () => void | Promise) => callback() -} - -export function FeatureFlagColumn( - featureFlag: string, - columnOptions: ColumnOptions = {} -): PropertyDecorator { - return function (target, propertyName) { - setImmediate_((): any => { - if (!featureFlagRouter.isFeatureEnabled(featureFlag)) { - return - } - - Column(columnOptions)(target, propertyName) - }) - } -} - -export function FeatureFlagDecorators( - featureFlag: string | string[], - decorators: PropertyDecorator[] -): PropertyDecorator { - return function (target, propertyName) { - setImmediate_((): any => { - if (!featureFlagRouter.isFeatureEnabled(featureFlag)) { - ValidateIf((o) => isDefined(o[propertyName]))(target, propertyName) - Equals(undefined, { - message: `${propertyName as string} should not exist`, - })(target, propertyName) - return - } - - decorators.forEach((decorator: PropertyDecorator) => { - decorator(target, propertyName) - }) - }) - } -} - -export function FeatureFlagClassDecorators( - featureFlag: string | string[], - decorators: ClassDecorator[] -): ClassDecorator { - return function (target) { - setImmediate_((): any => { - if (!featureFlagRouter.isFeatureEnabled(featureFlag)) { - return - } - - decorators.forEach((decorator: ClassDecorator) => { - decorator(target) - }) - }) - } -} - -export function FeatureFlagEntity( - featureFlag: string | string[], - name?: string, - options?: EntityOptions -): ClassDecorator { - return function (target: Function): void { - target["isFeatureEnabled"] = function (): boolean { - return featureFlagRouter.isFeatureEnabled(featureFlag) - } - Entity(name, options)(target) - } -} diff --git a/packages/medusa/src/utils/generate-entity-id.ts b/packages/medusa/src/utils/generate-entity-id.ts deleted file mode 100644 index 4f4f61766e..0000000000 --- a/packages/medusa/src/utils/generate-entity-id.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ulid } from "ulid" - -/** - * Generate a composed id based on the input parameters and return either the is if it exists or the generated one. - * @param idProperty - * @param prefix - */ -export function generateEntityId(idProperty?: string, prefix?: string): string { - if (idProperty) { - return idProperty - } - - const id = ulid() - prefix = prefix ? `${prefix}_` : "" - return `${prefix}${id}` -} diff --git a/packages/medusa/src/utils/get-query-config.ts b/packages/medusa/src/utils/get-query-config.ts index 21cd187d0e..0d7d6090ad 100644 --- a/packages/medusa/src/utils/get-query-config.ts +++ b/packages/medusa/src/utils/get-query-config.ts @@ -6,11 +6,9 @@ import { import { pick } from "lodash" import { MedusaError, isDefined } from "medusa-core-utils" import { RequestQueryFields } from "@medusajs/types" -import { BaseEntity } from "../interfaces" -import { featureFlagRouter } from "../loaders/feature-flags" import { FindConfig, QueryConfig } from "../types/common" -export function pickByConfig( +export function pickByConfig( obj: TModel | TModel[], config: FindConfig ): Partial | Partial[] { @@ -26,10 +24,10 @@ export function pickByConfig( return obj } -export function prepareListQuery< - T extends RequestQueryFields, - TEntity extends BaseEntity ->(validated: T, queryConfig: QueryConfig = {}) { +export function prepareListQuery( + validated: T, + queryConfig: QueryConfig = {} +) { // TODO: this function will be simplified a lot once we drop support for the old api const { order, fields, limit = 50, expand, offset = 0 } = validated let { @@ -215,10 +213,10 @@ export function prepareListQuery< } } -export function prepareRetrieveQuery< - T extends RequestQueryFields, - TEntity extends BaseEntity ->(validated: T, queryConfig?: QueryConfig) { +export function prepareRetrieveQuery( + validated: T, + queryConfig?: QueryConfig +) { const { listConfig, remoteQueryConfig } = prepareListQuery( validated, queryConfig diff --git a/packages/medusa/src/utils/has-changes.ts b/packages/medusa/src/utils/has-changes.ts deleted file mode 100644 index 2b0826e524..0000000000 --- a/packages/medusa/src/utils/has-changes.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { isObject } from "./is-object" - -/** - * Compare two objects and return true if there is changes detected from obj2 compared to obj1 - * @param obj1 - * @param obj2 - */ -export function hasChanges( - obj1: T1, - obj2: T2 -): boolean { - for (const [key, value] of Object.entries(obj2)) { - if (isObject(obj1[key])) { - if (hasChanges(obj1[key], value)) { - return true - } - continue - } - - if (obj1[key] !== value) { - return true - } - } - - return false -} diff --git a/packages/medusa/src/utils/idempotency/index.ts b/packages/medusa/src/utils/idempotency/index.ts deleted file mode 100644 index 8d7196fd83..0000000000 --- a/packages/medusa/src/utils/idempotency/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./run-idempotency-step" -export * from "./initialize-idempotency-request" diff --git a/packages/medusa/src/utils/idempotency/initialize-idempotency-request.ts b/packages/medusa/src/utils/idempotency/initialize-idempotency-request.ts deleted file mode 100644 index ae8bc96022..0000000000 --- a/packages/medusa/src/utils/idempotency/initialize-idempotency-request.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Request, Response } from "express" -import { IdempotencyKey } from "../../models" -import IdempotencyKeyService from "../../services/idempotency-key" -import { EntityManager } from "typeorm" - -export async function initializeIdempotencyRequest( - req: Request, - res: Response -): Promise { - const idempotencyKeyService: IdempotencyKeyService = req.scope.resolve( - "idempotencyKeyService" - ) - const manager: EntityManager = req.scope.resolve("manager") - - const headerKey = req.get("Idempotency-Key") || "" - - let idempotencyKey - idempotencyKey = await idempotencyKeyService - .withTransaction(manager) - .initializeRequest(headerKey, req.method, req.params, req.path) - - res.setHeader("Access-Control-Expose-Headers", "Idempotency-Key") - res.setHeader("Idempotency-Key", idempotencyKey.idempotency_key) - - return idempotencyKey -} diff --git a/packages/medusa/src/utils/idempotency/run-idempotency-step.ts b/packages/medusa/src/utils/idempotency/run-idempotency-step.ts deleted file mode 100644 index 2e14e449f6..0000000000 --- a/packages/medusa/src/utils/idempotency/run-idempotency-step.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { IdempotencyCallbackResult } from "../../types/idempotency-key" -import { EntityManager } from "typeorm" -import { IdempotencyKey } from "../../models" -import { AwilixContainer } from "awilix" -import IdempotencyKeyService from "../../services/idempotency-key" -import { IsolationLevel } from "typeorm/driver/types/IsolationLevel" - -export type RunIdempotencyStepOptions = { - manager: EntityManager - idempotencyKey: IdempotencyKey - container: AwilixContainer - isolationLevel: IsolationLevel -} - -export async function runIdempotencyStep( - handler: ({ - manager, - }: { - manager: EntityManager - }) => Promise, - { - manager, - idempotencyKey, - container, - isolationLevel, - }: RunIdempotencyStepOptions -) { - const idempotencyKeyService: IdempotencyKeyService = container.resolve( - "idempotencyKeyService" - ) - return await manager.transaction( - isolationLevel, - async (transactionManager) => { - const idempotencyKey_ = await idempotencyKeyService - .withTransaction(transactionManager) - .workStage(idempotencyKey.idempotency_key, async (stageManager) => { - return await handler({ manager: stageManager }) - }) - idempotencyKey.response_code = idempotencyKey_.response_code - idempotencyKey.response_body = idempotencyKey_.response_body - idempotencyKey.recovery_point = idempotencyKey_.recovery_point - } - ) -} diff --git a/packages/medusa/src/utils/index.ts b/packages/medusa/src/utils/index.ts index f3e6dcbd24..6b41e538ef 100644 --- a/packages/medusa/src/utils/index.ts +++ b/packages/medusa/src/utils/index.ts @@ -1,11 +1,5 @@ -export * from "./build-query" -export * from "./calculate-price-tax-amount" export * from "./clean-response-data" -export * from "./csv-cell-content-formatter" -export * from "./db-aware-column" export * from "./exception-formatter" -export * from "./generate-entity-id" -export * from "./has-changes" export * from "./is-date" export * from "./is-object" export * from "./is-string" @@ -13,7 +7,4 @@ export * from "./omit-deep" export * from "./remote-query-fetch-data" export * from "./remove-undefined-properties" export * from "./set-metadata" -export * from "./validate-id" -export { registerOverriddenValidators, validator } from "./validator" -export * from "./validators/is-type" export * from "./middlewares" diff --git a/packages/medusa/src/utils/is-email.ts b/packages/medusa/src/utils/is-email.ts deleted file mode 100644 index ff63c48e2c..0000000000 --- a/packages/medusa/src/utils/is-email.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { isEmail } from "class-validator" -import { MedusaError } from "medusa-core-utils" - -/** - * Used to validate user email. - * @param {string} email - email to validate - * @return {string} the validated email - */ -export function validateEmail(email: string): string { - const validatedEmail = isEmail(email) - - if (!validatedEmail) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - "The email is not valid" - ) - } - - return email.toLowerCase() -} diff --git a/packages/medusa/src/utils/manual-auto-increment.ts b/packages/medusa/src/utils/manual-auto-increment.ts deleted file mode 100644 index d16e4100ec..0000000000 --- a/packages/medusa/src/utils/manual-auto-increment.ts +++ /dev/null @@ -1,5 +0,0 @@ -export async function manualAutoIncrement( - tableName: string -): Promise { - return null -} diff --git a/packages/medusa/src/utils/middlewares/__tests__/transform-query.spec.ts b/packages/medusa/src/utils/middlewares/__tests__/transform-query.spec.ts deleted file mode 100644 index 51c17ff385..0000000000 --- a/packages/medusa/src/utils/middlewares/__tests__/transform-query.spec.ts +++ /dev/null @@ -1,716 +0,0 @@ -import { NextFunction, Request, Response } from "express" -import { transformQuery } from "../transform-query" -import { extendedFindParamsMixin } from "../../../types/common" -import { MedusaError } from "medusa-core-utils" - -describe("transformQuery", () => { - afterEach(() => { - jest.clearAllMocks() - }) - - it("should transform the input query", async () => { - let mockRequest = { - query: {}, - } as Request - const mockResponse = {} as Response - const nextFunction: NextFunction = jest.fn() - - const expectations = ({ - offset, - limit, - inputOrder, - transformedOrder, - }: { - offset: number - limit: number - inputOrder: string | undefined - transformedOrder?: Record - relations?: string[] - }) => { - expect(mockRequest.validatedQuery).toEqual({ - offset, - limit, - order: inputOrder, - }) - expect(mockRequest.filterableFields).toEqual({}) - expect(mockRequest.allowedProperties).toEqual([ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ]) - expect(mockRequest.listConfig).toEqual({ - take: limit, - skip: offset, - select: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - relations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - order: transformedOrder, - }) - expect(mockRequest.remoteQueryConfig).toEqual({ - fields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - pagination: { - order: transformedOrder, - skip: offset, - take: limit, - }, - }) - } - - let queryConfig: any = { - defaultFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - defaultRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - isList: true, - } - - let middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expectations({ - limit: 20, - offset: 0, - inputOrder: undefined, - }) - - ////////////////////////////// - - mockRequest = { - query: { - limit: "10", - offset: "5", - order: "created_at", - }, - } as unknown as Request - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expectations({ - limit: 10, - offset: 5, - inputOrder: "created_at", - transformedOrder: { created_at: "ASC" }, - }) - - ////////////////////////////// - - mockRequest = { - query: { - limit: "10", - offset: "5", - order: "created_at", - }, - } as unknown as Request - - queryConfig = { - defaults: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expectations({ - limit: 10, - offset: 5, - inputOrder: "created_at", - transformedOrder: { created_at: "ASC" }, - }) - }) - - it("should transform the input query taking into account the fields symbols (+,- or no symbol)", async () => { - let mockRequest = { - query: { - fields: "id", - }, - } as unknown as Request - const mockResponse = {} as Response - const nextFunction: NextFunction = jest.fn() - - let queryConfig: any = { - defaultFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - defaultRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - isList: true, - } - - let middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(mockRequest.listConfig).toEqual( - expect.objectContaining({ - select: ["id", "created_at"], - }) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "+test_prop,-prop-test-something", - }, - } as unknown as Request - - queryConfig = { - defaultFields: [ - "id", - "prop-test-something", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - defaultRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(mockRequest.listConfig).toEqual( - expect.objectContaining({ - select: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "test_prop", - ], - }) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "+test_prop,-updated_at", - }, - } as unknown as Request - - queryConfig = { - defaults: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(mockRequest.listConfig).toEqual( - expect.objectContaining({ - select: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "test_prop", - ], - }) - ) - }) - - it(`should transform the input and manage the allowed fields and relations properly without error`, async () => { - let mockRequest = { - query: { - fields: "*product.variants,+product.id", - }, - } as unknown as Request - const mockResponse = {} as Response - const nextFunction: NextFunction = jest.fn() - - let queryConfig: any = { - defaults: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowed: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product", - "product.variants", - ], - isList: true, - } - - let middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(mockRequest.listConfig).toEqual( - expect.objectContaining({ - select: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product.id", - ], - relations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - "product", - "product.variants", - ], - }) - ) - expect(mockRequest.remoteQueryConfig).toEqual( - expect.objectContaining({ - fields: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product.id", - "product.variants.*", - ], - }) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "store.name", - }, - } as unknown as Request - - queryConfig = { - defaultFields: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowedFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product", - "product.variants", - "store.name", - ], - allowedRelations: ["metadata", "product"], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(mockRequest.listConfig).toEqual( - expect.objectContaining({ - select: ["store.name", "created_at", "id"], - relations: ["store"], - }) - ) - expect(mockRequest.remoteQueryConfig).toEqual( - expect.objectContaining({ - fields: ["store.name", "created_at", "id"], - }) - ) - }) - - it("should throw when attempting to transform the input if disallowed fields are requested", async () => { - let mockRequest = { - query: { - fields: "+test_prop", - }, - } as unknown as Request - const mockResponse = {} as Response - const nextFunction: NextFunction = jest.fn() - - let queryConfig: any = { - defaultFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - defaultRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - allowedFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - isList: true, - } - - let middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [test_prop] are not valid` - ) - ) - - ////////////////////////////// - - mockRequest = { - query: { - expand: "product", - }, - } as unknown as Request - - queryConfig = { - defaultFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - defaultRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - allowedFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowedRelations: [ - "metadata", - "metadata.parent", - "metadata.children", - "metadata.product", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [product] are not valid` - ) - ) - - ////////////////////////////// - - mockRequest = { - query: { - expand: "store", - }, - } as unknown as Request - - queryConfig = { - defaultFields: [ - "id", - "created_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowedFields: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product", - "product.variants", - "store.name", - ], - allowedRelations: ["metadata", "product"], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [store] are not valid` - ) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "*product", - }, - } as unknown as Request - - queryConfig = { - defaults: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowed: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [product] are not valid` - ) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "*product.variants", - }, - } as unknown as Request - - queryConfig = { - defaults: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowed: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - "product", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [product.variants] are not valid` - ) - ) - - ////////////////////////////// - - mockRequest = { - query: { - fields: "product", - }, - } as unknown as Request - - queryConfig = { - defaults: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - allowed: [ - "id", - "created_at", - "updated_at", - "deleted_at", - "metadata.id", - "metadata.parent.id", - "metadata.children.id", - "metadata.product.id", - ], - isList: true, - } - - middleware = transformQuery(extendedFindParamsMixin(), queryConfig) - - await middleware(mockRequest, mockResponse, nextFunction) - - expect(nextFunction).toHaveBeenCalledWith( - new MedusaError( - MedusaError.Types.INVALID_DATA, - `Requested fields [product] are not valid` - ) - ) - }) -}) diff --git a/packages/medusa/src/utils/middlewares/index.ts b/packages/medusa/src/utils/middlewares/index.ts index 97453ab2d3..0811ad6134 100644 --- a/packages/medusa/src/utils/middlewares/index.ts +++ b/packages/medusa/src/utils/middlewares/index.ts @@ -4,8 +4,4 @@ export { default as authenticateCustomer } from "./authenticate-customer" export { default as wrapHandler } from "./await-middleware" export { default as errorHandler } from "./error-handler" export { isFeatureFlagEnabled } from "./feature-flag-enabled" -export { default as normalizeQuery } from "./normalized-query" export { default as requireCustomerAuthentication } from "./require-customer-authentication" -export { transformBody } from "./transform-body" -export { transformIncludesOptions } from "./transform-includes-options" -export { transformQuery, transformStoreQuery } from "./transform-query" diff --git a/packages/medusa/src/utils/middlewares/normalized-query.ts b/packages/medusa/src/utils/middlewares/normalized-query.ts deleted file mode 100644 index 7cc6e90231..0000000000 --- a/packages/medusa/src/utils/middlewares/normalized-query.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { NextFunction, Request, Response } from "express" - -/** - * Normalize an input query, especially from array like query params to an array type - * e.g: /admin/orders/?fields[]=id,status,cart_id becomes { fields: ["id", "status", "cart_id"] } - */ -export default (): (( - req: Request, - res: Response, - next: NextFunction -) => void) => { - return (req: Request, res: Response, next: NextFunction): void => { - req.query = Object.entries(req.query).reduce((acc, [key, val]) => { - if (Array.isArray(val) && val.length === 1) { - acc[key] = (val as string[])[0].split(",") - } else { - acc[key] = val - } - return acc - }, {}) - - next() - } -} diff --git a/packages/medusa/src/utils/middlewares/transform-body.ts b/packages/medusa/src/utils/middlewares/transform-body.ts deleted file mode 100644 index 026ee29dc8..0000000000 --- a/packages/medusa/src/utils/middlewares/transform-body.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { ValidatorOptions } from "class-validator" -import { NextFunction, Request, Response } from "express" -import { ClassConstructor } from "../../types/global" -import { validator } from "../../utils/validator" - -export function transformBody( - plainToClass: ClassConstructor, - config: ValidatorOptions = { - forbidUnknownValues: false, - } -): (req: Request, res: Response, next: NextFunction) => Promise { - return async (req: Request, res: Response, next: NextFunction) => { - try { - req.validatedBody = await validator(plainToClass, req.body, config) - next() - } catch (e) { - next(e) - } - } -} diff --git a/packages/medusa/src/utils/middlewares/transform-includes-options.ts b/packages/medusa/src/utils/middlewares/transform-includes-options.ts deleted file mode 100644 index 54b898f423..0000000000 --- a/packages/medusa/src/utils/middlewares/transform-includes-options.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { NextFunction, Request, Response } from "express" -import { MedusaError } from "medusa-core-utils" - -/** - * Retrieve the includes options from the fields query param. - * If the include option is present then assigned it to includes on req - * @param allowedIncludes The list of fields that can be passed and assign to req.includes - * @param expectedIncludes The list of fields that the consumer can pass to the end point using this middleware. It is a subset of `allowedIncludes` - */ -export function transformIncludesOptions( - allowedIncludes: string[] = [], - expectedIncludes: string[] = [] -) { - return (req: Request, res: Response, next: NextFunction): void => { - if (!allowedIncludes.length || !req.query.expand) { - return next() - } - - const expand = (req.query.expand as string).split(",") ?? [] - - for (const includes of allowedIncludes) { - const fieldIndex = expand.indexOf(includes) ?? -1 - - const isPresent = fieldIndex !== -1 - - if (isPresent) { - expand.splice(fieldIndex, 1) - - if (!expectedIncludes.includes(includes)) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `The field "${includes}" is not supported by this end point. ${ - expectedIncludes.length - ? `The includes fields can be one of entity properties or in [${expectedIncludes.join( - ", " - )}]` - : "" - }` - ) - } - - req.includes = req.includes ?? {} - req.includes[includes] = true - } - } - - if (req.query.expand) { - if (expand.length) { - req.query.expand = expand.join(",") - } else { - delete req.query.expand - } - } - - next() - } -} diff --git a/packages/medusa/src/utils/middlewares/transform-query.ts b/packages/medusa/src/utils/middlewares/transform-query.ts deleted file mode 100644 index bf228a56fd..0000000000 --- a/packages/medusa/src/utils/middlewares/transform-query.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { ValidatorOptions } from "class-validator" -import { NextFunction, Request, Response } from "express" -import { omit } from "lodash" -import { RequestQueryFields } from "@medusajs/types" -import { BaseEntity } from "../../interfaces" -import { FindConfig, QueryConfig } from "../../types/common" -import { ClassConstructor } from "../../types/global" -import { removeUndefinedProperties } from "../../utils" -import { - prepareListQuery, - prepareRetrieveQuery, -} from "../../utils/get-query-config" -import { validator } from "../../utils/validator" -import { default as normalizeQuery } from "./normalized-query" - -/** - * Middleware that transform the query input for the admin end points - * @param plainToClass - * @param queryConfig - * @param config - */ -export function transformQuery< - T extends RequestQueryFields, - TEntity extends BaseEntity ->( - plainToClass: ClassConstructor, - queryConfig: QueryConfig = {}, - config: ValidatorOptions = {} -): (req: Request, res: Response, next: NextFunction) => Promise { - return async (req: Request, res: Response, next: NextFunction) => { - try { - normalizeQuery()(req, res, () => void 0) - const validated: T = await validator>( - plainToClass, - req.query, - config - ) - - req.validatedQuery = validated - req.filterableFields = getFilterableFields(validated) - - attachListOrRetrieveConfig(req, { - ...queryConfig, - allowed: - req.allowed ?? queryConfig.allowed ?? queryConfig.allowedFields ?? [], - }) - - /** - * TODO: the bellow allowedProperties should probably need to be reworked which would create breaking changes everywhere - * cleanResponseData is used. It is in fact, what is expected to be returned which IMO - * should correspond to the select/relations - * - * Kept it as it is to maintain backward compatibility - */ - const queryConfigRes = !queryConfig.isList - ? req.retrieveConfig - : req.listConfig - const includesRelations = Object.keys(req.includes ?? {}) - req.allowedProperties = Array.from( - new Set( - [ - ...(req.validatedQuery.fields - ? queryConfigRes.select ?? [] - : req.allowed ?? - queryConfig.allowed ?? - queryConfig.allowedFields ?? - (queryConfig.defaults as string[]) ?? - queryConfig.defaultFields ?? - []), - ...(req.validatedQuery.expand || includesRelations.length - ? [...(validated.expand?.split(",") || []), ...includesRelations] // For backward compatibility, the includes takes precedence over the relations for the returnable fields - : queryConfig.allowedRelations ?? queryConfigRes.relations ?? []), // For backward compatibility, the allowedRelations takes precedence over the relations for the returnable fields - ].filter(Boolean) - ) - ) - - next() - } catch (e) { - next(e) - } - } -} - -/** - * Middleware that transform the query input for the store endpoints - * @param plainToClass - * @param queryConfig - * @param config - * - * @deprecated use `transformQuery` instead - */ -export function transformStoreQuery< - T extends RequestQueryFields, - TEntity extends BaseEntity ->( - plainToClass: ClassConstructor, - queryConfig?: QueryConfig, - config: ValidatorOptions = {} -): (req: Request, res: Response, next: NextFunction) => Promise { - return transformQuery(plainToClass, queryConfig, config) -} - -/** - * Omit the non filterable config from the validated object - * @param obj - */ -function getFilterableFields(obj: T): T { - const result = omit(obj, [ - "limit", - "offset", - /** - * @deprecated - */ - "expand", - "fields", - "order", - ]) as T - return removeUndefinedProperties(result) -} - -/** - * build and attach the `retrieveConfig` or `listConfig` and remoteQueryConfig to the request object - * @param req - * @param queryConfig - */ -function attachListOrRetrieveConfig( - req: Request, - queryConfig: QueryConfig = {} -) { - const validated = req.validatedQuery - const config = queryConfig.isList - ? prepareListQuery(validated, queryConfig) - : prepareRetrieveQuery(validated, queryConfig) - - req.listConfig = ("listConfig" in config && - config.listConfig) as FindConfig - req.retrieveConfig = ("retrieveConfig" in config && - config.retrieveConfig) as FindConfig - req.remoteQueryConfig = config.remoteQueryConfig -} diff --git a/packages/medusa/src/utils/omit-relation-if-exists.ts b/packages/medusa/src/utils/omit-relation-if-exists.ts deleted file mode 100644 index 938b43fdbc..0000000000 --- a/packages/medusa/src/utils/omit-relation-if-exists.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * - * @param relations relations from which a relation should be removed - * @param relation relation to be removed - * @returns tuple containing the new relations and a boolean indicating whether the relation was found in the relations array - */ -export const omitRelationIfExists = ( - relations: string[], - relation: string -): [string[], boolean] => { - const filteredRelations = relations.filter((rel) => rel !== relation) - const includesRelation = relations.length !== filteredRelations.length - - return [relations, includesRelation] -} diff --git a/packages/medusa/src/utils/remote-query-fetch-data.ts b/packages/medusa/src/utils/remote-query-fetch-data.ts index 5bf63c65ee..0d0897e49f 100644 --- a/packages/medusa/src/utils/remote-query-fetch-data.ts +++ b/packages/medusa/src/utils/remote-query-fetch-data.ts @@ -60,8 +60,6 @@ export function remoteQueryFetchData(container: MedusaContainer) { } const expandRelations = Object.keys(expand.expands ?? {}) - // filter out links from relations because TypeORM will throw if the relation doesn't exist - options.relations = options.relations.filter( (relation) => !expandRelations.some((ex) => relation.startsWith(ex)) ) diff --git a/packages/medusa/src/utils/repository.ts b/packages/medusa/src/utils/repository.ts deleted file mode 100644 index f07fb8e53f..0000000000 --- a/packages/medusa/src/utils/repository.ts +++ /dev/null @@ -1,381 +0,0 @@ -import { promiseAll } from "@medusajs/utils" -import { flatten, groupBy, map, merge } from "lodash" -import { - EntityMetadata, - ObjectLiteral, - Repository, - SelectQueryBuilder, -} from "typeorm" -import { ExtendedFindConfig } from "../types/common" - -// Regex matches all '.' except the rightmost -export const positiveLookaheadDotReplacer = new RegExp(/\.(?=[^.]*\.)/, "g") -// Replace all '.' with '__' to avoid typeorm's automatic aliasing -export const dotReplacer = new RegExp(/\./, "g") - -/** - * Custom query entity, it is part of the creation of a custom findWithRelationsAndCount needs. - * Allow to query the relations for the specified entity ids - * - * @param repository - * @param entityIds - * @param groupedRelations - * @param withDeleted - * @param select - * @param customJoinBuilders - */ -export async function queryEntityWithIds({ - repository, - entityIds, - groupedRelations, - withDeleted = false, - select = [], - customJoinBuilders = [], -}: { - repository: Repository - entityIds: string[] - groupedRelations: { [toplevel: string]: string[] } - withDeleted?: boolean - select?: (keyof T)[] - customJoinBuilders?: (( - qb: SelectQueryBuilder, - alias: string, - toplevel: string - ) => false | undefined)[] -}): Promise { - const alias = repository.metadata.name.toLowerCase() - return await promiseAll( - Object.entries(groupedRelations).map( - async ([toplevel, topLevelRelations]) => { - let querybuilder = repository.createQueryBuilder(alias) - - if (select?.length) { - querybuilder.select( - (select as string[]) - .filter(function (s) { - return s.startsWith(toplevel) || !s.includes(".") - }) - .map((column) => { - // In case the column is the toplevel relation, we need to replace the dot with a double underscore if it also contains top level relations - if (column.includes(toplevel)) { - return topLevelRelations.some((rel) => column.includes(rel)) - ? column.replace(positiveLookaheadDotReplacer, "__") - : column - } - return `${alias}.${column}` - }) - ) - } - - let shouldAttachDefault: boolean | undefined = true - for (const customJoinBuilder of customJoinBuilders) { - const result = customJoinBuilder(querybuilder, alias, toplevel) - if (result === undefined) { - continue - } - - shouldAttachDefault = shouldAttachDefault && result - } - - if (shouldAttachDefault) { - const regexp = new RegExp(`^${toplevel}\\.\\w+$`) - const joinMethod = (select as string[]).filter( - (key) => !!key.match(regexp) - ).length - ? "leftJoin" - : "leftJoinAndSelect" - - querybuilder = querybuilder[joinMethod]( - `${alias}.${toplevel}`, - toplevel - ) - } - - for (const rel of topLevelRelations) { - const [_, rest] = rel.split(".") - if (!rest) { - continue - } - - const regexp = new RegExp(`^${rel}\\.\\w+$`) - const joinMethod = (select as string[]).filter( - (key) => !!key.match(regexp) - ).length - ? "leftJoin" - : "leftJoinAndSelect" - - querybuilder = querybuilder[joinMethod]( - rel.replace(positiveLookaheadDotReplacer, "__"), - rel.replace(dotReplacer, "__") - ) - } - - querybuilder = querybuilder.where(`${alias}.id IN (:...entitiesIds)`, { - entitiesIds: entityIds, - }) - - if (withDeleted) { - querybuilder.withDeleted() - } - - return querybuilder.getMany() - } - ) - ).then(flatten) -} - -/** - * Custom query entity without relations, it is part of the creation of a custom findWithRelationsAndCount needs. - * Allow to query the entities without taking into account the relations. The relations will be queried separately - * using the queryEntityWithIds util - * - * @param repository - * @param optionsWithoutRelations - * @param shouldCount - * @param customJoinBuilders - */ -export async function queryEntityWithoutRelations({ - repository, - optionsWithoutRelations, - shouldCount = false, - customJoinBuilders = [], -}: { - repository: Repository - optionsWithoutRelations: Omit, "relations"> - shouldCount: boolean - customJoinBuilders: (( - qb: SelectQueryBuilder, - alias: string - ) => Promise<{ relation: string; preventOrderJoin: boolean } | void>)[] -}): Promise<[T[], number]> { - const alias = repository.metadata.name.toLowerCase() - - const qb = repository.createQueryBuilder(alias).select([`${alias}.id`]) - - if (optionsWithoutRelations.where) { - qb.where(optionsWithoutRelations.where) - } - - const shouldJoins: { relation: string; shouldJoin: boolean }[] = [] - for (const customJoinBuilder of customJoinBuilders) { - const result = await customJoinBuilder(qb, alias) - if (result) { - shouldJoins.push({ - relation: result.relation, - shouldJoin: !result.preventOrderJoin, - }) - } - } - - applyOrdering({ - repository, - order: (optionsWithoutRelations.order as any) ?? {}, - qb, - alias, - shouldJoin: (relationToJoin) => { - return shouldJoins.every( - ({ relation, shouldJoin }) => - relation !== relationToJoin || - (relation === relationToJoin && shouldJoin) - ) - }, - }) - - if (optionsWithoutRelations.withDeleted) { - qb.withDeleted() - } - - /* - * Deduplicate tuples for join + ordering (e.g. variants.prices.amount) since typeorm doesnt - * know how to manage it by itself - */ - const expressionMapAllOrderBys = qb.expressionMap.allOrderBys - if ( - expressionMapAllOrderBys && - Object.keys(expressionMapAllOrderBys).length - ) { - const orderBysString = Object.keys(expressionMapAllOrderBys) - .map((column) => { - return `${column} ${expressionMapAllOrderBys[column]}` - }) - .join(", ") - - qb.addSelect( - `row_number() OVER (PARTITION BY ${alias}.id ORDER BY ${orderBysString}) AS rownum` - ) - } else { - qb.addSelect(`1 AS rownum`) - } - - /* - * In typeorm SelectQueryBuilder, the orderBy is removed from the original query when there is pagination - * and join involved together. - * - * This workaround allows us to include the order as part of the original query (including joins) before - * selecting the distinct ids of the main alias entity. The distinct ids deduplication - * is managed by the rownum column added to the select below. - * - * see: node_modules/typeorm/query-builder/SelectQueryBuilder.js(1973) - */ - const outerQb = new SelectQueryBuilder(qb.connection, (qb as any).queryRunner) - .select(`${qb.escape(`${alias}_id`)}`) - .from(`(${qb.getQuery()})`, alias) - .where(`${alias}.rownum = 1`) - .setParameters(qb.getParameters()) - .setNativeParameters(qb.expressionMap.nativeParameters) - .offset(optionsWithoutRelations.skip) - .limit(optionsWithoutRelations.take) - - const mapToEntities = (array: any) => { - return array.map((rawProduct) => ({ - id: rawProduct[`${alias}_id`], - })) as unknown as T[] - } - - let entities: T[] - let count = 0 - if (shouldCount) { - const outerQbCount = new SelectQueryBuilder( - qb.connection, - (qb as any).queryRunner - ) - .select(`COUNT(1)`, `count`) - .from(`(${qb.getQuery()})`, alias) - .where(`${alias}.rownum = 1`) - .setParameters(qb.getParameters()) - .setNativeParameters(qb.expressionMap.nativeParameters) - .orderBy() - .groupBy() - .offset(undefined) - .limit(undefined) - .skip(undefined) - .take(undefined) - - const result = await promiseAll([ - outerQb.getRawMany(), - outerQbCount.getRawOne(), - ]) - - entities = mapToEntities(result[0]) - count = Number(result[1].count) - } else { - const result = await outerQb.getRawMany() - entities = mapToEntities(result) - } - - return [entities, count] -} - -/** - * Grouped the relation to the top level entity - * @param relations - */ -export function getGroupedRelations(relations: string[]): { - [toplevel: string]: string[] -} { - const groupedRelations: { [toplevel: string]: string[] } = {} - for (const rel of relations) { - const [topLevel] = rel.split(".") - if (groupedRelations[topLevel]) { - groupedRelations[topLevel].push(rel) - } else { - groupedRelations[topLevel] = [rel] - } - } - - return groupedRelations -} - -/** - * Merged the entities and relations that composed by the result of queryEntityWithIds and queryEntityWithoutRelations - * call - * @param entitiesAndRelations - */ -export function mergeEntitiesWithRelations( - entitiesAndRelations: Array> -): T[] { - const entitiesAndRelationsById = groupBy(entitiesAndRelations, "id") - return map(entitiesAndRelationsById, (entityAndRelations) => - merge({}, ...entityAndRelations) - ) -} - -/** - * Apply the appropriate order depending on the requirements - * @param repository - * @param order The field on which to apply the order (e.g { "variants.prices.amount": "DESC" }) - * @param qb - * @param alias - * @param shouldJoin In case a join is already applied elsewhere and therefore you want to avoid to re joining the data in that case you can return false for specific relations - */ -export function applyOrdering({ - repository, - order, - qb, - alias, - shouldJoin, -}: { - repository: Repository - order: Record - qb: SelectQueryBuilder - alias: string - shouldJoin: (relation: string) => boolean -}) { - const toSelect: string[] = [] - - const parsed = Object.entries(order).reduce( - (acc, [orderPath, orderDirection]) => { - // If the orderPath (e.g variants.prices.amount) includes a point it means that it is to access - // a child relation of an unknown depth - if (orderPath.includes(".")) { - // We are spliting the path and separating the relations from the property to order. (e.g relations ["variants", "prices"] and property "amount" - const relationsToJoin = orderPath.split(".") - const propToOrder = relationsToJoin.pop() - - // For each relation we will retrieve the metadata in order to use the right property name from the relation registered in the entity. - // Each time we will return the child (i.e the relation) and the inverse metadata (corresponding to the child metadata from the parent point of view) - // In order for the next child to know its parent - relationsToJoin.reduce( - ([parent, parentMetadata], child) => { - // Find the relation metadata from the parent entity - const relationMetadata = ( - parentMetadata as EntityMetadata - ).relations.find( - (relationMetadata) => relationMetadata.propertyName === child - ) - - // The consumer can refuse to apply a join on a relation if the join has already been applied before calling this util - const shouldApplyJoin = shouldJoin(child) - if (shouldApplyJoin) { - qb.leftJoin(`${parent}.${relationMetadata!.propertyPath}`, child) - } - - // Return the child relation to be the parent for the next one, as well as the metadata corresponding the child in order - // to find the next relation metadata for the next child - return [child, relationMetadata!.inverseEntityMetadata] - }, - [alias, repository.metadata] - ) - - // The key for variants.prices.amount will be "prices.amount" since we are ordering on the join added to its parent "variants" in this example - const key = `${ - relationsToJoin[relationsToJoin.length - 1] - }.${propToOrder}` - acc[key] = orderDirection - toSelect.push(key) - return acc - } - - const key = `${alias}.${orderPath}` - // Prevent ambiguous column error when top level entity id is ordered - if (orderPath !== "id") { - toSelect.push(key) - } - acc[key] = orderDirection - return acc - }, - {} - ) - qb.addSelect(toSelect) - qb.orderBy(parsed) -} diff --git a/packages/medusa/src/utils/transformers/tree.ts b/packages/medusa/src/utils/transformers/tree.ts deleted file mode 100644 index 81acd55277..0000000000 --- a/packages/medusa/src/utils/transformers/tree.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { pick } from "lodash" -import { isDefined } from "medusa-core-utils" -import { filter, isNull } from "lodash" - -// TODO: When we implement custom queries for tree paths in medusa, remove the transformer -// Adding this here since typeorm tree repo doesn't allow configs to be passed -// onto its children nodes. As an alternative, we are transforming the data post query. -export function transformTreeNodesWithConfig( - object, - config, - scope = {}, - isParentNode = false -) { - const selects = (config.select || []) as string[] - const relations = (config.relations || []) as string[] - const selectsAndRelations = selects.concat(relations) - - for (const [key, value] of Object.entries(scope)) { - const modelValue = object[key] - - if (isDefined(modelValue) && modelValue !== value) { - return null - } - } - - if (object.parent_category) { - object.parent_category = transformTreeNodesWithConfig( - object.parent_category, - config, - scope, - true - ) - } - - if (!isParentNode && (object.category_children || []).length > 0) { - object.category_children = object.category_children.map((child) => { - return transformTreeNodesWithConfig(child, config, scope) - }) - - object.category_children = filter( - object.category_children, - (el) => !isNull(el) - ) - } - - return pick(object, selectsAndRelations) -} diff --git a/packages/medusa/src/utils/validate-id.ts b/packages/medusa/src/utils/validate-id.ts deleted file mode 100644 index 1d0edb3568..0000000000 --- a/packages/medusa/src/utils/validate-id.ts +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Confirms whether a given raw id is valid. Fails if the provided - * id is null or undefined. The validate function takes an optional config - * param, to support checking id prefix and length. - * @param rawId - the id to validate. - * @param config - optional config - * @returns the rawId given that nothing failed - */ -import { MedusaError } from "medusa-core-utils/dist" - -export function validateId( - rawId: string, - config: { prefix?: string; length?: number } = {} -): string { - const { prefix, length } = config - if (!rawId) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `Failed to validate id: ${rawId}` - ) - } - - if (prefix || length) { - const [pre, rand] = rawId.split("_") - if (prefix && pre !== prefix) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `The provided id: ${rawId} does not adhere to prefix constraint: ${prefix}` - ) - } - - if (length && length !== rand.length) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `The provided id: ${rawId} does not adhere to length constraint: ${length}` - ) - } - } - - return rawId -} diff --git a/packages/medusa/src/utils/validator.ts b/packages/medusa/src/utils/validator.ts deleted file mode 100644 index a2030e8d7b..0000000000 --- a/packages/medusa/src/utils/validator.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { ClassConstructor, plainToInstance } from "class-transformer" -import { validate, ValidationError, ValidatorOptions } from "class-validator" -import { MedusaError } from "medusa-core-utils" -import { Constructor } from "@medusajs/types" - -const extendedValidators: Map> = new Map() - -/** - * When overriding a validator, you can register it to be used instead of the original one. - * For example, the place where you are overriding the core validator, you can call this function - * @example - * ```ts - * // /src/api/routes/admin/products/create-product.ts - * import { registerOverriddenValidators } from "@medusajs/medusa" - * import { AdminPostProductsReq as MedusaAdminPostProductsReq } from "@medusajs/medusa/dist/api/routes/admin/products/create-product" - * import { IsString } from "class-validator" - * - * class AdminPostProductsReq extends MedusaAdminPostProductsReq { - * @IsString() - * test: string - * } - * - * registerOverriddenValidators(AdminPostProductsReq) - * ``` - * @param extendedValidator - */ -export function registerOverriddenValidators( - extendedValidator: Constructor -): void { - extendedValidators.set(extendedValidator.name, extendedValidator) -} - -const reduceErrorMessages = (errs: ValidationError[]): string[] => { - return errs.reduce((acc: string[], next) => { - if (next.constraints) { - for (const [_, msg] of Object.entries(next.constraints)) { - acc.push(msg) - } - } - - if (next.children) { - acc.push(...reduceErrorMessages(next.children)) - } - return acc - }, []) -} - -export async function validator( - typedClass: ClassConstructor, - plain: V, - config: ValidatorOptions = {} -): Promise { - typedClass = extendedValidators.get(typedClass.name) ?? typedClass - - const toValidate = plainToInstance(typedClass, plain) - // @ts-ignore - const errors = await validate(toValidate, { - whitelist: true, - forbidNonWhitelisted: true, - ...config, - }) - - const errorMessages = reduceErrorMessages(errors) - - if (errors?.length) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - errorMessages.join(", ") - ) - } - - return toValidate -} diff --git a/packages/medusa/src/utils/validators/date-transform.ts b/packages/medusa/src/utils/validators/date-transform.ts deleted file mode 100644 index 6e64392f90..0000000000 --- a/packages/medusa/src/utils/validators/date-transform.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { isDate } from "@medusajs/utils" - -export const transformDate = ({ value }): Date => { - return isDate(value) ? new Date(value) : new Date(Number(value) * 1000) -} - -export const transformOptionalDate = ({ value }) => { - return !isDate(value) ? value : transformDate({ value }) -} diff --git a/packages/medusa/src/utils/validators/greater-than.ts b/packages/medusa/src/utils/validators/greater-than.ts deleted file mode 100644 index ae8fba3300..0000000000 --- a/packages/medusa/src/utils/validators/greater-than.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { - registerDecorator, - ValidationArguments, - ValidationOptions, - isDefined, -} from "class-validator" -import { MedusaError } from "medusa-core-utils" - -export function IsGreaterThan( - property: string, - validationOptions?: ValidationOptions -) { - return function (object: any, propertyName: string): void { - registerDecorator({ - name: "IsGreaterThan", - target: object.constructor, - propertyName: propertyName, - constraints: [property], - options: validationOptions, - validator: { - validate(value: any, args: ValidationArguments) { - const [relatedPropertyName] = args.constraints - const relatedValue = args.object[relatedPropertyName] - return relatedValue ? value > relatedValue : isDefined(value) - }, - defaultMessage(args?: ValidationArguments): string { - return `"${propertyName}" must be greater than ${JSON.stringify( - args?.constraints[0] - )}` - }, - }, - }) - } -} diff --git a/packages/medusa/src/utils/validators/is-boolean.ts b/packages/medusa/src/utils/validators/is-boolean.ts deleted file mode 100644 index cc767dc1df..0000000000 --- a/packages/medusa/src/utils/validators/is-boolean.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Util function defining the transformation of booleans when part of req.query -// e.g. /admin/shipping-options?is_return=false -> false -// -// We've previously been using @Type(() => Boolean), but this will always return true for strings. -// See https://github.com/typestack/class-transformer/issues/676 -// and https://github.com/typestack/class-transformer/issues/306 -// -// The solution here is stolen from: https://github.com/typestack/class-transformer/issues/676#issuecomment-822699830 -export const optionalBooleanMapper = new Map([ - ["undefined", undefined], - ["null", null], - ["true", true], - ["false", false], -]) diff --git a/packages/medusa/src/utils/validators/is-type.ts b/packages/medusa/src/utils/validators/is-type.ts deleted file mode 100644 index 95916bcad4..0000000000 --- a/packages/medusa/src/utils/validators/is-type.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { - isArray, - isNumber, - isString, - registerDecorator, - ValidationArguments, - ValidationOptions, -} from "class-validator" -import { isDate } from "lodash" -import { MedusaError } from "medusa-core-utils" -import { validator } from "../validator" -import { promiseAll } from "@medusajs/utils" - -async function typeValidator( - typedClass: any, - plain: unknown -): Promise { - switch (typedClass) { - case String: - if (!isString(plain)) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `String validation failed: ${plain} is not a string` - ) - } - return true - case Number: - if (!isNumber(Number(plain))) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `Number validation failed: ${plain} is not a number` - ) - } - return true - case Date: - if (!isDate(new Date(plain as string))) { - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - `Date validation failed: ${plain} is not a date` - ) - } - return true - default: - if (isArray(typedClass) && isArray(plain)) { - const errors: Map = new Map() - const result = ( - await promiseAll( - (plain as any[]).map( - async (p) => - await typeValidator(typedClass[0], p).catch((e) => { - errors.set(typedClass[0].name, e.message.split(",")) - return false - }) - ) - ) - ).some(Boolean) - - if (result) { - return true - } - - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - Object.fromEntries(errors.entries()) - ) - } - return ( - (await validator(typedClass, plain).then(() => true)) && - typeof plain === "object" - ) - } -} - -export function IsType(types: any[], validationOptions?: ValidationOptions) { - return function (object: Object, propertyName: string): void { - registerDecorator({ - name: "IsType", - target: object.constructor, - propertyName: propertyName, - options: validationOptions, - validator: { - async validate(value: unknown, args: ValidationArguments) { - const errors: Map = new Map() - const results = await promiseAll( - types.map( - async (v) => - await typeValidator(v, value).catch((e) => { - errors.set(v.name, e.message.split(",").filter(Boolean)) - return false - }) - ) - ) - - if (results.some(Boolean)) { - return true - } - - throw new MedusaError( - MedusaError.Types.INVALID_DATA, - JSON.stringify({ - message: `${args.property} must be one of: ${types.map( - (t) => `${t.name || (Array.isArray(t) ? t[0]?.name : "")}` - )}`, - details: Object.fromEntries(errors.entries()), - }) - ) - }, - - defaultMessage(validationArguments?: ValidationArguments) { - const names = types.map( - (t) => t.name || (isArray(t) ? `${t[0].name}[]` : "") - ) - return `${validationArguments?.property} must be one of ${names - .join(", ") - .replace(/, ([^,]*)$/, " or $1")}` - }, - }, - }) - } -} diff --git a/packages/medusa/src/utils/validators/iso8601-duration.ts b/packages/medusa/src/utils/validators/iso8601-duration.ts deleted file mode 100644 index 09f44a32d5..0000000000 --- a/packages/medusa/src/utils/validators/iso8601-duration.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { - registerDecorator, - ValidationArguments, - ValidationOptions, -} from "class-validator" - -export function IsISO8601Duration(validationOptions?: ValidationOptions) { - return function (object: any, propertyName: string): void { - registerDecorator({ - name: "IsGreaterThan", - target: object.constructor, - propertyName: propertyName, - options: validationOptions, - validator: { - validate(value: any, args: ValidationArguments) { - const isoDurationRegex = - /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/ - return isoDurationRegex.test(value) - }, - defaultMessage(args?: ValidationArguments): string { - return `"${propertyName}" must be a valid ISO 8601 duration` - }, - }, - }) - } -} diff --git a/yarn.lock b/yarn.lock index c492843c68..67bd6eafe6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5393,17 +5393,13 @@ __metadata: awilix: ^8.0.0 body-parser: ^1.19.0 boxen: ^5.0.1 - bullmq: ^5.4.2 chokidar: ^3.4.2 - class-transformer: ^0.5.1 - class-validator: ^0.14.0 compression: ^1.7.4 connect-redis: ^5.0.0 cookie-parser: ^1.4.6 core-js: ^3.6.5 cors: ^2.8.5 cross-env: ^5.2.1 - cross-spawn: ^7.0.3 dotenv: ^16.4.5 express: ^4.18.2 express-session: ^1.17.3 @@ -5411,7 +5407,6 @@ __metadata: glob: ^7.1.6 ioredis: ^5.2.5 ioredis-mock: 8.4.0 - iso8601-duration: ^1.3.0 jest: ^25.5.4 jsonwebtoken: ^9.0.0 lodash: ^4.17.21 @@ -5422,30 +5417,23 @@ __metadata: morgan: ^1.9.1 multer: ^1.4.5-lts.1 node-schedule: ^2.1.1 - papaparse: 5.3.2 passport: ^0.6.0 passport-custom: ^1.1.1 passport-jwt: ^4.0.1 passport-local: ^1.0.0 pg: ^8.11.2 qs: ^6.11.2 - randomatic: ^3.1.1 reflect-metadata: ^0.1.13 regenerator-runtime: ^0.13.11 request-ip: ^3.3.0 rimraf: ^5.0.1 - scrypt-kdf: ^2.0.1 supertest: ^4.0.2 ts-jest: ^25.5.1 - typeorm: ^0.3.16 typescript: ^4.4.4 - ulid: ^2.3.0 uuid: ^9.0.0 - winston: ^3.8.2 zod: 3.22.4 peerDependencies: medusa-interfaces: ^1.3.7 - typeorm: ^0.3.16 bin: medusa: ./cli.js languageName: unknown @@ -11562,7 +11550,7 @@ __metadata: languageName: node linkType: hard -"@types/validator@npm:^13.11.8, @types/validator@npm:^13.7.17": +"@types/validator@npm:^13.7.17": version: 13.11.9 resolution: "@types/validator@npm:13.11.9" checksum: 856ebfcfe25d6c91a90235e0eb27302a737832530898195bbfb265da52ae7fe6d68f684942574f8818d3c262cae7a1de99f145dac73fc57217933af1bfc199cb @@ -14112,13 +14100,6 @@ __metadata: languageName: node linkType: hard -"class-transformer@npm:^0.5.1": - version: 0.5.1 - resolution: "class-transformer@npm:0.5.1" - checksum: 19809914e51c6db42c036166839906420bb60367df14e15f49c45c8c1231bf25ae661ebe94736ee29cc688b77101ef851a8acca299375cc52fc141b64acde18a - languageName: node - linkType: hard - "class-utils@npm:^0.3.5": version: 0.3.6 resolution: "class-utils@npm:0.3.6" @@ -14131,17 +14112,6 @@ __metadata: languageName: node linkType: hard -"class-validator@npm:^0.14.0": - version: 0.14.1 - resolution: "class-validator@npm:0.14.1" - dependencies: - "@types/validator": ^13.11.8 - libphonenumber-js: ^1.10.53 - validator: ^13.9.0 - checksum: 946e914e47548b5081449c720ea6a4877bac63dc960e14fca4b990b56e64efe3802d12f07ec22d6420c290245b72ea2d646939239f2a3b597794e6c4c2a4f2ae - languageName: node - linkType: hard - "classnames@npm:^2.3.2": version: 2.5.1 resolution: "classnames@npm:2.5.1" @@ -20358,13 +20328,6 @@ __metadata: languageName: node linkType: hard -"iso8601-duration@npm:^1.3.0": - version: 1.3.0 - resolution: "iso8601-duration@npm:1.3.0" - checksum: a848f4c3caca38c7a3a7ee6708f0da8ab00499b1ba4b06de95ccccecc4d1c45f60b0725b1bbd6cc36f47b59b1fb18e020b36c06368e1f908a05271076df11e05 - languageName: node - linkType: hard - "isobject@npm:^2.0.0": version: 2.1.0 resolution: "isobject@npm:2.1.0" @@ -22697,13 +22660,6 @@ __metadata: languageName: node linkType: hard -"libphonenumber-js@npm:^1.10.53": - version: 1.11.0 - resolution: "libphonenumber-js@npm:1.11.0" - checksum: c9230aa2353372dbe277768a4a2b74a10d241d6013d8133ea4260fab201e7ac2fb1751460f1d8660fff7a493eeaf208d9844ebea70d997cea70bd9a3fd78041d - languageName: node - linkType: hard - "lilconfig@npm:^2.0.3, lilconfig@npm:^2.0.5, lilconfig@npm:^2.1.0": version: 2.1.0 resolution: "lilconfig@npm:2.1.0" @@ -25280,13 +25236,6 @@ __metadata: languageName: node linkType: hard -"papaparse@npm:5.3.2": - version: 5.3.2 - resolution: "papaparse@npm:5.3.2" - checksum: fdc50cae03fdf94fa2b78da86fe18fa53ca36753ccd6619ca7f738df097cdd2cbf572a9c048a72c05118db7cf0ccb25d574f39a720c5e1a8d8c6903b0fd30765 - languageName: node - linkType: hard - "parent-module@npm:^1.0.0": version: 1.0.1 resolution: "parent-module@npm:1.0.1"