Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

19.4 KB
Raw Blame
import { writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
  FIXTURE_BOGUS_GATEWAY,
  FIXTURE_BOGUS_ORDER_EMAIL,
  FIXTURE_BOGUS_TRANSACTION_ID,
  FIXTURE_BULK_CATEGORY,
  FIXTURE_BULK_CATEGORY_PERMALINK,
  FIXTURE_BULK_CHANNEL_CODE,
  FIXTURE_BULK_CHANNEL_NAME,
  FIXTURE_BULK_PRODUCT_A,
  FIXTURE_BULK_PRODUCT_B,
  FIXTURE_BULK_PRODUCT_C,
  FIXTURE_BULK_PRODUCT_D,
  FIXTURE_BULK_PRODUCT_E,
  FIXTURE_BULK_PRODUCT_F,
  FIXTURE_BULK_PRODUCT_G,
  FIXTURE_BULK_PRODUCT_H,
  FIXTURE_BULK_PRODUCT_I,
  FIXTURE_BULK_PRODUCT_J,
  FIXTURE_BULK_PRODUCT_K,
  FIXTURE_BULK_PRODUCT_L,
  FIXTURE_BULK_PRODUCT_M,
  FIXTURE_BULK_PRODUCT_N,
  FIXTURE_INVENTORY_PRODUCT,
  FIXTURE_INVENTORY_RESERVED,
  FIXTURE_INVENTORY_SKU,
  FIXTURE_LEDGER_OWED_AMOUNT,
  FIXTURE_LEDGER_PAYOUT_AMOUNT,
  FIXTURE_LEDGER_SELLER,
  FIXTURE_PANEL_SELLER,
  FIXTURE_PROMO_CUSTOMER_EMAIL,
  FIXTURE_PROMO_CUSTOMER_FIRST_NAME,
  FIXTURE_PROMO_CUSTOMER_FULL_NAME,
  FIXTURE_PROMO_CUSTOMER_GROUP,
  FIXTURE_PROMO_PRODUCT,
  FIXTURE_PROMO_SKU,
  FIXTURE_PROMO_TAXON,
  FIXTURE_PROMO_TAXON_PERMALINK,
  FIXTURE_SELLER_PASSWORD,
  FIXTURE_SELLER_USER_EMAIL,
  FIXTURE_SELLER_WRITER_EMAIL,
  FIXTURE_SUPPLIER,
  FIXTURE_TRANSFER_DESTINATION,
  FIXTURE_TRANSFER_PRODUCT,
  FIXTURE_TRANSFER_SKU,
  FIXTURE_TRANSFER_SOURCE,
} from './helpers'
import {
  ASYNC_JOBS_INITIALIZER,
  CREDENTIALS_FILE,
  RAILS_PID_FILE,
  SLOT_PROBES_INITIALIZER,
  TEST_INTEGRATION_INITIALIZER,
} from './paths'
import { API_GEM_DIR, rmIfExists, runRailsBootstrap, startRails } from './rails'

const PORT = process.env.E2E_RAILS_PORT || '3010'
// A database of its own, so the seeded data left behind after a run never
// reaches the API gem's RSpec suite, which shares the dummy app.
const TEST_SQLITE = resolve(API_GEM_DIR, 'spec/dummy/db/spree_test_e2e.sqlite3')

const RAILS_ENV = {
  ...process.env,
  RAILS_ENV: 'test',
  PORT,
  DASHBOARD_E2E: '1',
  DATABASE_URL: `sqlite3:${TEST_SQLITE}`,
}

// Customer's last name is derived from the full name so the seeder and the
// matching `full_name` assertion in promotions.spec stay in sync.
const FIXTURE_PROMO_CUSTOMER_LAST_NAME = FIXTURE_PROMO_CUSTOMER_FULL_NAME.replace(
  `${FIXTURE_PROMO_CUSTOMER_FIRST_NAME} `,
  '',
)

const BOOTSTRAP_RUBY = [
  "load Rails.root.join('db', 'schema.rb').to_s",
  'Spree::Seeds::All.call',
  'require "json"',
  's = Spree::Store.default',
  'admin = Spree.admin_user_class.first || Spree.admin_user_class.create!(email: "[email protected]", password: "spree123", password_confirmation: "spree123")',
  'admin.update!(password: "spree123", password_confirmation: "spree123")',
  's.add_user(admin, Spree::Role.default_admin_role(s)) unless s.role_users.exists?(user: admin)',
  // Idempotent fixtures for promotion rule/action editor specs. Customer
  // groups have no admin UI yet, so this is the only path to seed one.
  // Looked up by permalink, not name: category names are not unique, so a name
  // lookup could match an unrelated (or child) category.
  `category = s.categories.where(permalink: '${FIXTURE_PROMO_TAXON_PERMALINK}').first_or_create!(name: '${FIXTURE_PROMO_TAXON}', parent: nil)`,
  `product = Spree::Product.where(name: '${FIXTURE_PROMO_PRODUCT}').first_or_create!(store: s, status: 'active')`,
  `product.default_variant.set_price(s.default_currency, 19.99)`,
  // Published on the default channel, so the new-order item search — which
  // lists only what the order's channel sells — offers it.
  `Spree::ProductPublication.find_or_create_by!(product: product, channel: s.default_channel)`,
  `product.default_variant.update!(sku: '${FIXTURE_PROMO_SKU}') if product.default_variant.sku != '${FIXTURE_PROMO_SKU}'`,
  `product.categories << category unless product.categories.include?(category)`,
  // Stock the promo product on the store's default stock location so
  // order-creation tests can add it to a draft order without the
  // +"Quantity not available"+ validation kicking in.
  `default_location = s.default_stock_location`,
  `product.variants.each { |v| default_location.stock_levels.where(variant: v).first_or_create!.update!(count_on_hand: 100, backorderable: true) }`,
  // Disjoint product fixtures for products-bulk.spec.ts. Each test owns its
  // own pair (A/B → status, C/D → categories, E/F → tags, G/H → delete,
  // I → row-action clone/delete) so the serial suite can mutate them in any
  // order without poisoning siblings. All start `active` so the status spec
  // sees a clean transition.
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_A}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_B}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_C}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_D}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_E}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_F}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_G}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_H}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_I}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_J}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_K}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_L}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_M}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  `Spree::Product.where(name: '${FIXTURE_BULK_PRODUCT_N}').first_or_create!(store: s, status: 'active').tap { |p| p.default_variant.set_price(s.default_currency, 9.99); p.update!(status: 'active') }`,
  // Second channel beyond the seeded default; the channels bulk-action
  // and filter specs need a non-default channel to add/remove against.
  `bulk_channel = s.channels.where(code: '${FIXTURE_BULK_CHANNEL_CODE}').first_or_create!(name: '${FIXTURE_BULK_CHANNEL_NAME}')`,
  // Pre-list M/N on the bulk channel so the remove-from-channels test
  // has something to undo.
  `bulk_channel.add_products([Spree::Product.find_by(name: '${FIXTURE_BULK_PRODUCT_M}').id, Spree::Product.find_by(name: '${FIXTURE_BULK_PRODUCT_N}').id])`,
  // Category used by the bulk-add-to-categories test, found by permalink for the
  // same reason as the promo category above.
  `s.categories.where(permalink: '${FIXTURE_BULK_CATEGORY_PERMALINK}').first_or_create!(name: '${FIXTURE_BULK_CATEGORY}', parent: nil)`,
  `Spree.customer_class.where(email: '${FIXTURE_PROMO_CUSTOMER_EMAIL}').first_or_create! { |u| u.password = 'customer123'; u.password_confirmation = 'customer123'; u.first_name = '${FIXTURE_PROMO_CUSTOMER_FIRST_NAME}'; u.last_name = '${FIXTURE_PROMO_CUSTOMER_LAST_NAME}' }`,
  `s.customer_groups.where(name: '${FIXTURE_PROMO_CUSTOMER_GROUP}').first_or_create!`,
  // Make the store multi-currency so the money-entry forms (store credit,
  // refunds, manual prices) offer EUR alongside the USD default. Markets own
  // currency + locale (the legacy Store#supported_currencies column is dead),
  // and in markets mode the supported-currency list is exactly the markets'
  // currencies. The store already has a default US/USD market via
  // Store#ensure_default_market, so we add a EUR market here, anchored to
  // Germany. `MarketCountry#country_unique_per_store` forbids reusing a
  // country across markets — the markets specs draw from other EU countries
  // (see the note atop markets.spec.ts).
  // Fail fast (find_by_iso!) if Germany can't be resolved — a missing EUR
  // market would otherwise surface later as opaque multi-currency failures.
  `germany = Spree::Country.find_by_iso!('DE')`,
  `s.markets.find_or_create_by!(name: 'Europe') { |m| m.currency = 'EUR'; m.default_locale = 'de'; m.countries = [germany] } unless s.markets.exists?(currency: 'EUR')`,
  // An order's locale has to be one its market offers, so the orders list can
  // show a German-language order in the default US market.
  `s.default_market.update!(supported_locales: s.default_market.supported_locales_list | ['de']) unless s.default_market.supported_locales_list.include?('de')`,
  // A seller with one settled earning and one payout still owed, so the
  // marketplace ledger screens have rows to read and a settlement to mark
  // paid. Written directly: both are produced by fulfilment and the payout
  // sweep, neither of which an E2E run can reach.
  `ledger_seller = s.sellers.where(name: '${FIXTURE_LEDGER_SELLER}').first_or_create! { |v| v.status = 'approved' }`,
  `ledger_payout = ledger_seller.seller_payouts.where(amount: ${FIXTURE_LEDGER_PAYOUT_AMOUNT}).first_or_create!(store: s, currency: s.default_currency, provider: Spree::PayoutProvider::System.provider_key, status: 'pending')`,
  `ledger_seller.seller_payouts.where(amount: ${FIXTURE_LEDGER_OWED_AMOUNT}).first_or_create!(store: s, currency: s.default_currency, provider: Spree::PayoutProvider::System.provider_key, status: 'pending')`,
  `ledger_order = s.orders.where(seller: ledger_seller).first || Spree::Order.create!(store: s, seller: ledger_seller, currency: s.default_currency, email: '[email protected]', status: 'placed', completed_at: Time.current)`,
  `ledger_seller.seller_transfers.first_or_create!(store: s, order: ledger_order, payout: ledger_payout, amount: ${FIXTURE_LEDGER_PAYOUT_AMOUNT}, currency: s.default_currency, kind: 'earning', provider: Spree::PayoutProvider::System.provider_key, status: 'completed')`,
  // Seller panel accounts. One runs the ledger seller, whose sale and payouts
  // give the read-only panel screens something to show; the other runs a
  // seller of its own that the specs editing a profile, policy or team may
  // change freely. One seller each, so neither lands on the seller picker.
  `seller_user = Spree.admin_user_class.where(email: '${FIXTURE_SELLER_USER_EMAIL}').first_or_create! { |u| u.password = '${FIXTURE_SELLER_PASSWORD}'; u.password_confirmation = '${FIXTURE_SELLER_PASSWORD}'; u.first_name = 'Lee'; u.last_name = 'Ledger' }`,
  'ledger_seller.add_user(seller_user)',
  `panel_seller = s.sellers.where(name: '${FIXTURE_PANEL_SELLER}').first_or_create!`,
  `seller_writer = Spree.admin_user_class.where(email: '${FIXTURE_SELLER_WRITER_EMAIL}').first_or_create! { |u| u.password = '${FIXTURE_SELLER_PASSWORD}'; u.password_confirmation = '${FIXTURE_SELLER_PASSWORD}'; u.first_name = 'Pat'; u.last_name = 'Panel' }`,
  'panel_seller.add_user(seller_writer)',
  // Inventory operations: a second warehouse to transfer into, a stocked
  // product to send, and a supplier to order from. A transfer cannot be
  // created from its own screens without two warehouses.
  `transfer_source = s.stock_locations.where(name: '${FIXTURE_TRANSFER_SOURCE}').first_or_create!(active: true)`,
  `transfer_destination = s.stock_locations.where(name: '${FIXTURE_TRANSFER_DESTINATION}').first_or_create!(active: true)`,
  `transfer_product = Spree::Product.where(name: '${FIXTURE_TRANSFER_PRODUCT}').first_or_create!(store: s, status: 'active')`,
  `transfer_product.default_variant.update!(sku: '${FIXTURE_TRANSFER_SKU}')`,
  `transfer_product.default_variant.set_price(s.default_currency, 24.99)`,
  // Deep enough that the serial suite can ship from it repeatedly.
  'transfer_source.stock_levels.where(variant: transfer_product.default_variant).first_or_create!.update!(count_on_hand: 5000)',
  `s.suppliers.where(name: '${FIXTURE_SUPPLIER}').first_or_create!(email: '[email protected]')`,
  // The Inventory page: its own SKU, stocked at the source so a transfer can
  // leave, and held by one checkout at the destination. The hold is a
  // reservation row written directly — the row keeps the level's counter
  // itself — because a real checkout needs reservations switched on
  // store-wide, which the order specs must not inherit.
  `inventory_product = Spree::Product.where(name: '${FIXTURE_INVENTORY_PRODUCT}').first_or_create!(store: s, status: 'active')`,
  `inventory_product.default_variant.update!(sku: '${FIXTURE_INVENTORY_SKU}')`,
  `inventory_product.default_variant.set_price(s.default_currency, 19.99)`,
  'transfer_source.stock_levels.where(variant: inventory_product.default_variant).first_or_create!.update!(count_on_hand: 500)',
  'inventory_level = transfer_destination.stock_levels.where(variant: inventory_product.default_variant).first_or_create!',
  `unless inventory_level.stock_reservations.exists?; inventory_cart = Spree::Cart.create!(store: s, currency: s.default_currency, email: '[email protected]'); inventory_line = inventory_cart.line_items.create!(variant: inventory_product.default_variant, quantity: ${FIXTURE_INVENTORY_RESERVED}); inventory_level.stock_reservations.create!(cart: inventory_cart, line_item: inventory_line, quantity: ${FIXTURE_INVENTORY_RESERVED}, expires_at: 10.years.from_now); end`,
  // A store whose market writes a comma decimal (Dutch) and prices in EUR: the
  // server reads every request in the market's language, so this is where a
  // price is misread if anything parses money by locale. Its name sorts after
  // the default store's, so signing in still opens the default store first, and
  // its dashboard stays in English so the specs' labels match.
  `comma_store = Spree::Store.find_by(code: 'e2e-nl') || Spree::Store.create!(code: 'e2e-nl', name: 'Winkel', url: 'nl.example.com', mail_from_address: '[email protected]', preferred_admin_locale: 'en')`,
  'Spree::Seeds::StoreResources.call(store: comma_store); Spree::Stores::ProvisionDefaults.call(store: comma_store, country: Spree::Country.find_by_iso!("NL"), locale: "nl", currency: "EUR") unless comma_store.stock_locations.exists?',
  // A second market in USD, so the store sells in a currency written with a
  // period as well as its own.
  `comma_store.markets.find_or_create_by!(name: 'United States') { |m| m.currency = 'USD'; m.default_locale = 'en'; m.countries = [Spree::Country.find_by_iso!('US')] } unless comma_store.markets.exists?(currency: 'USD')`,
  'comma_store.add_user(admin, Spree::Role.default_admin_role(comma_store)) unless comma_store.role_users.exists?(user: admin)',
  // A card payment the Bogus gateway has charged, so its page at the gateway's
  // dashboard has an address, and whose card failed both of the issuer's
  // checks. On this store because the payment method specs install Bogus on the
  // default one, and a store holds each provider once. Written directly:
  // charging a card needs a full checkout.
  `comma_bogus = comma_store.payment_methods.where(type: 'Spree::Gateway::Bogus').first_or_create!(name: '${FIXTURE_BOGUS_GATEWAY}', active: true, storefront_visible: false)`,
  `gateway_order = comma_store.orders.find_by(email: '${FIXTURE_BOGUS_ORDER_EMAIL}') || Spree::Order.create!(store: comma_store, currency: 'EUR', email: '${FIXTURE_BOGUS_ORDER_EMAIL}', status: 'placed', completed_at: Time.current, total: 10)`,
  "gateway_card = Spree::CreditCard.where(payment_method: comma_bogus, gateway_customer_profile_id: 'BGS-E2E').first_or_create!(number: '4111111111111111', verification_value: '123', month: 12, year: 1.year.from_now.year, name: 'E2E Customer', cc_type: 'visa')",
  `gateway_order.payments.create!(payment_method: comma_bogus, source: gateway_card, amount: 10, status: 'completed', response_code: '${FIXTURE_BOGUS_TRANSACTION_ID}', avs_response: 'N', cvv_response_code: 'N', cvv_response_message: 'CVV does not match').capture_events.create!(amount: 10) unless gateway_order.payments.exists?`,
  'port = ENV.fetch("PORT", 3010)',
  'puts JSON.generate(api_url: "http://localhost:#{port}", admin_email: admin.email, admin_password: "spree123", store_id: s.prefixed_id, store_name: s.name, comma_store_id: comma_store.prefixed_id)',
].join('; ')

export default async function globalSetup() {
  rmIfExists(TEST_SQLITE)

  // The dummy test env pins ActiveJob to the :test adapter (RSpec asserts on
  // enqueues), but e2e flows like CSV import only progress when jobs actually
  // run — execute them in-process for the e2e server only. Removed in
  // global-teardown; the DASHBOARD_E2E guard keeps a leftover file inert for
  // regular spec runs.
  writeFileSync(
    ASYNC_JOBS_INITIALIZER,
    [
      '# Written by packages/dashboard/e2e/global-setup.ts — safe to delete.',
      "ActiveJob::Base.queue_adapter = :async if ENV['DASHBOARD_E2E'] == '1'",
      '',
    ].join('\n'),
  )

  // One setting of each kind the connect form renders, so the integrations
  // spec can prove each saves and reads back. Registered after Spree's own
  // integrations list is set up, the way a provider gem registers its own.
  writeFileSync(
    TEST_INTEGRATION_INITIALIZER,
    [
      '# Written by packages/dashboard/e2e/global-setup.ts — safe to delete.',
      "if ENV['DASHBOARD_E2E'] == '1'",
      '  Rails.application.config.after_initialize do',
      '    unless defined?(::E2eRelay)',
      '      class ::E2eRelay < Spree::Integration',
      '        preference :account_id, :string',
      '        preference :api_secret, :password',
      '        preference :sync_interval, :integer, default: 15',
      '        preference :sandbox_mode, :boolean, default: true',
      '',
      "        def self.integration_name = 'E2E Relay'",
      '      end',
      '    end',
      "    Spree.integrations << 'E2eRelay' unless Spree.integrations.include?('E2eRelay')",
      '  end',
      'end',
      '',
    ].join('\n'),
  )

  writeFileSync(
    SLOT_PROBES_INITIALIZER,
    [
      '# Written by packages/dashboard/e2e/global-setup.ts — safe to delete.',
      "if ENV['DASHBOARD_E2E'] == '1'",
      '  Rails.application.config.after_initialize do',
      '    [Spree::Media, Spree::TaxRate, Spree::Variant].each do |model|',
      '      next if model.additional_permitted_attributes.include?({ metadata: {} })',
      '',
      '      model.additional_permitted_attributes += [{ metadata: {} }]',
      '    end',
      '  end',
      'end',
      '',
    ].join('\n'),
  )

  const credentials = runRailsBootstrap(BOOTSTRAP_RUBY, RAILS_ENV)
  writeFileSync(CREDENTIALS_FILE, credentials)

  await startRails(PORT, RAILS_ENV, RAILS_PID_FILE)
}