// apps/backend/src/migration-scripts/us-region.ts // From https://exe.dev/deploy/medusa: a United States region in dollars next // to the starter's Europe region, with manual payment, taxes, and the same // two shipping options, so the storefront can open on /us. Medusa runs // migration scripts once each, in filename order, so this runs right after // the starter's initial-data-seed and region-store-policies. import { MedusaContainer } from '@medusajs/framework' import { ContainerRegistrationKeys, Modules } from '@medusajs/framework/utils' import { createRegionsWorkflow, createShippingOptionsWorkflow, createTaxRegionsWorkflow, } from '@medusajs/medusa/core-flows' import { DEFAULT_REGION_STORE_POLICIES } from '../lib/region-store-policies' export default async function usRegion({ container }: { container: MedusaContainer }) { const logger = container.resolve(ContainerRegistrationKeys.LOGGER) const query = container.resolve(ContainerRegistrationKeys.QUERY) const fulfillment = container.resolve(Modules.FULFILLMENT) const { data: regions } = await query.graph({ entity: 'region', fields: ['id', 'countries.iso_2'], }) if (regions.some((r) => r.countries?.some((c) => c?.iso_2 === 'us'))) { logger.info('A region for the United States exists already.') return } const { result: [region], } = await createRegionsWorkflow(container).run({ input: { regions: [ { name: 'United States', currency_code: 'usd', countries: ['us'], payment_providers: ['pp_system_default'], metadata: DEFAULT_REGION_STORE_POLICIES, }, ], }, }) await createTaxRegionsWorkflow(container).run({ input: [{ country_code: 'us', provider_id: 'tp_system' }], }) // Ship to the US from the starter's warehouse, with its two options. const [set] = await fulfillment.listFulfillmentSets({ type: 'shipping' }) const { data: profiles } = await query.graph({ entity: 'shipping_profile', fields: ['id'], }) if (!set || !profiles.length) { logger.warn('No fulfillment set or shipping profile: add US shipping in the admin.') return } const zone = await fulfillment.createServiceZones({ name: 'United States', fulfillment_set_id: set.id, geo_zones: [{ type: 'country', country_code: 'us' }], }) const option = (name: string, label: string, code: string, description: string) => ({ name, price_type: 'flat' as const, provider_id: 'manual_manual', service_zone_id: zone.id, shipping_profile_id: profiles[0].id, type: { label, code, description }, prices: [ { currency_code: 'usd', amount: 10 }, { region_id: region.id, amount: 10 }, ], rules: [ { attribute: 'enabled_in_store', value: 'true', operator: 'eq' as const }, { attribute: 'is_return', value: 'false', operator: 'eq' as const }, ], }) await createShippingOptionsWorkflow(container).run({ input: [ option('Standard Shipping', 'Standard', 'standard', 'Ship in 2-3 days.'), option('Express Shipping', 'Express', 'express', 'Ship in 24 hours.'), ], }) logger.info('Added the United States region.') }