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: Connect again for a store that has not granted read_all_orders yet (PR 2081)

Tim Gutberlet045e7fdd7a24
diff --git a/apps/api/src/shopify-setup.ts b/apps/api/src/shopify-setup.ts
index 638c613f..50ac373e 100644
--- a/apps/api/src/shopify-setup.ts
+++ b/apps/api/src/shopify-setup.ts
@@ -24,6 +24,7 @@ import {
import { shopDomain, verifyShopifyQuery } from '@linedesk/connectors'
import {
app_connections,
+ app_credentials,
app_setup_requests,
member,
organization,
@@ -118,12 +119,32 @@ async function appStoreListing(tx: Tx, workspaceId: string): Promise<string | nu
return (await hasOwnApp(tx, workspaceId)) ? null : url
}
+/** A scope the app asks for now that a store connected before may not have granted yet (LIN-899). */
+const NEWER_SCOPES = ['read_all_orders'] as const
+
+/**
+ * Whether the workspace's connected store has not yet granted a scope the app asks for now: Integrations › Shopify then
+ * offers Connect again, which keeps the connection and its settings and only asks Shopify for the new permission. A
+ * grant without scopes named (an older row) is not flagged.
+ */
+async function newPermissionWaiting(tx: Tx, workspaceId: string): Promise<boolean> {
+ const [row] = await tx
+ .select({ scope: app_credentials.scope })
+ .from(app_credentials)
+ .innerJoin(app_connections, eq(app_connections.id, app_credentials.connection_id))
+ .where(and(eq(app_connections.workspace_id, workspaceId), eq(app_connections.provider, 'shopify')))
+ if (!row?.scope) return false
+ const granted = row.scope.split(/[\s,]+/)
+ return NEWER_SCOPES.some(scope => !granted.includes(scope))
+}
+
async function statusData(tx: Tx, workspaceId: string): Promise<ShopifySetupStatusData> {
const row = await openRequest(tx, workspaceId)
const request = row ? shown(row) : null
+ const newPermission = (await newPermissionWaiting(tx, workspaceId)) ? { newPermission: true as const } : {}
const appStoreUrl = await appStoreListing(tx, workspaceId)
- if (appStoreUrl) return { way: 'app_store', request, appStoreUrl }
- return { way: (await shopifyConnectOpen(tx, workspaceId)) ? 'connect' : 'request', request }
+ if (appStoreUrl) return { way: 'app_store', request, appStoreUrl, ...newPermission }
+ return { way: (await shopifyConnectOpen(tx, workspaceId)) ? 'connect' : 'request', request, ...newPermission }
}
/** The connect of this store finished: the workspace's open request for it is done (app.connectFinish). */
diff --git a/apps/api/test/shopify-setup.test.ts b/apps/api/test/shopify-setup.test.ts
index 1994bde2..ca912aa5 100644
--- a/apps/api/test/shopify-setup.test.ts
+++ b/apps/api/test/shopify-setup.test.ts
@@ -6,7 +6,7 @@
import { createHmac } from 'node:crypto'
import { actions, REDACTED, rolePermissions } from '@linedesk/actions'
import { AppError, type AppOAuth } from '@linedesk/connectors'
-import { app_setup_requests, commands, provider_settings, type Tx, user } from '@linedesk/db'
+import { app_connections, app_setup_requests, commands, provider_settings, type Tx, user } from '@linedesk/db'
import { and, eq, isNull } from 'drizzle-orm'
import { afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { type AppServices, workspaceAppKeys } from '../src/app-connections.ts'
@@ -218,12 +218,16 @@ describe('connected and failed', () => {
scopes: [],
authorizeUrl: ({ state }: { state: string }) => `https://${SHOP}/admin/oauth/authorize?state=${state}`,
exchangeCode: async ({ code }: { code: string }) => {
- if (code !== 'good-code') throw new AppError('shopify', 'auth', 'bad code')
+ if (code !== 'good-code' && code !== 'all-orders-code') throw new AppError('shopify', 'auth', 'bad code')
return {
accessToken: 'shpat_1',
refreshToken: 'shpat_1',
expiresAt: null,
- scope: 'write_customers,write_orders,read_products',
+ // A store connected before the app asked for read_all_orders grants the older scopes only.
+ scope:
+ code === 'all-orders-code'
+ ? 'write_customers,write_orders,read_all_orders,read_products'
+ : 'write_customers,write_orders,read_products',
account: { id: SHOP, name: SHOP },
}
},
@@ -255,6 +259,24 @@ describe('connected and failed', () => {
await run('app.connectFinish', { app: 'shopify', state, code: 'good-code' })
const [row] = await tx.select().from(app_setup_requests).where(eq(app_setup_requests.workspace_id, ws.id))
expect(row?.status).toBe('connected')
+ // Connected without read_all_orders: the page offers Connect again for the new permission (LIN-899).
+ expect((await run('shopify.setupStatus', {})).data).toEqual({
+ way: 'connect',
+ request: null,
+ newPermission: true,
+ })
+ const [before] = await tx.select().from(app_connections).where(eq(app_connections.workspace_id, ws.id))
+ await tx
+ .update(app_connections)
+ .set({ settings: { verify_postcode: true } })
+ .where(eq(app_connections.id, before!.id))
+ // Connect again with the store: Shopify grants the new scope; the same connection and its settings stay.
+ const again = await run('app.connectStart', { app: 'shopify', shop: SHOP })
+ const againState = new URL(again.data!.url as string).searchParams.get('state')!
+ await run('app.connectFinish', { app: 'shopify', state: againState, code: 'all-orders-code' })
+ const [after] = await tx.select().from(app_connections).where(eq(app_connections.workspace_id, ws.id))
+ expect(after?.id).toBe(before!.id)
+ expect(after?.settings).toEqual({ verify_postcode: true })
expect((await run('shopify.setupStatus', {})).data).toEqual({ way: 'connect', request: null })
// A connected store keeps its app: a new request would replace the keys its webhooks are signed with.
await expect(run('shopify.requestSetup', { shop: 'another-store' })).rejects.toMatchObject({
diff --git a/apps/web/src/integrations/ConnectedApp.tsx b/apps/web/src/integrations/ConnectedApp.tsx
index 906d2fb9..b46e95da 100644
--- a/apps/web/src/integrations/ConnectedApp.tsx
+++ b/apps/web/src/integrations/ConnectedApp.tsx
@@ -37,7 +37,7 @@ import { Loading, SkeletonList, useLoadState } from '../ui/LoadStates.tsx'
import { List, ListEmpty, ListRow } from '../ui/list.tsx'
import { SettingRow } from '../ui/SettingRow.tsx'
import { appConnectErrorKey, appConnectResult, appPushErrorKey, appSettingsWith, nameKey } from './catalog.ts'
-import { SHOPIFY_SETUP, ShopifyNotConnected, shopToConnect, withoutConnect } from './ShopifySetup.tsx'
+import { loadShopifySetup, SHOPIFY_SETUP, ShopifyNotConnected, shopToConnect, withoutConnect } from './ShopifySetup.tsx'
type Props = {
app: ConnectableApp
@@ -154,6 +154,12 @@ function useOpenShop(app: ConnectableApp) {
return shop
}
+/** Whether a connected Shopify store has yet to grant a permission the app asks for now (shopify.setupStatus). */
+function useShopifyNewPermission(app: ConnectableApp): boolean {
+ const setup = useQuery(app === 'shopify' ? SHOPIFY_SETUP : null, loadShopifySetup)
+ return setup.data?.newPermission === true
+}
+
/** The `code` an action's rejection carries (settings-api.ts), which the page words itself. */
const codeOf = (e: unknown) => (e as { code?: unknown }).code
@@ -221,6 +227,8 @@ function Connection({ app, connection, canEdit, toast }: Props & { connection: A
/** Disconnect asks once in place (click again), like revoking a key: no browser dialog. */
const [confirming, setConfirming] = useState(false)
const attention = connection.status === 'needs_attention'
+ // A store connected before the app asked for a newer permission (orders older than 60 days): Connect again adds it.
+ const newPermission = useShopifyNewPermission(app)
async function disconnect() {
if (!confirming) return setConfirming(true)
@@ -243,11 +251,13 @@ function Connection({ app, connection, canEdit, toast }: Props & { connection: A
? connection.error_code
? t(appPushErrorKey(connection.error_code, app), { name })
: t('settings.integrations.app.attentionFallback', { name })
- : connection.last_push_at
- ? t('settings.integrations.app.lastSent', {
- when: format.dateTime(new Date(connection.last_push_at), { dateStyle: 'medium', timeStyle: 'short' }),
- })
- : t('settings.integrations.app.noneSent')
+ : newPermission
+ ? t('settings.integrations.app.shopify.newPermission')
+ : connection.last_push_at
+ ? t('settings.integrations.app.lastSent', {
+ when: format.dateTime(new Date(connection.last_push_at), { dateStyle: 'medium', timeStyle: 'short' }),
+ })
+ : t('settings.integrations.app.noneSent')
return (
<List label={t('settings.integrations.app.title')}>
@@ -277,7 +287,7 @@ function Connection({ app, connection, canEdit, toast }: Props & { connection: A
actions={
canEdit && (
<>
- {attention && (
+ {(attention || newPermission) && (
<Button
size="sm"
disabled={opening || busy}
diff --git a/apps/web/src/integrations/ShopifySetup.tsx b/apps/web/src/integrations/ShopifySetup.tsx
index 5c855392..cff026f7 100644
--- a/apps/web/src/integrations/ShopifySetup.tsx
+++ b/apps/web/src/integrations/ShopifySetup.tsx
@@ -15,7 +15,7 @@ import { Button, Note } from '../ui/kit.tsx'
import { nameKey } from './catalog.ts'
export const SHOPIFY_SETUP = 'shopify.setupStatus'
-const loadSetup = () => readAction<ShopifySetupStatusData>('shopify.setupStatus')
+export const loadShopifySetup = () => readAction<ShopifySetupStatusData>('shopify.setupStatus')
/** The store the installed app opened with (`#integrations/shopify?connect=<shop>`), or null. */
export function shopToConnect(hash: string): string | null {
@@ -50,7 +50,7 @@ type Props = {
export function ShopifyNotConnected({ canEdit, toast, connect, opening, openShop }: Props) {
const t = useT()
- const setup = useQuery(SHOPIFY_SETUP, loadSetup)
+ const setup = useQuery(SHOPIFY_SETUP, loadShopifySetup)
const [asking, setAsking] = useState(false)
const started = useRef(false)
const data = setup.data
diff --git a/packages/actions/src/shopify-setup.ts b/packages/actions/src/shopify-setup.ts
index 9ab8f7f5..78a0a00b 100644
--- a/packages/actions/src/shopify-setup.ts
+++ b/packages/actions/src/shopify-setup.ts
@@ -40,13 +40,15 @@ export type ShopifySetupStatusData = {
way: 'connect' | 'request' | 'app_store'
request: ShopifySetupRequest | null
appStoreUrl?: string
+ /** The connected store has not yet granted a scope the app asks for now (read_all_orders): Connect again asks for it. */
+ newPermission?: true
}
export const shopifySetupStatus = defineAction({
name: 'shopify.setupStatus',
// i18n-ignore: API and MCP docs for agents and developers, not shown in the app
description:
- "How the workspace connects Shopify: `way` is `connect` (Connect opens Shopify's consent page) or `request` (the store's own app must be set up first, with shopify.requestSetup), and the open setup request with its status (requested, ready with the install link, failed).",
+ "How the workspace connects Shopify: `way` is `connect` (Connect opens Shopify's consent page) or `request` (the store's own app must be set up first, with shopify.requestSetup), and the open setup request with its status (requested, ready with the install link, failed). `newPermission: true` when the connected store has not yet granted a permission the app asks for now (orders older than 60 days): app.connectStart with the store, then the store's OK, adds it and keeps the connection.",
input: z.object({}),
permission: 'call:read',
readOnly: true,
diff --git a/packages/i18n/locales/en/settings.json b/packages/i18n/locales/en/settings.json
index 95adf8a0..2541ffd3 100644
--- a/packages/i18n/locales/en/settings.json
+++ b/packages/i18n/locales/en/settings.json
@@ -1055,6 +1055,7 @@
"integrations.app.shopify.help": "During calls, the assistant finds the caller’s orders and your products in your Shopify store. After every call, Linedesk adds a note with the summary and the next steps to the caller’s Shopify customer.",
"integrations.app.shopify.lastCheck": "At least one check stays ticked.",
"integrations.app.shopify.lastCheckTip": "Tick another check first: at least one stays ticked",
+ "integrations.app.shopify.newPermission": "Click Connect again to also find orders older than 60 days.",
"integrations.app.shopify.notConnected": "During calls, the assistant finds the caller’s orders and your products. Every call goes to the customer as a note. Shopify asks you to sign in and pick your store.",
"integrations.app.shopify.pushError.noCallerId": "The caller has no number or email to find or add a customer.",
"integrations.app.shopify.pushError.noContact": "Not sent: no Shopify customer matched the caller, and adding new callers is off.",