Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

14.8 KB
Raw Blame
import type { ShopifyOrder, ShopifyStore } from '@linedesk/connectors'
import { describe, expect, it } from 'vitest'
import {
  checkProof,
  nameFits,
  nameQueries,
  orderView,
  phoneForSearch,
  productQueries,
  sameName,
  samePostcode,
  searchOrders,
} from './shopify-calls.ts'

const order = (over: Partial<ShopifyOrder> = {}): ShopifyOrder => ({
  id: 'gid://shopify/Order/1',
  name: '#1001',
  createdAt: '2026-11-18T10:00:00Z',
  cancelledAt: null,
  financialStatus: 'PAID',
  fulfillmentStatus: 'UNFULFILLED',
  total: '89.00 USD',
  customer: { id: 'gid://shopify/Customer/7', name: 'Mike Brennan', email: '[email protected]', phone: '+15035550142' },
  email: '[email protected]',
  phone: null,
  shippingAddress: {
    name: 'Mike Brennan',
    address1: '12 Oak St',
    address2: null,
    city: 'Portland',
    province: 'Oregon',
    zip: '97205',
    country: 'United States',
    phone: null,
  },
  items: [{ title: 'Water heater valve', quantity: 1 }],
  shipments: [],
  ...over,
})

describe('checks before a change', () => {
  it('matches the family name, not a first name alone', () => {
    expect(sameName('Mike Brennan', order())).toBe(true)
    expect(sameName('michael brennan', order())).toBe(true)
    expect(sameName('Mike', order())).toBe(false)
    expect(sameName('Mike Smith', order())).toBe(false)
  })
  it('compares postcodes loosely', () => {
    expect(samePostcode('97205-1234', '97205')).toBe(true)
    expect(samePostcode('sw1a 1aa', 'SW1A1AA')).toBe(true)
    expect(samePostcode('97206', '97205')).toBe(false)
  })
  const caller = { number: '+15035550142', attested: true }
  it('asks for what is missing', () => {
    expect(checkProof(['verify_name', 'verify_postcode'], { name: 'Mike Brennan' }, order(), caller)).toEqual({
      missing: ['verify_postcode'],
      mismatch: false,
    })
  })
  it('passes when everything matches, fails when one does not', () => {
    expect(
      checkProof(['verify_name', 'verify_postcode'], { name: 'Mike Brennan', postcode: '97205' }, order(), caller),
    ).toEqual({ missing: [], mismatch: false })
    expect(
      checkProof(['verify_name', 'verify_postcode'], { name: 'Mike Brennan', postcode: '10001' }, order(), caller)
        .mismatch,
    ).toBe(true)
  })
  it('trusts the caller number only with full attestation', () => {
    expect(checkProof(['verify_caller_number'], {}, order(), caller).mismatch).toBe(false)
    expect(checkProof(['verify_caller_number'], {}, order(), { ...caller, attested: false }).mismatch).toBe(true)
    expect(checkProof(['verify_caller_number'], {}, order(), { number: '+15035550199', attested: true }).mismatch).toBe(
      true,
    )
  })
})

describe('finding orders', () => {
  const store = (orders: ShopifyOrder[], seen: string[] = []) =>
    ({
      findCustomers: async (_t: unknown, q: string) => (
        seen.push(`customers ${q}`),
        q.includes('+1503') || q.includes('"Brennan"') ? [{ id: 'gid://shopify/Customer/7', name: 'Mike Brennan' }] : []
      ),
      findOrders: async (_t: unknown, q: string) => (seen.push(`orders ${q}`), orders),
    }) as unknown as ShopifyStore
  const token = async () => 'a.myshopify.com|t'
  it('searches by order number in both forms', async () => {
    const seen: string[] = []
    await searchOrders(store([order()], seen), token, { orderNumber: 'order 1001', status: 'unshipped' })
    expect(seen).toEqual([
      'orders (name:"#1001" OR name:"1001") AND fulfillment_status:unshipped AND -status:cancelled',
    ])
  })
  it('finds a phone number’s customer first', async () => {
    const seen: string[] = []
    await searchOrders(store([order()], seen), token, { phone: '+15035550142' })
    expect(seen).toEqual(['customers phone:"+15035550142"', 'orders (customer_id:7)'])
  })
  it('narrows by postcode, and needs something besides it', async () => {
    const other = order({ name: '#1002', shippingAddress: { ...order().shippingAddress!, zip: '10001' } })
    expect(
      (await searchOrders(store([order(), other]), token, { name: 'Brennan', postcode: '97205' }))!.map(o => o.name),
    ).toEqual(['#1001'])
    expect(await searchOrders(store([order()]), token, { postcode: '97205' })).toBeNull()
  })
  it('quotes what the caller said', async () => {
    const seen: string[] = []
    await searchOrders(store([], seen), token, { name: 'O"Brien OR status:any' })
    expect(seen[0]).toBe('customers first_name:"O\\"Brien OR" AND last_name:"status:any"')
  })
  it('tries each detail alone when all together find nothing, the order number first', async () => {
    const seen: string[] = []
    const byNumber = {
      findCustomers: async () => [{ id: 'gid://shopify/Customer/7', name: 'Mike Brennan' }],
      findOrders: async (_t: unknown, q: string) => (
        seen.push(q), q.startsWith('(name:') && !q.includes('AND') ? [order()] : []
      ),
    } as unknown as ShopifyStore
    const found = await searchOrders(byNumber, token, { orderNumber: '1001', name: 'Mike Brenan' })
    expect(found!.map(o => o.name)).toEqual(['#1001'])
    expect(seen).toEqual(['(name:"#1001" OR name:"1001") AND (customer_id:7)', '(name:"#1001" OR name:"1001")'])
  })
  it('falls back from the full name to the family name and its first letters, all on the customer', async () => {
    const seen: string[] = []
    expect(await searchOrders(store([], seen), token, { name: 'Mike Brenan' })).toEqual([])
    expect(seen).toEqual([
      'customers first_name:"Mike" AND last_name:"Brenan"',
      'customers last_name:"Brenan"',
      'customers last_name:bren*',
    ])
  })
  it('searches at most six times for one lookup', async () => {
    const seen: string[] = []
    await searchOrders(store([], seen), token, {
      orderNumber: '1',
      email: '[email protected]',
      phone: '+15035550142',
      name: 'Ann Lee Brennan',
    })
    expect(seen.filter(q => q.startsWith('orders')).length).toBeLessThanOrEqual(6)
  })
  it('finds no order for a phone number no customer has', async () => {
    expect(await searchOrders(store([order()]), token, { phone: '+19995550100' })).toEqual([])
  })
  it('shows an order in plain words', () => {
    const view = orderView(
      order({
        fulfillmentStatus: 'FULFILLED',
        shipments: [
          {
            status: 'IN_TRANSIT',
            carrier: 'UPS',
            tracking: '1Z9',
            trackingUrl: null,
            estimatedDelivery: '2026-11-22T00:00:00Z',
            deliveredAt: null,
          },
        ],
      }),
    )
    expect(view.status).toBe('shipped')
    expect(view.shipments).toEqual(['in transit, with UPS, tracking number 1Z9, expected 2026-11-22'])
    // Never the name, street or postcode: the checks before a change compare those.
    expect(view.shipTo).toBe('Portland, Oregon, United States')
    expect(view.customer).toBeNull()
  })
  it('says store states as plain words, not Shopify jargon', () => {
    expect(orderView(order({ fulfillmentStatus: 'UNFULFILLED', shipments: [] })).status).toBe('not shipped yet')
    expect(orderView(order({ fulfillmentStatus: 'PARTIALLY_FULFILLED', shipments: [] })).status).toBe('partly shipped')
    // A state Shopify adds later keeps its own words.
    expect(orderView(order({ fulfillmentStatus: 'NEW_STATE', shipments: [] })).status).toBe('new state')
  })
})

describe('productQueries', () => {
  it('tries what the caller said, then with the last words left out, at most three times', () => {
    expect(productQueries('Complete Snowboard Powder')).toEqual([
      'Complete Snowboard Powder',
      'Complete Snowboard',
      'Complete',
    ])
    expect(productQueries('the big red ski wax')).toEqual(['the big red ski wax', 'the big red ski', 'the big red'])
    expect(productQueries('  wax  ')).toEqual(['wax'])
  })

  it('never searches a single word shorter than three letters', () => {
    expect(productQueries('XL shirt')).toEqual(['XL shirt'])
    expect(productQueries('a')).toEqual(['a'])
  })
})

describe('phoneForSearch', () => {
  it('writes a number as the store keeps it', () => {
    expect(phoneForSearch('(503) 555-0118')).toBe('+15035550118')
    expect(phoneForSearch('503-555-0118', '+15035550142')).toBe('+15035550118')
    expect(phoneForSearch('1 503 555 0118')).toBe('+15035550118')
    expect(phoneForSearch('+1 (503) 555-0118')).toBe('+15035550118')
    expect(phoneForSearch('0049 151 2345678')).toBe('+491512345678')
  })
  it('keeps a number of another country as said', () => {
    expect(phoneForSearch('0151 2345678', '+4930123456')).toBe('01512345678')
    expect(phoneForSearch('no number')).toBeNull()
  })
})

describe('nameQueries', () => {
  it('searches customers by first and family name, then the family name, then its first letters', () => {
    expect(nameQueries('Michael Brennan')).toEqual([
      'first_name:"Michael" AND last_name:"Brennan"',
      'last_name:"Brennan"',
      'last_name:bren*',
    ])
    expect(nameQueries('José Núñez')).toEqual([
      'first_name:"José" AND last_name:"Núñez"',
      'last_name:"Núñez"',
      'last_name:nune*',
    ])
  })
  it('takes one word as the family name, and leaves out titles and initials', () => {
    expect(nameQueries('Lee')).toEqual(['last_name:"Lee"'])
    expect(nameQueries('Mr. Weber')).toEqual(['last_name:"Weber"', 'last_name:webe*'])
    expect(nameQueries('Frau Dr. Anna Weber')).toEqual([
      'first_name:"Anna" AND last_name:"Weber"',
      'last_name:"Weber"',
      'last_name:webe*',
    ])
    expect(nameQueries('J. Weber')[0]).toBe('last_name:"Weber"')
    expect(nameQueries('Mr')).toEqual([])
  })
  it('keeps a double-barrel first name together', () => {
    expect(nameQueries('Jonas-Peter Haller')[0]).toBe('first_name:"Jonas-Peter" AND last_name:"Haller"')
    expect(nameQueries('Jonas Peter Haller')[0]).toBe('first_name:"Jonas Peter" AND last_name:"Haller"')
  })
})

describe('finding orders by name', () => {
  type Person = { id: number; first: string; last: string }
  const people: Person[] = [
    { id: 1, first: 'Jonas-Peter', last: 'Haller' },
    { id: 2, first: 'Jonas', last: 'Weber' },
    { id: 3, first: 'Michael', last: 'Brennan' },
  ]
  const orderOf = (p: Person, name: string, shipTo = `${p.first} ${p.last}`) =>
    order({
      id: `gid://shopify/Order/${name.slice(1)}`,
      name,
      customer: { id: `gid://shopify/Customer/${p.id}`, name: `${p.first} ${p.last}`, email: null, phone: null },
      shippingAddress: { ...order().shippingAddress!, name: shipTo },
    })
  const orders = [orderOf(people[0]!, '#2002'), orderOf(people[1]!, '#8001'), orderOf(people[2]!, '#7001')]
  const unquote = (v: string) => v.replace(/^"|"$/g, '').toLowerCase()
  /**
   * A shop like Shopify's: field searches on customers, orders by customer id. `loose`: its customer search also
   * returns customers that share only the first name, and free text on orders matches every order (stemming, LIN-899).
   */
  const shop = (seen: string[] = [], loose = false) =>
    ({
      findCustomers: async (_t: unknown, q: string) => {
        seen.push(`customers ${q}`)
        const first = /first_name:("[^"]*"|\S+)/.exec(q)?.[1]
        const last = /last_name:("[^"]*"|\S+)/.exec(q)?.[1]
        return people
          .filter(p => {
            const firstOk = !first
              ? true
              : loose
                ? p.first.toLowerCase().startsWith(unquote(first))
                : p.first.toLowerCase() === unquote(first)
            const lastOk = !last
              ? true
              : last.endsWith('*')
                ? p.last.toLowerCase().startsWith(last.slice(0, -1))
                : p.last.toLowerCase() === unquote(last)
            return loose ? firstOk || lastOk : firstOk && lastOk
          })
          .map(p => ({ id: `gid://shopify/Customer/${p.id}`, name: `${p.first} ${p.last}` }))
      },
      findOrders: async (_t: unknown, q: string) => {
        seen.push(`orders ${q}`)
        const ids = [...q.matchAll(/customer_id:(\d+)/g)].map(m => m[1])
        if (ids.length) {
          const mine = orders.filter(o => ids.includes(gidOf(o)))
          // Loose: the free text in the query hits every order.
          return loose ? orders : mine
        }
        return loose ? orders : []
      },
    }) as unknown as ShopifyStore
  const gidOf = (o: ShopifyOrder) => o.customer!.id.split('/').at(-1)!
  const token = async () => 'a.myshopify.com|t'
  const numbers = (found: ShopifyOrder[] | null) => found!.map(o => o.name)

  it('finds the customer by first and family name, then their orders', async () => {
    const seen: string[] = []
    expect(numbers(await searchOrders(shop(seen), token, { name: 'Jonas Weber' }))).toEqual(['#8001'])
    expect(seen).toEqual(['customers first_name:"Jonas" AND last_name:"Weber"', 'orders (customer_id:2)'])
  })
  it('never gives Jonas Weber the order of another Jonas, even from a loose store', async () => {
    const found = await searchOrders(shop([], true), token, { name: 'Jonas Weber' })
    expect(numbers(found)).toEqual(['#8001'])
  })
  it('finds a double-barrel first name', async () => {
    expect(numbers(await searchOrders(shop(), token, { name: 'Jonas-Peter Haller' }))).toEqual(['#2002'])
    // Said without the hyphen: the family name alone finds them.
    expect(numbers(await searchOrders(shop(), token, { name: 'Jonas Peter Haller' }))).toEqual(['#2002'])
  })
  it('finds a family name with another first name, a title, or one letter misheard', async () => {
    expect(numbers(await searchOrders(shop(), token, { name: 'Mike Brennan' }))).toEqual(['#7001'])
    expect(numbers(await searchOrders(shop(), token, { name: 'Mr Brennan' }))).toEqual(['#7001'])
    expect(numbers(await searchOrders(shop(), token, { name: 'Mike Brenan' }))).toEqual(['#7001'])
  })
  it('finds no order for a name no customer has', async () => {
    const seen: string[] = []
    expect(await searchOrders(shop(seen), token, { name: 'Anna Schmidt' })).toEqual([])
    expect(seen.some(q => q.startsWith('orders'))).toBe(false)
    // A first name alone is no family name.
    expect(await searchOrders(shop(), token, { name: 'Jonas' })).toEqual([])
  })
  it('drops an order a name search returns for another name', async () => {
    expect(nameFits('Jonas Weber', orders[0]!)).toBe(false)
    expect(nameFits('Jonas Weber', orders[1]!)).toBe(true)
    // The shipping name counts too.
    expect(nameFits('Anna Keller', orderOf(people[1]!, '#8002', 'Anna Keller'))).toBe(true)
    // One letter off only from five letters on.
    expect(nameFits('Mike Brenan', orders[2]!)).toBe(true)
    expect(
      nameFits('Ann Lee', order({ customer: null, shippingAddress: { ...order().shippingAddress!, name: 'Ann Leo' } })),
    ).toBe(false)
  })
  it('keeps the order number when the name does not fit', async () => {
    const found = await searchOrders(
      {
        findCustomers: async () => [],
        findOrders: async (_t: unknown, q: string) => (q.startsWith('(name:') ? [orders[0]!] : []),
      } as unknown as ShopifyStore,
      token,
      { orderNumber: '2002', name: 'Jonas Weber' },
    )
    expect(numbers(found)).toEqual(['#2002'])
  })
})