From 222a1df9e223661734bf609c8a36a175d893661e Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 10 Oct 2026 17:47:08 +0000 Subject: [PATCH] Full IAP catalog: non-renewing products, per-platform availability, catalog diff (cross-store parity report) --- cli/apple/iap.ts | 8 ++- cli/catalog.ts | 110 +++++++++++++++++++++++++++++++++ cli/lib/catalog.ts | 141 +++++++++++++++++++++++++++++++++++++++++++ cli/play/products.ts | 6 +- 4 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 cli/catalog.ts create mode 100644 cli/lib/catalog.ts diff --git a/cli/apple/iap.ts b/cli/apple/iap.ts index 659c0038..f11765f5 100644 --- a/cli/apple/iap.ts +++ b/cli/apple/iap.ts @@ -4,6 +4,7 @@ // storebound apple iap [--dry] [--only id1,id2] // Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version, // from the IAP page in the web UI (see the store-iap-setup skill). +import { sellsOn } from '../lib/config'; import { APPLE_IAP_LIMITS } from '../lib/copy'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; @@ -11,11 +12,14 @@ import { done, log, step } from '../lib/log'; import { appleTerritory, nearestPrices, samePrice } from '../lib/money'; import { ascClient, type J } from './asc'; +/** Product type -> InAppPurchaseType (POST /v2/inAppPurchases). */ +export const APPLE_IAP_TYPE = { consumable: 'CONSUMABLE', non_consumable: 'NON_CONSUMABLE', non_renewing: 'NON_RENEWING_SUBSCRIPTION' } as const; + export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); const only = ctx.args.list('only'); - const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id)); + const products = need(config.products, 'products').filter(p => (!only.length || only.includes(p.id)) && sellsOn(config, p, 'apple')); const dry = ctx.args.has('dry'); const c = await ascClient(root, bundleId, config.apple?.appId); const appId = await c.app(); @@ -39,7 +43,7 @@ export async function run(ctx: Ctx): Promise { if (!id) { const first = Object.values(p.listings)[0]!; id = (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases', - attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: p.type === 'consumable' ? 'CONSUMABLE' : 'NON_CONSUMABLE', + attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: APPLE_IAP_TYPE[p.type], familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) }, relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id; log('apple', `${tag}: created`); diff --git a/cli/catalog.ts b/cli/catalog.ts new file mode 100644 index 00000000..3de5fff5 --- /dev/null +++ b/cli/catalog.ts @@ -0,0 +1,110 @@ +// Cross-store catalog parity report (read-only on both stores): +// storebound catalog diff [--store apple|play] [--threshold 10] [--json] +// One product definition (products + subscriptions in storebound.config.ts) against what exists on App Store Connect +// and Google Play: missing and extra items, kind / billing period / level mismatches, base (US) and override prices, +// localizations, offers, and a per-region price comparison between the stores (same currency, difference over +// --threshold percent). Exit 1 when an item is missing or mismatched; price differences between the stores are +// information (stores round to their own price tiers). Pure rules: lib/catalog.ts. +import { appleCurrent, pages, playProduct } from './prices'; +import { ascClient, type J } from './apple/asc'; +import { type CatalogRow, catalogDiff, fromApplePeriod, fromAppleType, regionOf, type StoreItem, wantedCatalog } from './lib/catalog'; +import type { Ctx } from './lib/ctx'; +import { done, log } from './lib/log'; +import { fromMoney } from './lib/money'; +import { listOneTimeProducts } from './play/products'; +import { playClient } from './play/client'; +import { appleSubPrices, basePlanId } from './lib/subscriptions'; +import { textTable } from './lib/table'; + +const TAG = 'catalog'; + +async function appleItems(ctx: Ctx): Promise { + const { config, root } = ctx.loaded; + const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId); + const appId = await c.app(); + const out: StoreItem[] = []; + const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`); + for (const [i, p] of iaps.entries()) { + log(TAG, `apple ${i + 1}/${iaps.length} ${p.attributes.productId}`); + const locales = (await c.all(`/v2/inAppPurchases/${p.id}/inAppPurchaseLocalizations?limit=50`)).map((l: J) => l.attributes.locale); + const hasSchedule = !!(await c.maybe(`/v2/inAppPurchases/${p.id}/iapPriceSchedule`))?.data; + const today = new Date().toISOString().slice(0, 10); + // today's price per territory: entries that started (or have no start), the latest start wins; manual over automatic + const rows = hasSchedule ? (await appleCurrent(c, p.id, p.attributes.productId, true)).rows.filter(r => (r.startDate ?? '') <= today) + .sort((x, y) => (x.kind === 'auto' ? 0 : 1) - (y.kind === 'auto' ? 0 : 1) || (x.startDate ?? '').localeCompare(y.startDate ?? '')) : []; + const byRegion = new Map(rows.map(r => [r.region, r] as const)); + out.push({ id: p.attributes.productId, kind: fromAppleType(p.attributes.inAppPurchaseType), state: p.attributes.state, locales, + prices: [...byRegion.values()].map(r => ({ region: r.region, currency: r.currency, price: r.price })) }); + } + for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)) { + for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) { + log(TAG, `apple subscription ${s.attributes.productId}`); + const locales = (await c.all(`/v1/subscriptions/${s.id}/subscriptionLocalizations?limit=200`)).map((l: J) => l.attributes.locale); + const prices = appleSubPrices(await pages(c, `/v1/subscriptions/${s.id}/prices?include=subscriptionPricePoint,territory&limit=200`)).filter(p => !p.startDate); + const intro = (await c.asc('GET', `/v1/subscriptions/${s.id}/introductoryOffers?limit=1`)).data?.length ? ['intro'] : []; + const promos = (await c.all(`/v1/subscriptions/${s.id}/promotionalOffers?limit=200`)).map((o: J) => o.attributes.offerCode as string); + const codes = (await c.all(`/v1/subscriptions/${s.id}/offerCodes?limit=200`)).map((o: J) => `code:${o.attributes.name}`); + out.push({ id: s.attributes.productId, kind: 'subscription', state: s.attributes.state, period: fromApplePeriod(s.attributes.subscriptionPeriod), + level: s.attributes.groupLevel, locales, prices: prices.map(p => ({ region: regionOf(p.territory), currency: p.currency ?? '', price: p.price })), + offers: [...intro, ...promos, ...codes] }); + } + } + return out; +} + +async function playItems(ctx: Ctx): Promise { + const { config, root } = ctx.loaded; + const play = await playClient(root, config.play!.packageName); + const out: StoreItem[] = []; + for (const { productId } of await listOneTimeProducts(play)) { + log(TAG, `play ${productId}`); + const p = await playProduct(play, productId); + if (!p) continue; + const opt = p.purchaseOptions?.find(o => o.purchaseOptionId === 'buy') ?? p.purchaseOptions?.[0]; + out.push({ id: productId, kind: 'one_time', state: opt?.state, locales: ((p.listings as { languageCode: string }[] | undefined) ?? []).map(l => l.languageCode), + prices: (opt?.regionalPricingAndAvailabilityConfigs ?? []).filter(r => r.price && r.availability !== 'NO_LONGER_AVAILABLE').map(r => ({ region: r.regionCode, currency: r.price!.currencyCode, price: fromMoney(r.price!) })) }); + } + let page = ''; + do { + const r = await play.call<{ subscriptions?: J[]; nextPageToken?: string }>('GET', `${play.API}/subscriptions?pageSize=100${page ? '&pageToken=' + page : ''}`); + for (const s of r.subscriptions ?? []) { + log(TAG, `play subscription ${s.productId}`); + const subCfg = config.subscriptions?.flatMap(g => g.subscriptions).find(x => x.id === s.productId); + const bpId = subCfg ? basePlanId(subCfg) : undefined; + const plans: J[] = s.basePlans ?? []; + const bp = plans.find(b => b.basePlanId === bpId) ?? plans.find(b => b.autoRenewingBasePlanType?.billingPeriodDuration === subCfg?.period) ?? plans[0]; + const offers = bp ? ((await play.call<{ subscriptionOffers?: { offerId: string }[] }>('GET', `${play.API}/subscriptions/${encodeURIComponent(s.productId)}/basePlans/${bp.basePlanId}/offers`)).subscriptionOffers ?? []).map(o => o.offerId) : []; + out.push({ id: s.productId, kind: 'subscription', state: bp?.state, period: bp?.autoRenewingBasePlanType?.billingPeriodDuration ?? bp?.prepaidBasePlanType?.billingPeriodDuration, + locales: (s.listings ?? []).map((l: J) => l.languageCode), + prices: (bp?.regionalConfigs ?? []).filter((x: J) => x.price).map((x: J) => ({ region: x.regionCode, currency: x.price.currencyCode, price: fromMoney(x.price) })), offers }); + } + page = r.nextPageToken ?? ''; + } while (page); + return out; +} + +export async function run(ctx: Ctx): Promise { + const { config } = ctx.loaded; + const a = ctx.args; + if (a._[0] !== 'diff') throw new Error('usage: storebound catalog diff [--store apple|play] [--threshold 10] [--json]'); + const store = a.get('store'); + if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play'); + const want = wantedCatalog(config); + const apple = (!store || store === 'apple') && config.apple ? await appleItems(ctx) : null; + const play = (!store || store === 'play') && config.play ? await playItems(ctx) : null; + const { rows, parity } = catalogDiff(want, { apple, play }, { threshold: a.num('threshold', 10) / 100 }); + const errors = rows.filter(r => r.level === 'error').length; + if (a.has('json')) console.log(JSON.stringify({ errors, rows, parity }, null, 2)); + else { + console.log(formatRows(rows)); + if (parity.length) console.log(`\nprice differences between the stores (same currency, over ${a.num('threshold', 10)} %):\n` + + textTable(['product', 'region', 'currency', 'apple', 'play', 'diff %'], parity.map(p => [p.id, p.region, p.currency, p.apple.toFixed(2), p.play.toFixed(2), p.diffPct.toFixed(1)]))); + } + done(TAG, `${want.length} catalog items: ${errors} mismatch(es), ${rows.filter(r => r.level === 'warn').length} warning(s), ${parity.length} price difference(s) between the stores`); + if (errors) process.exitCode = 1; +} + +export function formatRows(rows: CatalogRow[]): string { + const tag = { error: 'ERROR', warn: 'warn ', ok: 'ok ' } as const; + return rows.map(r => `${tag[r.level]} [${r.store}] ${r.id}: ${r.msg}`).join('\n') || 'no catalog items'; +} diff --git a/cli/lib/catalog.ts b/cli/lib/catalog.ts new file mode 100644 index 00000000..333b82c7 --- /dev/null +++ b/cli/lib/catalog.ts @@ -0,0 +1,141 @@ +// Cross-store catalog parity, as pure parts: one product definition (products + subscriptions in the config) against +// what exists on the App Store and on Google Play. `storebound catalog diff` collects the store side (read-only) and +// prints these rows. Kinds compared: Apple CONSUMABLE / NON_CONSUMABLE / NON_RENEWING_SUBSCRIPTION / auto-renewable +// subscriptions; Play one-time products (every non-subscription kind) and subscriptions (base plan billing period). +import { type ShipConfig, playCodes, type ProductType, sellsOn, type Platform } from './config'; +import { ALPHA3 } from './money'; +import { allSubscriptions, offerId } from './subscriptions'; + +export type Kind = ProductType | 'subscription'; +export type Store = 'apple' | 'play'; + +/** One product as a store has it. Prices: what applies today, one per region (ISO alpha-2), in the local currency. */ +export interface StoreItem { + id: string; + /** Apple: the IAP type or subscription; Play: 'one_time' or 'subscription'. */ + kind: Kind | 'one_time'; + state?: string; + /** Subscriptions: ISO period (P1M ...); Apple level inside the group. */ + period?: string; + level?: number; + locales: string[]; + prices: { region: string; currency: string; price: number }[]; + /** Offer ids (Play offer ids; Apple: "intro" when there is an introductory offer, promotional offer codes, + * "code:" for offer code campaigns). */ + offers?: string[]; +} + +export interface WantItem { + id: string; + kind: Kind; + stores: Store[]; + period?: string; + level?: number; + usd: number; + overrides: { region: string; currency: string; price: number }[]; + locales: Record; + offers: Record; +} + +export interface CatalogRow { id: string; store: Store; level: 'error' | 'warn' | 'ok'; code: string; msg: string } +export interface ParityRow { id: string; region: string; currency: string; apple: number; play: number; diffPct: number } + +const APPLE_PERIOD: Record = { ONE_WEEK: 'P1W', ONE_MONTH: 'P1M', TWO_MONTHS: 'P2M', THREE_MONTHS: 'P3M', SIX_MONTHS: 'P6M', ONE_YEAR: 'P1Y' }; +const APPLE_KIND: Record = { CONSUMABLE: 'consumable', NON_CONSUMABLE: 'non_consumable', NON_RENEWING_SUBSCRIPTION: 'non_renewing' }; +/** App Store Connect subscriptionPeriod / inAppPurchaseType -> catalog values. */ +export const fromApplePeriod = (p: string | undefined): string | undefined => (p ? APPLE_PERIOD[p] ?? p : undefined); +export const fromAppleType = (t: string | undefined): Kind | 'one_time' => APPLE_KIND[t ?? ''] ?? 'one_time'; + +/** The config's catalog per store (products + subscriptions, `platforms` respected). */ +export function wantedCatalog(config: ShipConfig): WantItem[] { + const langs = config.languages; + const appleLoc = (ids: string[]) => ids.map(id => langs.find(l => l.id === id)?.apple).filter((x): x is string => !!x); + const playLoc = (ids: string[]) => ids.flatMap(id => { const l = langs.find(x => x.id === id); return l ? playCodes(l) : []; }); + const stores = (item: { platforms?: Platform[] }): Store[] => (['apple', 'play'] as const).filter(s => sellsOn(config, item, s)); + const out: WantItem[] = []; + for (const p of config.products ?? []) { + const ids = Object.keys(p.listings); + out.push({ id: p.id, kind: p.type, stores: stores(p), usd: p.usd, overrides: (p.overrides ?? []).map(o => ({ region: o.region, currency: o.currency, price: o.price })), + locales: { apple: appleLoc(ids), play: playLoc(ids) }, offers: { apple: [], play: [] } }); + } + for (const { sub } of allSubscriptions(config.subscriptions)) { + const ids = Object.keys(sub.listings); + out.push({ id: sub.id, kind: 'subscription', stores: stores(sub), period: sub.period, level: sub.level, usd: sub.usd, + overrides: (sub.overrides ?? []).map(o => ({ region: o.region, currency: o.currency, price: o.price })), + locales: { apple: appleLoc(ids), play: playLoc(ids) }, + offers: { + apple: [...(sub.intro ? ['intro'] : []), ...(sub.offers ?? []).map(o => o.id), ...(sub.offerCodes ?? []).map(o => `code:${o.name}`)], + play: [...(sub.intro ? [offerId(sub)] : []), ...(sub.offers ?? []).map(o => o.id)], + } }); + } + return out; +} + +const cents = (n: number) => Math.round(n * 100); +const fmt = (n: number) => (Math.round(n * 100) / 100).toFixed(2); + +/** + * Config vs both stores. `state.apple` / `state.play` null = that store was not read (no section / --store). Rows: + * missing (error), extra on the store (warn), kind / billing period (error), Apple level (warn), base price (US) and + * override regions (error), missing localizations and offers (warn). Parity: regions both stores price in the same + * currency, where the prices differ by more than `threshold` (default 10 %). + */ +export function catalogDiff(want: WantItem[], state: { apple: StoreItem[] | null; play: StoreItem[] | null }, o: { threshold?: number } = {}): { rows: CatalogRow[]; parity: ParityRow[] } { + const rows: CatalogRow[] = []; + const parity: ParityRow[] = []; + const add = (id: string, store: Store, level: CatalogRow['level'], code: string, msg: string) => rows.push({ id, store, level, code, msg }); + const threshold = o.threshold ?? 0.1; + for (const store of ['apple', 'play'] as const) { + const items = state[store]; + if (!items) continue; + const have = new Map(items.map(i => [i.id, i] as const)); + for (const w of want.filter(x => x.stores.includes(store))) { + const h = have.get(w.id); + if (!h) { add(w.id, store, 'error', 'missing', `not on ${store === 'apple' ? 'App Store Connect' : 'Google Play'} (storebound ${store} ${w.kind === 'subscription' ? 'subscriptions' : store === 'apple' ? 'iap' : 'products'})`); continue; } + const kindOk = store === 'play' ? (w.kind === 'subscription') === (h.kind === 'subscription') : h.kind === w.kind; + if (!kindOk) { add(w.id, store, 'error', 'kind', `${h.kind} on the store, ${w.kind} in the config (a product type cannot change: use a new id)`); continue; } + if (w.period && h.period && w.period !== h.period) add(w.id, store, 'error', 'period', `bills every ${h.period} on the store, ${w.period} in the config`); + if (store === 'apple' && w.level !== undefined && h.level !== undefined && w.level !== h.level) add(w.id, store, 'warn', 'level', `group level ${h.level} on the store, ${w.level} in the config`); + const price = new Map(h.prices.map(p => [p.region, p] as const)); + const us = price.get('US'); + if (!h.prices.length) add(w.id, store, 'error', 'price', 'no prices on the store'); + else if (!us) add(w.id, store, 'warn', 'price', 'no US price on the store'); + else if (cents(us.price) !== cents(w.usd)) add(w.id, store, 'error', 'price', `US ${fmt(us.price)} USD on the store, ${fmt(w.usd)} in the config`); + for (const ov of w.overrides) { + const p = price.get(ov.region); + if (!p) add(w.id, store, 'error', 'price', `${ov.region}: no price on the store, ${ov.price} ${ov.currency} in the config`); + else if (p.currency !== ov.currency || cents(p.price) !== cents(ov.price)) add(w.id, store, 'error', 'price', `${ov.region}: ${fmt(p.price)} ${p.currency} on the store, ${fmt(ov.price)} ${ov.currency} in the config`); + } + const missingLoc = w.locales[store].filter(l => !h.locales.includes(l)); + if (missingLoc.length) add(w.id, store, 'warn', 'locale', `no ${store === 'apple' ? 'localization' : 'listing'} for ${missingLoc.join(', ')}`); + const missingOffers = w.offers[store].filter(x => !(h.offers ?? []).includes(x)); + if (missingOffers.length) add(w.id, store, 'warn', 'offer', `offers missing: ${missingOffers.join(', ')}`); + if (!rows.some(r => r.id === w.id && r.store === store)) add(w.id, store, 'ok', 'ok', `${w.kind}${w.period ? ` ${w.period}` : ''}, ${h.prices.length} region prices${h.state ? `, ${h.state}` : ''}`); + } + const known = new Set(want.map(w => w.id)); + for (const h of items) if (!known.has(h.id)) add(h.id, store, 'warn', 'extra', `on the store but not in the config (${h.kind}${h.state ? `, ${h.state}` : ''})`); + } + if (state.apple && state.play) { + const a = new Map(state.apple.map(i => [i.id, i] as const)); + const p = new Map(state.play.map(i => [i.id, i] as const)); + for (const w of want) { + const ai = a.get(w.id), pi = p.get(w.id); + if (!ai || !pi) continue; + const pp = new Map(pi.prices.map(x => [x.region, x] as const)); + for (const ap of ai.prices) { + const q = pp.get(ap.region); + if (!q || q.currency !== ap.currency || !(ap.price > 0) || !(q.price > 0)) continue; + const diff = Math.abs(ap.price - q.price) / Math.max(ap.price, q.price); + if (diff > threshold) parity.push({ id: w.id, region: ap.region, currency: ap.currency, apple: ap.price, play: q.price, diffPct: Math.round(diff * 1000) / 10 }); + } + } + } + const rank = { error: 0, warn: 1, ok: 2 } as const; + rows.sort((x, y) => rank[x.level] - rank[y.level] || x.id.localeCompare(y.id) || x.store.localeCompare(y.store)); + parity.sort((x, y) => y.diffPct - x.diffPct || x.id.localeCompare(y.id) || x.region.localeCompare(y.region)); + return { rows, parity }; +} + +/** Apple territory (alpha-3) -> region (alpha-2). */ +const A2 = Object.fromEntries(Object.entries(ALPHA3).map(([a2, a3]) => [a3, a2])); +export const regionOf = (territory: string): string => A2[territory] ?? territory; diff --git a/cli/play/products.ts b/cli/play/products.ts index e87f5a07..d24681fb 100644 --- a/cli/play/products.ts +++ b/cli/play/products.ts @@ -4,7 +4,9 @@ // Per product: convertRegionPrices (USD base -> every region at local price points, plus regionsVersion), your // explicit overrides on top, PATCH ...?allowMissing=true (create or update), then activate the purchase option // (new options start as DRAFT) with purchaseOptions:batchUpdateStates. Idempotent. -import { playCodes } from '../lib/config'; +// Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it +// when the access ends). Products with `platforms` that leave out android are skipped. +import { playCodes, sellsOn } from '../lib/config'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; import { done, log, step, warn } from '../lib/log'; @@ -36,7 +38,7 @@ export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const pkg = need(config.play?.packageName, 'play.packageName'); const only = ctx.args.list('only'); - const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id)); + const products = need(config.products, 'products').filter(p => (!only.length || only.includes(p.id)) && sellsOn(config, p, 'play')); const dry = ctx.args.has('dry'); const play = await playClient(root, pkg); const existing = new Map((await listOneTimeProducts(play)).map(p => [p.productId, p]));