---
title: "Import from Luma"
description: "A script that reads your Luma events, ticket types, questions and guests, from Luma's API or a guest CSV, and recreates them on Sherpo through the merchant API."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.sherpo.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Import from Luma

This guide runs a script that moves your events from Luma to [event](/overview/categories#event) products on Sherpo: each event with its time and place, its ticket types, its registration questions, and every guest who's going, with what they paid and what they answered. [Migrate from Luma](/overview/migrate-from-luma) covers the rest of the move. It uses the `sherpo` helper from [your first call](/merchant-api/first-call).

## What maps to what

| On Luma | On Sherpo |
| --- | --- |
| An event | A product in the `event` category, its slug `luma-` and the Luma event's id |
| Its start, end and time zone | A [session](/overview/categories#event) |
| Its address, map pin and Google Maps place | `settings.event.location`, with its `latitude`, `longitude` and `map_url` |
| Location shown to guests only | `reveal_location: holders` |
| A Zoom, Google Meet or other online location | A hybrid or online event, its session labeled with the platform; the join link goes in an entry |
| Capacity and waitlist | `settings.event.capacity` and `waitlist` |
| Approval required | `settings.approval: required`, when every ticket type is free |
| A ticket type | A [tier](/overview/concepts#tiers-and-prices) with a one-time price, its capacity on the tier; a hidden one gets no price |
| A registration question | A [question](/merchant-api/guides/registration-questions) of the same kind, required as on Luma, asked with no pattern |
| A guest who's going | A recorded order for each kind of ticket they hold, which gives them their tickets, and their answers |

Tiers and questions are found by their names and labels, so an event with two ticket types of one name, or two questions of one label, on Luma or on Sherpo, stops the import until you rename one. Ticket types become tiers cheapest first, the product's own first tier taking the cheapest. Every run puts the imported tiers back in that order, below any tier of your own, so a cheaper type added on Luma later moves below the others; reorder imported tiers on Sherpo only once you stop running the script. A tier holds what every tier below it does, so a guest holding the in-person ticket also reaches what the online one opens.

## Before you start

- **A Luma Plus API key** for the calendar, from its settings on Luma, to read events through Luma's API. Without Plus, export each event's guest list as a CSV from its Guests tab, and create the event on Sherpo first.
- **A Sherpo token** holding `product:read`, `product:write`, `price:read` and `price:write` to create the events and find them again, `customer:read` and `customer:write` for the guests' access and answers, `transaction:write` to record their orders, `transaction:read` to read the orders earlier runs recorded, and `revenue:read` to tell which of those are refunded, without which a rerun stops when it reads them ([Authentication](/merchant-api/authentication)).
- **Your Stripe account connected**, if you sell paid tickets on Sherpo afterwards ([Payments and payouts](/overview/payments)).

There is no separate test mode, so rehearse on one event first, and with guests' addresses you own: every address you import becomes a customer of your store and counts toward your [plan's](/overview/plans) customers.

## The script

```js
// Your Luma Plus API key, and the currency a free ticket is recorded in; STORE_ID is the Sherpo store your events move to.
const LUMA = 'https://public-api.luma.com';
const LUMA_KEY = process.env.LUMA_API_KEY;
const FREE_CURRENCY = 'eur';
// A guest CSV's columns, as your export names them; any other column whose header is a question's label is its answer.
const CSV_COLUMNS = { email: 'email', status: 'approval_status', ticket: 'ticket_name', amount: 'amount', currency: 'currency', registered: 'created_at' };

// Calls Luma's API, waiting out its rate limit a few times at most.
async function luma(path, query = {}) {
  for (let attempt = 1; ; attempt++) {
    const url = new URL(LUMA + path);
    url.search = new URLSearchParams(query).toString();
    const response = await fetch(url, { headers: { 'x-luma-api-key': LUMA_KEY } });
    if (response.status === 429 && attempt < 10) {
      const header = response.headers.get('Retry-After');
      const after = header === null || header.trim() === '' ? NaN : Number(header);
      await new Promise((done) => setTimeout(done, (Number.isFinite(after) ? after : 60) * 1000));
      continue;
    }
    if (!response.ok) throw new Error(`Luma answered ${response.status} for ${path}.`);
    return response.json();
  }
}

// Every entry of a Luma list, page after page.
async function lumaAll(path, query = {}) {
  const entries = [];
  let cursor = null;
  do {
    const page = await luma(path, cursor === null ? query : { ...query, pagination_cursor: cursor });
    entries.push(...page.entries);
    cursor = page.has_more ? page.next_cursor : null;
  } while (cursor !== null);
  return entries;
}

// Every item of a Sherpo list, page after page.
async function sherpoAll(path, query = []) {
  const items = [];
  let cursor = null;
  do {
    const page = await sherpo('GET', path, { query: [...query, ['limit', '100'], ...(cursor === null ? [] : [['cursor', cursor]])] });
    if (page.cursor === undefined) throw new Error(`${path} answered no cursor, so it is no list to page.`);
    items.push(...page.items);
    cursor = page.cursor;
  } while (cursor !== null);
  return items;
}

// A Sherpo read that answers null for a 404.
async function found(path) {
  try {
    return await sherpo('GET', path);
  } catch (error) {
    if (error.status === 404) return null;
    throw error;
  }
}

// One line of text, cut to what a field takes; null when nothing is left.
const line = (text, max) => {
  const kept = String(text ?? '').split(/\s*[\r\n]+\s*/).join(', ').trim().slice(0, max).trim();
  return kept === '' ? null : kept;
};

// A stable digest wide enough to tell guests apart, so a key changes whenever what it names does.
const digest = async (text) => {
  const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(String(text))));
  return [...bytes.slice(0, 12)].map((byte) => byte.toString(16).padStart(2, '0')).join('');
};

const ONLINE = { zoom: 'Zoom', meet: 'Google Meet', youtube: 'YouTube', twitch: 'Twitch', discord: 'Discord', twitter: 'X' };

// What a Luma event's settings become on Sherpo.
function eventSettings(event, types) {
  const geo = event.geo_address_json;
  const online = Boolean(event.meeting_url) || event.location_type in ONLINE;
  const format = geo ? (online ? 'hybrid' : 'in_person') : 'online';
  const settings = { event: { format, waitlist: event.waitlist_status === 'enabled' } };
  if (event.max_capacity) settings.event.capacity = event.max_capacity;
  if (geo) {
    const country = String(geo.country ?? '').toUpperCase();
    settings.event.reveal_location = event.location_visibility === 'guests-only' ? 'holders' : 'everyone';
    settings.event.location = {
      venue: line(geo.address, 200),
      address: line(geo.full_address, 500),
      city: line(geo.city, 100),
      region: line(geo.region, 100),
      country: /^[A-Z]{2}$/.test(country) ? country : null,
      ...(event.coordinate ? { latitude: event.coordinate.latitude, longitude: event.coordinate.longitude } : {}),
      map_url: geo.google_maps_place_id ? `https://www.google.com/maps/place/?q=place_id:${geo.google_maps_place_id}` : null,
    };
  }
  // A product that asks your approval sells free tickets alone.
  if (event.require_approval && types.every((type) => type.type === 'free')) settings.approval = 'required';
  return settings;
}

// The product for a Luma event, made once: its slug names the Luma event, so a rerun finds it.
async function eventProduct(event, types) {
  const slug = `luma-${event.id.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
  const held = await found(`/v1/stores/STORE_ID/products/slug:${slug}`);
  if (held !== null) return held;
  return sherpo('POST', `/v1/stores/STORE_ID/products`, {
    key: `luma-product-${event.id}`,
    body: {
      slug,
      title: line(event.name, 200),
      category: 'event',
      text_format: 'markdown',
      ...(event.description_md ? { description: event.description_md } : {}),
      settings: eventSettings(event, types),
      metadata: { luma_event_id: event.id },
    },
  });
}

// The event's session, added unless it has one.
async function eventSession(product, event) {
  const sessions = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/sessions`);
  if (sessions.length > 0) return;
  const online = event.meeting_url || event.location_type in ONLINE;
  await sherpo('POST', `/v1/stores/STORE_ID/products/${product.id}/sessions`, {
    key: `luma-session-${event.id}`,
    body: {
      starts_at: event.start_at,
      ends_at: event.end_at,
      time_zone: event.timezone,
      venue: line(event.geo_address_json?.address, 200),
      online_label: online ? (ONLINE[event.location_type] ?? 'Online') : null,
    },
  });
}

// A tier per ticket type, matched by name, cheapest first; a new product's own first tier takes the cheapest. Each is priced unless hidden.
async function ticketTiers(product, types) {
  const tiers = new Map();
  const ranked = [...types].sort((a, b) => (a.cents ?? 0) - (b.cents ?? 0));
  // Tiers are found by name, so two ticket types of one name would share one: rename one on Luma first.
  const named = ranked.map((type) => line(type.name, 120));
  const twice = named.filter((name, i) => named.indexOf(name) !== i);
  if (twice.length > 0) throw new Error(`${product.title ?? product.id} has more than one ticket type named ${[...new Set(twice)].join(', ')}: give each its own name on Luma, then run again.`);
  let held = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/tiers`);
  requireDistinct(product, 'tier', held.map((t) => t.name));
  const prices = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/prices`);
  // The tier a product starts with, still untouched: the only one, and nothing uses it yet.
  const unused = (tier) => Object.values(tier.in_use).every((uses) => uses === 0);
  let fresh = held.length === 1 && prices.length === 0 && unused(held[0]) ? held[0] : null;
  for (const type of ranked) {
    const name = line(type.name, 120);
    const settings = type.max_capacity ? { event: { capacity: type.max_capacity } } : undefined;
    const body = { name, ...(settings ? { settings } : {}) };
    let tier = fresh === null ? held.find((t) => t.name === name) : undefined;
    if (tier === undefined && fresh !== null) {
      tier = await sherpo('PATCH', `/v1/stores/STORE_ID/products/${product.id}/tiers/${fresh.id}`, { key: `luma-tier-${type.id}-${await digest(name)}`, body });
      // Found by its new name from now on, never by its old one.
      held = [...held.filter((t) => t.id !== fresh.id), tier];
      fresh = null;
    } else if (tier === undefined) {
      tier = await sherpo('POST', `/v1/stores/STORE_ID/products/${product.id}/tiers`, { key: `luma-tier-${type.id}-${await digest(name)}`, body });
      // Found by its name from now on, as the next run finds it.
      held.push(tier);
    }
    tiers.set(type.id, tier);
    if (type.is_hidden || prices.some((price) => price.tier_id === tier.id)) continue;
    prices.push({ tier_id: tier.id });
    await sherpo('POST', `/v1/stores/STORE_ID/products/${product.id}/prices`, {
      key: `luma-price-${tier.id}`,
      body: {
        tier: { id: tier.id },
        currency: type.type === 'paid' ? type.currency : FREE_CURRENCY,
        amount: type.type === 'paid' ? type.cents : 0,
        kind: 'one_time',
      },
    });
  }
  // Cheaper tickets rank lower, since a tier holds everything below it; any other tier keeps its place after them.
  const mapped = [...new Set(ranked.map((type) => tiers.get(type.id).id))];
  const current = (await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/tiers`)).sort((a, b) => a.rank - b.rank).map((t) => t.id);
  const wanted = [...mapped, ...current.filter((id) => !mapped.includes(id))];
  // Unkeyed, since ordering again is safe, and refused if the order moved since it was read: then it reads again.
  if (wanted.join() === current.join()) return tiers;
  try {
    await sherpo('POST', `/v1/stores/STORE_ID/products/${product.id}/tiers/reorder`, {
      body: { tiers: wanted.map((id) => ({ id })), from: { tiers: current.map((id) => ({ id })) } },
    });
  } catch (error) {
    if (error.status !== 409) throw error;
    const now = (await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/tiers`)).sort((a, b) => a.rank - b.rank).map((t) => t.id);
    if (now.join() !== wanted.join()) throw new Error(`The tiers of ${product.title ?? product.id} moved while importing: run it again.`, { cause: error });
  }
  return tiers;
}

// What each Luma question kind becomes: Sherpo's kind, and how an answer reads.
const KINDS = {
  text: ['text', (value) => line(value, 300)],
  'long-text': ['long_text', (value) => String(value ?? '').trim().slice(0, 3000) || null],
  'phone-number': ['text', (value) => line(value, 300)],
  url: ['text', (value) => line(value, 300)],
  company: ['text', (value) => line([value?.company, value?.job_title].filter(Boolean).join(', '), 300)],
  'agree-check': ['checkbox', (value) => value === true],
  terms: ['checkbox', (value) => value !== null && value !== undefined && value !== false],
  select: ['select', (value) => value],
  // A CSV writes a ticked box as text.
  'csv-check': ['checkbox', (value) => /^(yes|true|1)$/i.test(String(value).trim())],
};

// A question per Luma question, matched by its label, required as on Luma, with no pattern so every imported answer fits.
async function eventQuestions(product, questions) {
  const asked = new Map();
  // Questions are found by label, so two of one label would answer as one: rename one on Luma first.
  const labels = questions.map((question) => line(question.label, 200));
  const twice = labels.filter((label, i) => labels.indexOf(label) !== i);
  if (twice.length > 0) throw new Error(`${product.title ?? product.id} asks more than one question labeled ${[...new Set(twice)].join(', ')}: give each its own label on Luma, then run again.`);
  const held = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/questions`);
  requireDistinct(product, 'question', held.map((q) => q.label));
  for (const question of questions) {
    let type = question.question_type === 'text' && question.multiline ? 'long-text' : question.question_type;
    if (type === 'select' && question.multiple) type = 'multi-select';
    const kind = type === 'multi-select' ? 'multi_select' : (KINDS[type] ?? KINDS.text)[0];
    const label = line(question.label, 200);
    let made = held.find((q) => q.label === label);
    if (made === undefined)
      made = await sherpo('POST', `/v1/stores/STORE_ID/products/${product.id}/questions`, {
        key: `luma-question-${product.id}-${question.id}-${await digest(label)}`,
        body: { kind, label, required: Boolean(question.required), ...(kind.endsWith('select') ? { options: question.options } : {}) },
      });
    asked.set(question.id, { ...made, type });
  }
  return asked;
}

// Whether an answer says nothing: empty, only spaces, or a company with neither part.
const blank = (value) =>
  value == null ||
  (typeof value === 'string' && value.trim() === '') ||
  (Array.isArray(value) && value.length === 0) ||
  (typeof value === 'object' && !Array.isArray(value) && Object.values(value).every((part) => blank(part ?? null)));

// A guest's answers as Sherpo takes them; one that no longer fits its question is left out and logged.
function answersOf(guest, asked) {
  const answers = [];
  for (const { key, value } of guest.answers) {
    const question = asked.get(key);
    if (question === undefined) continue;
    // An answer given blank clears an optional one here too; a required one keeps what it holds, and a question with no answer given is left as it is.
    if (blank(value)) {
      if (!question.required) answers.push({ question: question.id, label: question.label, value: null });
      continue;
    }
    let read = question.type === 'multi-select' ? [].concat(value) : (KINDS[question.type] ?? KINDS.text)[1](value);
    if (question.kind === 'select' && !question.options.includes(read)) read = null;
    // A question found by its label may be of another kind than Luma's: an answer that doesn't fit it is left out.
    if (question.kind === 'multi_select') read = Array.isArray(read) ? read.filter((option) => question.options.includes(option)) : null;
    else if (Array.isArray(read) || (question.kind === 'checkbox') !== (typeof read === 'boolean')) read = null;
    if (read === null || (Array.isArray(read) && read.length === 0)) {
      console.log(`Left out ${guest.email}'s answer to "${question.label}".`);
      continue;
    }
    answers.push({ question: question.id, label: question.label, value: read });
  }
  return answers;
}

// Records an order once by its key: a rerun reads the one recorded before.
async function recordOnce(body) {
  try {
    return await sherpo('POST', `/v1/stores/STORE_ID/orders`, { body });
  } catch (error) {
    const context = error.problem?.context;
    if (error.status !== 409 || context?.field !== 'source_key' || !context.current) throw error;
    return sherpo('GET', `/v1/stores/STORE_ID/orders/${context.current}`);
  }
}

// Sets a guest's answers, leaving out each one Sherpo refuses and saying why.
async function setAnswers(product, customerId, guest, answers) {
  let left = answers;
  while (left.length > 0) {
    try {
      await sherpo('PUT', `/v1/stores/STORE_ID/products/${product.id}/customers/${customerId}/answers`, {
        body: { answers: left.map(({ question, value }) => ({ question, value })) },
      });
      return;
    } catch (error) {
      if (error.status === 409 && error.problem?.context?.field === 'customer')
        return console.log(`Left out ${guest.email}'s answers: they hold no ticket to it now.`);
      const path = error.problem?.context?.path ?? [];
      const at = path[path.indexOf('answers') + 1];
      if (error.status !== 422 || !path.includes('answers') || typeof at !== 'number') throw error;
      console.log(`Left out ${guest.email}'s answer to "${left[at].label}": ${error.problem.context.reason ?? error.message}`);
      left = left.filter((_, i) => i !== at);
    }
  }
}

// One going guest: an order per kind of ticket they hold, recorded once each by a key naming the guest, then their answers.
async function recordGuest(product, tiers, asked, guest, touched) {
  if (guest.tickets.length === 0) return console.log(`Skipped ${guest.email}: no tickets.`);
  const groups = new Map();
  for (const ticket of guest.tickets) {
    const tier = tiers.get(ticket.type);
    if (tier === undefined) {
      console.log(`Skipped a ticket of ${guest.email}: no tier is named "${ticket.type}".`);
      // Their orders from earlier runs may stand for it, so none is taken for a ticket given back.
      touched.add(guest.key);
      continue;
    }
    const amount = Number(ticket.amount ?? 0);
    const where = `${guest.email}'s "${ticket.type}" ticket to ${product.title ?? product.id}`;
    if (!Number.isSafeInteger(amount) || amount < 0) throw new Error(`${where} cost ${ticket.amount}, which is no amount in minor units.`);
    if (amount > 0 && !ticket.currency) throw new Error(`${where} cost ${amount} in no currency.`);
    const currency = ticket.currency || FREE_CURRENCY;
    const group = `${tier.id}-${amount}-${currency}`;
    groups.set(group, { tier, amount, currency, quantity: (groups.get(group)?.quantity ?? 0) + 1 });
  }
  if (groups.size === 0) return console.log(`Skipped ${guest.email}: none of their tickets matched a tier, so no order and no answers.`);
  let customerId = null;
  for (const [group, { tier, amount, currency, quantity }] of groups) {
    const key = `${guest.key}-${await digest(group)}`;
    touched.add(key);
    const order = await recordOnce({
      customer: { email: guest.email },
      currency,
      items: [{ product: { id: product.id }, tier: { id: tier.id }, quantity, amount }],
      source_key: key,
      ...(guest.registered ? { occurred_at: guest.registered } : {}),
    });
    customerId = order.customer_id;
    // A guest holding more or fewer of these tickets than a run recorded before: say so, for you to record or refund the difference.
    const recorded = order.lines?.items?.[0]?.quantity;
    if (recorded !== undefined && recorded !== quantity)
      console.log(`${guest.email} holds ${quantity} "${tier.name}" tickets at ${amount} on Luma, and ${recorded} were recorded: record the difference by hand.`);
  }
  const answers = answersOf(guest, asked);
  if (customerId !== null && answers.length > 0) await setAnswers(product, customerId, guest, answers);
}

// Orders an earlier run imported for the event that no ticket on Luma stands for now: say so, for you to refund them or end the access.
async function reconcile(product, touched) {
  for (const order of await sherpoAll(`/v1/stores/STORE_ID/orders`, [['filter[product_id]', product.id], ['filter[source]', 'manual']])) {
    const key = order.source_key ?? '';
    if (!key.startsWith('luma-') || touched.has(key) || touched.has(key.slice(0, key.lastIndexOf('-')))) continue;
    if (order.free) {
      // A free ticket has nothing to refund: it's done once the access this order gave has ended.
      const live = await sherpoAll(`/v1/stores/STORE_ID/grants`, [['filter[customer_id]', order.customer_id], ['filter[product_id]', product.id], ['filter[live]', 'true']]);
      if (live.some((grant) => grant.source_kind === 'manual' && grant.source_ref === order.id))
        console.log(`Order ${order.number} was imported for a free ticket nobody holds on Luma now: revoke the access it gave on Sherpo if they cancelled.`);
      continue;
    }
    if (order.settled === null) throw new Error('Reading which imported orders are refunded takes a token holding revenue:read.');
    if (order.refund_status === 'full') continue;
    console.log(`Order ${order.number} was imported for tickets nobody holds on Luma now: refund it on Sherpo if you refunded them.`);
  }
}

// A currency's symbol, or null for a malformed code.
const symbolOf = (currency) => {
  let format;
  try {
    format = new Intl.NumberFormat('en', { style: 'currency', currency, currencyDisplay: 'narrowSymbol' });
  } catch (error) {
    if (error instanceof RangeError) return null;
    throw error;
  }
  return format.formatToParts(1).find((part) => part.type === 'currency').value;
};

// Tiers and questions are found by name and label, so two of one would be one: rename one on Sherpo first.
function requireDistinct(product, what, names) {
  const twice = names.filter((name, i) => names.indexOf(name) !== i);
  if (twice.length > 0) throw new Error(`${product.title ?? product.id} has more than one ${what} named ${[...new Set(twice)].join(', ')}: rename one on Sherpo first.`);
}

// Moves each Luma event named, or every event your key manages on the calendar.
async function importFromLuma(eventIds) {
  let ids = eventIds;
  if (ids === undefined) {
    ids = [];
    for (const entry of await lumaAll('/v1/calendars/events/list', { access: 'manage' })) {
      if (entry.platform === 'external') console.log(`Skipped ${entry.name}: it is listed on Luma from elsewhere.`);
      else ids.push(entry.id);
    }
  }
  for (const id of ids) {
    const event = await luma('/v1/events/get', { event_id: id });
    const types = (await luma('/v1/events/ticket-types/list', { event_id: id, include_hidden: 'true' })).entries;
    const product = await eventProduct(event, types);
    await eventSession(product, event);
    const tiers = await ticketTiers(product, types);
    const asked = await eventQuestions(product, event.registration_questions ?? []);
    if (event.meeting_url) console.log(`${event.name}: move its join link into a Join entry.`);
    const touched = new Set();
    for (const guest of await lumaAll('/v1/events/guests/list', { event_id: id })) {
      if (guest.approval_status !== 'approved') {
        console.log(`Skipped ${guest.user_email}: ${guest.approval_status}.`);
        continue;
      }
      await recordGuest(product, tiers, asked, {
        key: `luma-${guest.id}`,
        email: guest.user_email,
        registered: guest.registered_at ?? undefined,
        tickets: guest.event_tickets.map((ticket) => ({ type: ticket.event_ticket_type_id, amount: ticket.amount, currency: ticket.currency })),
        answers: (guest.registration_answers ?? []).map((answer) => ({ key: answer.question_id, value: answer.value })),
      }, touched);
    }
    await reconcile(product, touched);
  }
}

// A CSV's rows as objects by header, quoted fields and all.
function parseCsv(text) {
  const rows = [[]];
  let field = '';
  let quoted = false;
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    if (quoted) {
      if (c === '"' && text[i + 1] === '"') (field += '"'), i++;
      else if (c === '"') quoted = false;
      else field += c;
    } else if (c === '"') quoted = true;
    else if (c === ',') rows.at(-1).push(field), (field = '');
    else if (c === '\n' || c === '\r') {
      if (c === '\r' && text[i + 1] === '\n') i++;
      rows.at(-1).push(field), (field = ''), rows.push([]);
    } else field += c;
  }
  rows.at(-1).push(field);
  const [header = [], ...body] = rows.filter((row) => row.some((cell) => cell !== ''));
  const missing = ['email', 'status', 'ticket', 'amount', 'currency'].filter((column) => !header.includes(CSV_COLUMNS[column]));
  if (missing.length > 0) throw new Error(`The CSV has no ${missing.map((column) => CSV_COLUMNS[column]).join(', ')} column: set CSV_COLUMNS to its headers.`);
  return body.map((row) => Object.fromEntries(header.map((name, i) => [name, row[i] ?? ''])));
}

// Imports a Luma guest CSV into an event you already made on Sherpo: one row per ticket, its ticket name a tier's name.
async function importCsv(csv, productRef) {
  const product = await sherpo('GET', `/v1/stores/STORE_ID/products/${productRef}`);
  // A CSV names ticket types and questions by name and label, so it looks them up so, and two of one name would be one.
  const held = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/tiers`);
  const questions = await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/questions`);
  requireDistinct(product, 'tier', held.map((t) => t.name));
  requireDistinct(product, 'question', questions.map((q) => q.label));
  const tiers = new Map(held.map((tier) => [tier.name, tier]));
  // Each currency's minor units, as Sherpo counts them, from the event's own prices.
  const exponents = new Map((await sherpoAll(`/v1/stores/STORE_ID/products/${product.id}/prices`)).map((price) => [price.currency, price.exponent]));
  const asked = new Map();
  for (const question of questions) {
    const type = { multi_select: 'multi-select', checkbox: 'csv-check', long_text: 'long-text', select: 'select' }[question.kind] ?? 'text';
    asked.set(question.label, { ...question, type });
  }
  const guests = new Map();
  for (const row of parseCsv(csv)) {
    const email = row[CSV_COLUMNS.email].trim().toLowerCase();
    if (row[CSV_COLUMNS.status] !== 'approved') {
      console.log(`Skipped ${email}: ${row[CSV_COLUMNS.status]}.`);
      continue;
    }
    // Keyed by the event and the address, so the rows' order never changes what a rerun records.
    const guest = guests.get(email) ?? { key: `luma-${await digest(`${product.id} ${email}`)}`, email, registered: row[CSV_COLUMNS.registered] || undefined, tickets: [], answers: [] };
    // An amount such as 25, 25.00, $25.00 or 25.00 USD, or empty or Free for nothing; any other stops the import rather than guess.
    const written = row[CSV_COLUMNS.amount].trim();
    const read = /^(?:([$€£¥])|([A-Z]{3}) )?(\d+)(?:\.(\d+))?(?: ([A-Z]{3}))?$/.exec(written);
    if (read === null && !/^(free)?$/i.test(written)) throw new Error(`${email}'s amount ${written} isn't one this script reads: write it as 1250.00, with no thousands separator or sign.`);
    const [, symbol, before, whole = '0', fraction = '', after] = read ?? [];
    const column = row[CSV_COLUMNS.currency].trim().toLowerCase() || null;
    const paid = /[1-9]/.test(whole + fraction);
    if (paid && column === null) throw new Error(`${email} paid ${written} in no currency.`);
    const places = exponents.get(column) ?? null;
    if (paid && places === null) throw new Error(`${email} paid ${written} in ${column.toUpperCase()}, which the event sells no ticket in: add a price in it first.`);
    // Read exactly, digit by digit, in Sherpo's minor units for the currency: a decimal past them stops the import rather than round.
    if (/[1-9]/.test(fraction.slice(places ?? 0))) throw new Error(`${email}'s amount ${written} has more decimals than its currency takes.`);
    const amount = paid ? Number(whole) * 10 ** places + Number(fraction.slice(0, places).padEnd(places, '0') || 0) : 0;
    // A currency written in the amount, as a code or a symbol, must be the column's.
    const codes = [before, after].filter(Boolean).map((code) => code.toLowerCase());
    const fits = codes.every((code) => code === column) && (symbol === undefined || symbol === symbolOf(column));
    if (paid && !fits) throw new Error(`${email}'s amount ${written} is in another currency than its currency column's ${column}.`);
    // A free ticket is recorded in the free tickets' currency, whatever the event sells, so a rerun keys it the same.
    guest.tickets.push({ type: row[CSV_COLUMNS.ticket], amount, currency: paid ? column : null });
    if (guest.answers.length === 0)
      for (const [header, value] of Object.entries(row))
        if (asked.has(header)) guest.answers.push({ key: header, value: asked.get(header).type === 'multi-select' && value.trim() !== '' ? value.split(/\s*,\s*/).filter(Boolean) : value });
    guests.set(email, guest);
  }
  const touched = new Set();
  for (const guest of guests.values()) await recordGuest(product, tiers, asked, guest, touched);
  await reconcile(product, touched);
}
```

Run it in Node with `LUMA_API_KEY` and `SHERPO_TOKEN` set and your store's id in place of `STORE_ID`:

- **`importFromLuma()`** moves every event your key manages on its calendar, past ones included, and skips events listed there from elsewhere; `importFromLuma(['evt-...'])` moves only the events you name.
- **`importCsv(csv, 'PRODUCT_ID')`** imports a guest CSV into an event you already made on Sherpo, by its id or as `slug:` and its slug. Each row is one ticket, its ticket name the name of one of the event's tiers, and any column whose header is one of its questions' labels is that question's answer. Check `CSV_COLUMNS` against your export's headers. The CSV writes amounts in the currency's units, which the script turns into Sherpo's minor units for that currency, read from the event's own prices: a paid ticket in a currency the event has no price in stops the import, so add one first. A free ticket is recorded in `FREE_CURRENCY`, whatever its currency column says. A CSV missing one of those columns, an amount written another way than `25`, `25.00`, `$25.00` or `25.00 USD` (or empty or `Free` for a free ticket), a currency in the amount, as a code or a symbol, that isn't the column's, an amount with more decimals than its currency takes, or a paid amount with no currency, stops the import before it records anything. Import each event one way, through Luma's API or its CSV, never both: each keys its guests its own way.

It waits out Luma's rate limit. For Sherpo's, wrap each call in the [retry](/merchant-api/errors#retrying) helper.

## What each guest gets

Each guest who's going gets an order for each kind of ticket they hold, recorded with <a href="/merchant-api/reference/record-order/">`POST /orders`</a> by their email: two tickets of one type at one price are one order of two, and a ticket of another type or price is an order of its own, at its own tier. The order gives them their ticket, takes their seats from the event's capacity, and is dated when they registered. A guest who isn't a customer yet becomes one, invited, and finds the event in their library when they first sign in with that address. Recording moves no money: what they paid on Luma stays with your Stripe account there.

Their answers are set with <a href="/merchant-api/reference/set-customer-answers/">`PUT /products/{product}/customers/{customer}/answers`</a> once the order is recorded. An answer that no longer fits its question, such as a pick that isn't among the options, or one the question refuses, is left out and logged, and the rest are set. An answer Luma gives blank, or a blank cell in a CSV's column, clears an optional question on Sherpo; a required one keeps what it holds, and a question Luma or the CSV gives no answer to is left as it is, so an answer a guest gave on Sherpo stays.

Guests Luma hasn't approved, such as those pending your approval, on the waitlist, invited or declined, are skipped and logged: decide them on Luma before you move, then rerun.

Recording an order sends what a sale on your store sends:

- **The registration email**, with the guest's ticket code as a QR code and a calendar file, for an event with a session ahead. To import quietly, add an **Event registration** message in [Customer messages](/merchant-app/settings#customer-messages) that sends for that event alone, with **Sending** off, before you run the script, and delete it after.
- **Reminders** before each session and a thanks after the last one, as browser notifications to guests who allowed them.
- **Your automations** on a purchase of the event, and an `order.created` [webhook](/merchant-api/webhooks) to endpoints that take it. Pause what shouldn't fire for an import.

## Run it again

A run that stops halfway runs again from the start. It finds the event by its slug, adds a session only to an event with none, and finds tiers by their names, prices by their tiers and questions by their labels, so it adds none twice, however long after. Each order is recorded once by its `source_key`, which names the Luma guest (from a CSV, the event and their address) and the kind of ticket: a rerun reads the one already recorded and sets the guest's answers again. A tier or question you rename on Sherpo is no longer found, and the next run adds it again under its Luma name. A guest whose tickets changed on Luma since the last run, to another type or price, gets an order for the new ones too, beside the one recorded before: record a refund of the old one on Sherpo when you refunded it on Luma. A guest holding more or fewer tickets of one type and price than were recorded is logged, for you to record the difference, and, once every guest is through, so is each order imported before for tickets nobody holds on Luma now, whether the guest gave a ticket back, cancelled or left the list, for you to refund, unless it's refunded in full already; a free one is logged while the access it gave stands, for you to revoke it. A ticket whose tier the run can't find leaves that guest's earlier orders alone. A guest who registered on Luma since the last run is imported by the next.

The products stay drafts. Publish each once you've checked it ([Products and prices](/merchant-api/guides/products-and-prices)).

## What doesn't move

- **Check-ins**: a guest is checked in at the door when they arrive, so past check-ins stay in Luma's export.
- **Ticket codes**: Sherpo issues its own, which each guest finds in the registration email and in their library.
- **Coupons**: recreate them as [discounts](/merchant-app/discounts-and-affiliates).
- **The cover and the join link**: upload the cover to the product, and put the join link in an entry that opens before the session ([Events](/overview/categories#event)).
- **Hosts**: invite them to your business as members in the merchant app ([Business and team](/merchant-app/business-and-team)).
- **Payments and payouts**: they stay with the Stripe account Luma paid into.

Source: https://docs.sherpo.io/merchant-api/guides/import-from-luma/index.mdx
