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.

Shopify calls: search names through the customer's first and last name, keep only matching orders (PR 2058)

Tim Gutberletcbe30d770fff
diff --git a/apps/api/src/shopify-calls.test.ts b/apps/api/src/shopify-calls.test.ts
index 9392e8ed..6b0164bd 100644
--- a/apps/api/src/shopify-calls.test.ts
+++ b/apps/api/src/shopify-calls.test.ts
@@ -2,6 +2,7 @@ import type { ShopifyOrder, ShopifyStore } from '@linedesk/connectors'
import { describe, expect, it } from 'vitest'
import {
checkProof,
+ nameFits,
nameQueries,
orderView,
phoneForSearch,
@@ -78,7 +79,8 @@ describe('finding orders', () => {
const store = (orders: ShopifyOrder[], seen: string[] = []) =>
({
findCustomers: async (_t: unknown, q: string) => (
- seen.push(`customers ${q}`), q.includes('+1503') ? [{ id: 'gid://shopify/Customer/7' }] : []
+ 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
@@ -105,24 +107,28 @@ describe('finding orders', () => {
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('orders "O\\"Brien" AND "OR" AND "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 () => [],
+ 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 "Mike" AND "Brenan"', '(name:"#1001" OR name:"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', async () => {
+ it('falls back from the full name to the family name and its first letters, all on the customer', async () => {
const seen: string[] = []
- await searchOrders(store([], seen), token, { name: 'Mike Brenan' })
- expect(seen).toEqual(['orders "Mike" AND "Brenan"', 'orders "Brenan"', 'orders bren*'])
+ 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[] = []
@@ -199,9 +205,138 @@ describe('phoneForSearch', () => {
})
describe('nameQueries', () => {
- it('searches every word, then the family name, then its first letters', () => {
- expect(nameQueries('Michael Brennan')).toEqual(['"Michael" AND "Brennan"', '"Brennan"', 'bren*'])
- expect(nameQueries('José Núñez')).toEqual(['"José" AND "Núñez"', '"Núñez"', 'nune*'])
- expect(nameQueries('Lee')).toEqual(['"Lee"'])
+ 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'])
})
})
diff --git a/apps/api/src/shopify-calls.ts b/apps/api/src/shopify-calls.ts
index ef694dc2..08b197cc 100644
--- a/apps/api/src/shopify-calls.ts
+++ b/apps/api/src/shopify-calls.ts
@@ -241,32 +241,109 @@ export function phoneForSearch(spoken: string, callerNumber?: string | null): st
return digits
}
+/** Words that are a title, not part of the name ("Mr Weber", "Frau Dr. Weber"). */
+const TITLES = new Set([
+ 'mr',
+ 'mrs',
+ 'ms',
+ 'miss',
+ 'mx',
+ 'mister',
+ 'missus',
+ 'sir',
+ 'madam',
+ 'dr',
+ 'prof',
+ 'herr',
+ 'frau',
+])
+
+/** A word of a name as compared: plain letters; null for a title or an initial ("J."). */
+const nameWord = (word: string) => {
+ const w = plain(word)[0]
+ return w && !TITLES.has(w) ? w : null
+}
+
+/** The name as the caller said it, without titles and initials: the first names (null: none) and the family name. */
+function nameParts(name: string): { first: string | null; family: string } | null {
+ const words = name.split(/\s+/).filter(word => nameWord(word))
+ if (words.length === 0) return null
+ return { first: words.length > 1 ? words.slice(0, -1).join(' ') : null, family: words.at(-1)! }
+}
+
+/** Whether two words differ in at most one letter (one added, left out or changed). */
+function oneEditApart(a: string, b: string): boolean {
+ if (Math.abs(a.length - b.length) > 1) return false
+ let i = 0
+ while (i < a.length && i < b.length && a[i] === b[i]) i++
+ return a.slice(i + 1) === b.slice(i + 1) || a.slice(i + 1) === b.slice(i) || a.slice(i) === b.slice(i + 1)
+}
+
+/**
+ * Whether one of these names has the family name the caller said or, from five letters on, one that differs in one
+ * letter ("Brenan" as speech recognition heard Brennan). Only the family name counts: speech recognition spells first
+ * names loosely, and a first name never makes up for another family name.
+ */
+function familyFits(given: string, names: (string | null | undefined)[]): boolean {
+ const said = given
+ .split(/\s+/)
+ .map(nameWord)
+ .filter((w): w is string => !!w)
+ .at(-1)
+ if (!said) return false
+ return names.some(name => {
+ const family = plain(name ?? '').at(-1)
+ return !!family && (family === said || (said.length >= 5 && oneEditApart(family, said)))
+ })
+}
+
+/** Whether an order a name search found belongs to that name (its customer or its shipping name); else it is dropped. */
+export const nameFits = (given: string, order: ShopifyOrder) =>
+ familyFits(given, [order.customer?.name, order.shippingAddress?.name])
+
/**
- * The searches for a name, most exact first: every word (each quoted: as one phrase "Pat Guest" finds nothing at
- * Shopify), then the family name alone ("Michael Brennan" for Mike Brennan's orders), then its first four letters
- * ("Brenan" as speech recognition heard Brennan). Reads need no check, so a near match is fine: the assistant asks
- * which order the caller means.
+ * The customer searches for a name, most exact first: the first and the family name, then the family name alone
+ * ("Michael Brennan" for Mike Brennan), then its first four letters ("Brenan" as speech recognition heard Brennan).
+ * Only field searches: Shopify stems free text ("Weber" finds every order from the web shop), so a free-text first and
+ * family name found the order of another customer with the same first name (LIN-899). One word is a family name,
+ * never a first name.
*/
export function nameQueries(name: string): string[] {
- const words = name.split(/\s+/).filter(Boolean)
- if (words.length === 0) return []
- const queries = [words.map(quoteTerm).join(' AND ')]
- const family = words.at(-1)!
- if (words.length > 1) queries.push(quoteTerm(family))
- const stem = plain(family)
+ const parts = nameParts(name)
+ if (!parts) return []
+ const family = `last_name:${quoteTerm(parts.family)}`
+ const queries = parts.first ? [`first_name:${quoteTerm(parts.first)} AND ${family}`, family] : [family]
+ const stem = plain(parts.family)
.join('')
.replace(/[^a-z]/g, '')
- if (stem.length >= 5) queries.push(`${stem.slice(0, 4)}*`)
- return [...new Set(queries)]
+ if (stem.length >= 5) queries.push(`last_name:${stem.slice(0, 4)}*`)
+ return queries
+}
+
+/** At most this many customers one name brings into the order search. */
+const CUSTOMERS_PER_NAME = 5
+
+/** The customers with the name the caller said: the first customer search that finds one whose family name fits. */
+async function customersNamed(store: ShopifyStore, token: TokenSource, name: string) {
+ for (const query of nameQueries(name)) {
+ const found = await store.findCustomers(token, query, CUSTOMERS_PER_NAME)
+ const named = found.filter(c => familyFits(name, [c.name]))
+ if (named.length) return named
+ }
+ return []
}
+const byCustomers = (customers: { id: string }[]) =>
+ `(${customers.map(c => `customer_id:${gidNumber(c.id)}`).join(' OR ')})`
+
/** At most this many searches at the store for one lookup. */
const SEARCHES_PER_LOOKUP = 6
/**
* The orders matching what the caller said, newest first. Everything they said together first; when that finds
* nothing, each detail alone (order number, email, phone, name, in that order), so one detail the speech recognition
- * got wrong does not hide the order. A postcode narrows the others down; alone it finds none.
+ * got wrong does not hide the order. A postcode narrows the others down; alone it finds none. A phone number or a
+ * name finds the customers first, then their orders; an order a name search returns for another name is dropped.
*/
export async function searchOrders(
store: ShopifyStore,
@@ -276,21 +353,24 @@ export async function searchOrders(
): Promise<ShopifyOrder[] | null> {
// Each detail the caller gave, with its searches, most exact first.
const details: string[][] = []
+ // A phone number or name that no customer has: nothing found (not: nothing to search by).
+ let noCustomer = false
const digits = search.orderNumber ? orderDigits(search.orderNumber) : null
if (digits) details.push([`(name:${quoteTerm(`#${digits}`)} OR name:${quoteTerm(digits)})`])
if (search.email?.trim()) details.push([`email:${quoteTerm(search.email.trim())}`])
const phone = search.phone ? phoneForSearch(search.phone, callerNumber) : null
- let phoneKnown = false
if (phone) {
// An order keeps the customer's number on the customer: find them by it, then their orders.
const customers = await store.findCustomers(token, `phone:${quoteTerm(phone)}`, 3)
- if (customers.length) {
- phoneKnown = true
- details.push([`(${customers.map(c => `customer_id:${gidNumber(c.id)}`).join(' OR ')})`])
- }
+ if (customers.length) details.push([byCustomers(customers)])
+ else noCustomer = true
}
- if (search.name?.trim()) details.push(nameQueries(search.name.trim()))
- if (details.length === 0) return phone && !phoneKnown ? [] : null
+ const name = search.name?.trim() || null
+ const named = name ? await customersNamed(store, token, name) : []
+ const byName = named.length ? byCustomers(named) : null
+ if (byName) details.push([byName])
+ else if (name) noCustomer = true
+ if (details.length === 0) return noCustomer ? [] : null
const status = search.status && search.status !== 'any' ? STATUS_QUERY[search.status] : undefined
const first = search.postcode ? 20 : ORDERS_SHOWN
const tried = new Set<string>()
@@ -298,7 +378,8 @@ export async function searchOrders(
const query = [...terms, status].filter(Boolean).join(' AND ')
if (tried.has(query) || tried.size >= SEARCHES_PER_LOOKUP) return []
tried.add(query)
- const found = await store.findOrders(token, query, first)
+ let found = await store.findOrders(token, query, first)
+ if (name && byName && terms.includes(byName)) found = found.filter(o => nameFits(name, o))
return search.postcode ? found.filter(o => samePostcode(o.shippingAddress?.zip, search.postcode)) : found
}
const together = await run(details.map(d => d[0]!))