play products: price, region and activation changes of existing products ask first (diff, terminal confirmation or --yes; refused without a terminal and under serve unless a desktop owner action confirmed); new products and listing text unchanged; store-iap-setup skill and MCP description; tests

This commit is contained in:
CRTkafa 2026-10-11 08:47:28 +08:00
parent 52d1e379e3
commit 3af1b3e5f4
5 changed files with 139 additions and 33 deletions

View file

@ -15,6 +15,12 @@
called `:validate` before discarding it. The output says per language what would change. called `:validate` before discarding it. The output says per language what would change.
- `play products --dry` names what a run would change per product (listings added / changed / removed, regional - `play products --dry` names what a run would change per product (listings added / changed / removed, regional
prices old -> new, dropped regions, activation) instead of "update · 174 regions" for every existing product. prices old -> new, dropped regions, activation) instead of "update · 174 regions" for every existing product.
- `play products` asks before changing what an existing product costs or where it is sold (regional prices, the
other-regions price, dropped regions, activating a purchase option), the same way `play subscriptions` does: the
diff, then a terminal confirmation (or `--yes`). Without one (MCP, CI, serve without a desktop owner-action token)
those changes are skipped with a warning; new products and listing text still go through. `apple iap` and
`apple appinfo` only create a price schedule or availability where none exists, so they need no gate; price
changes on both stores stay with `prices import` (confirmation, the desktop Prices "Apply" owner action).
- `play status`, `play next-version-code`: the read-only edit goes through one helper that always deletes it and - `play status`, `play next-version-code`: the read-only edit goes through one helper that always deletes it and
warns when the delete fails; `next-version-code` counts distinct version codes (one code on two tracks is one). warns when the delete fails; `next-version-code` counts distinct version codes (one code on two tracks is one).

View file

@ -110,7 +110,7 @@ export const TOOLS: ToolDef[] = [
description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder (or an A/B variant folder). Slow (minutes): prefer the terminal with a log for many languages.', description: 'Replace icon, feature graphic and screenshots per Play language from the renders folder (or an A/B variant folder). Slow (minutes): prefer the terminal with a log for many languages.',
props: { only, variant }, args: i => [...opt('only', i.only), ...opt('variant', i.variant)] }, props: { only, variant }, args: i => [...opt('only', i.only), ...opt('variant', i.variant)] },
{ name: 'play_products', title: 'Sync Play one-time products', command: ['play', 'products'], write: true, network: true, idempotent: true, { name: 'play_products', title: 'Sync Play one-time products', command: ['play', 'products'], write: true, network: true, idempotent: true,
description: 'Create / update one-time products with regional prices and activate their purchase option.', description: 'Create one-time products with regional prices and activate them; update listing text of existing ones. dry_run shows per product what would change. Price, region or activation changes of existing products are the owner\'s (terminal confirmation): here they are skipped with a warning.',
props: { only }, args: i => opt('only', i.only) }, props: { only }, args: i => opt('only', i.only) },
{ name: 'play_subscriptions', title: 'Sync Play subscriptions', command: ['play', 'subscriptions'], write: true, network: true, idempotent: true, { name: 'play_subscriptions', title: 'Sync Play subscriptions', command: ['play', 'subscriptions'], write: true, network: true, idempotent: true,
description: 'Auto-renewable subscriptions on Google Play from the config: listings per language (title, description, benefits), one auto-renewing base plan with regional prices (convertRegionPrices + overrides + optional prices CSV), activation, and the introductory offer for new subscribers. dry_run prints the plan. Without a terminal it creates only what is new; price changes of existing base plans are an owner terminal run.', description: 'Auto-renewable subscriptions on Google Play from the config: listings per language (title, description, benefits), one auto-renewing base plan with regional prices (convertRegionPrices + overrides + optional prices CSV), activation, and the introductory offer for new subscribers. dry_run prints the plan. Without a terminal it creates only what is new; price changes of existing base plans are an owner terminal run.',

View file

@ -4,11 +4,15 @@
// Per product: convertRegionPrices (USD base -> every region at local price points, plus regionsVersion), your // 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 // explicit overrides on top, PATCH ...?allowMissing=true (create or update), then activate the purchase option
// (new options start as DRAFT) with purchaseOptions:batchUpdateStates. Idempotent. // (new options start as DRAFT) with purchaseOptions:batchUpdateStates. Idempotent.
// New products and listing text changes are written directly. Changes to what an EXISTING product costs or where it
// is sold (regional prices, the price for other regions, dropped regions, activating its purchase option) are shown
// as a diff first and need a confirmation: a terminal question (or --yes), or under the desktop app an owner action
// confirm token. Without one (MCP, CI, serve) those changes are skipped with a warning; listing changes still go.
// Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it // 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. // when the access ends). Products with `platforms` that leave out android are skipped.
import { playCodes, sellsOn } from '../lib/config'; import { playCodes, sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx'; import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx'; import { confirm, need } from '../lib/ctx';
import { done, log, step, warn } from '../lib/log'; import { done, log, step, warn } from '../lib/log';
import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money'; import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money';
import { playClient } from './client'; import { playClient } from './client';
@ -30,21 +34,25 @@ export interface Existing {
const money = (m?: PlayMoney): string => (m ? `${m.currencyCode} ${fromMoney(m).toFixed(2)}` : '-'); const money = (m?: PlayMoney): string => (m ? `${m.currencyCode} ${fromMoney(m).toFixed(2)}` : '-');
export interface ProductChange { text: string; /** price / region / activation change of an existing product: asks first */ owner: boolean }
/** /**
* What a run would change on one product, from the product Play has now (oneTimeProducts list) and the body the run * What a run would change on one product, from the product Play has now (oneTimeProducts list) and the body the run
* would PATCH. The PATCH replaces listings and purchase options, so a language on Play that is not in the config is * would PATCH. The PATCH replaces listings and purchase options, so a language on Play that is not in the config is
* removed. Prices are compared per region (currency and amount). Empty: nothing would change. Pure. * removed. Prices are compared per region (currency and amount). Empty: nothing would change. Pure.
*/ */
export function productChanges(cur: Existing | undefined, want: { listings: { languageCode: string; title: string; description: string }[]; regions: RegionConfig[]; newRegions: { usdPrice: Money; eurPrice: Money } }): string[] { export function productChanges(cur: Existing | undefined, want: { listings: { languageCode: string; title: string; description: string }[]; regions: RegionConfig[]; newRegions: { usdPrice: Money; eurPrice: Money } }): ProductChange[] {
if (!cur) return ['create']; if (!cur) return [{ text: 'create', owner: false }];
const out: string[] = []; const out: ProductChange[] = [];
const text = (t: string) => out.push({ text: t, owner: false });
const owner = (t: string) => out.push({ text: t, owner: true });
const have = new Map((cur.listings ?? []).map(l => [l.languageCode, l])); const have = new Map((cur.listings ?? []).map(l => [l.languageCode, l]));
const added = want.listings.filter(l => !have.has(l.languageCode)).map(l => l.languageCode); const added = want.listings.filter(l => !have.has(l.languageCode)).map(l => l.languageCode);
const changed = want.listings.filter(l => { const h = have.get(l.languageCode); return h && ((h.title ?? '') !== l.title || (h.description ?? '') !== l.description); }).map(l => l.languageCode); const changed = want.listings.filter(l => { const h = have.get(l.languageCode); return h && ((h.title ?? '') !== l.title || (h.description ?? '') !== l.description); }).map(l => l.languageCode);
const removed = [...have.keys()].filter(c => !want.listings.some(l => l.languageCode === c)); const removed = [...have.keys()].filter(c => !want.listings.some(l => l.languageCode === c));
if (added.length) out.push(`listings added: ${added.join(', ')}`); if (added.length) text(`listings added: ${added.join(', ')}`);
if (changed.length) out.push(`listings changed: ${changed.join(', ')}`); if (changed.length) text(`listings changed: ${changed.join(', ')}`);
if (removed.length) out.push(`listings removed: ${removed.join(', ')}`); if (removed.length) text(`listings removed: ${removed.join(', ')}`);
const opt = cur.purchaseOptions?.find(o => o.purchaseOptionId === OPTION); const opt = cur.purchaseOptions?.find(o => o.purchaseOptionId === OPTION);
const now = new Map((opt?.regionalPricingAndAvailabilityConfigs ?? []).map(r => [r.regionCode, r])); const now = new Map((opt?.regionalPricingAndAvailabilityConfigs ?? []).map(r => [r.regionCode, r]));
const prices = want.regions.flatMap(r => { const prices = want.regions.flatMap(r => {
@ -52,12 +60,12 @@ export function productChanges(cur: Existing | undefined, want: { listings: { la
return h && h.currencyCode === r.price.currencyCode && Math.round(fromMoney(h) * 100) === Math.round(fromMoney(r.price) * 100) ? [] : [`${r.regionCode} ${money(h)} -> ${money(r.price)}`]; return h && h.currencyCode === r.price.currencyCode && Math.round(fromMoney(h) * 100) === Math.round(fromMoney(r.price) * 100) ? [] : [`${r.regionCode} ${money(h)} -> ${money(r.price)}`];
}); });
const gone = [...now.keys()].filter(c => !want.regions.some(r => r.regionCode === c)); const gone = [...now.keys()].filter(c => !want.regions.some(r => r.regionCode === c));
if (prices.length) out.push(`prices in ${prices.length} region(s): ${prices.slice(0, 6).join(', ')}${prices.length > 6 ? ', ...' : ''}`); if (prices.length) owner(`prices in ${prices.length} region(s): ${prices.slice(0, 6).join(', ')}${prices.length > 6 ? ', ...' : ''}`);
if (gone.length) out.push(`regions dropped: ${gone.join(', ')}`); if (gone.length) owner(`regions dropped: ${gone.join(', ')}`);
const nr = opt?.newRegionsConfig; const nr = opt?.newRegionsConfig;
if (money(nr?.usdPrice) !== money(want.newRegions.usdPrice) || money(nr?.eurPrice) !== money(want.newRegions.eurPrice)) if (money(nr?.usdPrice) !== money(want.newRegions.usdPrice) || money(nr?.eurPrice) !== money(want.newRegions.eurPrice))
out.push(`other regions ${money(nr?.usdPrice)} / ${money(nr?.eurPrice)} -> ${money(want.newRegions.usdPrice)} / ${money(want.newRegions.eurPrice)}`); owner(`other regions ${money(nr?.usdPrice)} / ${money(nr?.eurPrice)} -> ${money(want.newRegions.usdPrice)} / ${money(want.newRegions.eurPrice)}`);
if (opt?.state !== 'ACTIVE') out.push('purchase option activated'); if (opt?.state !== 'ACTIVE') owner(`purchase option ${opt?.state ?? 'missing'} -> ACTIVE`);
return out; return out;
} }
@ -83,6 +91,7 @@ export async function run(ctx: Ctx): Promise<void> {
const existing = new Map((await listOneTimeProducts(play)).map(p => [p.productId, p])); const existing = new Map((await listOneTimeProducts(play)).map(p => [p.productId, p]));
const langs = new Map(config.languages.map(l => [l.id, l])); const langs = new Map(config.languages.map(l => [l.id, l]));
const plan: { p: (typeof products)[number]; tag: string; body: Record<string, unknown>; version: string; cur?: Existing; changes: ProductChange[]; regions: number; listings: number }[] = [];
for (const [i, p] of products.entries()) { for (const [i, p] of products.entries()) {
const tag = step(i + 1, products.length, p.id); const tag = step(i + 1, products.length, p.id);
const conv = await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', p.usd) }); const conv = await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', p.usd) });
@ -101,22 +110,41 @@ export async function run(ctx: Ctx): Promise<void> {
}], }],
}; };
const cur = existing.get(p.id); const cur = existing.get(p.id);
if (dry) { const changes = productChanges(cur, { listings, regions, newRegions: conv.convertedOtherRegionsPrice });
const ch = productChanges(cur, { listings, regions, newRegions: conv.convertedOtherRegionsPrice }); const what = !changes.length ? 'unchanged' : !cur ? `${dry ? 'would create' : 'create'} · ${regions.length} regions · ${listings.length} listings`
log('play', `${tag}: ${!ch.length ? 'unchanged' : ch[0] === 'create' ? `would create · ${regions.length} regions · ${listings.length} listings` : 'would update ' + ch.join('; ')} (dry)`); : `${dry ? 'would update' : 'update'} ${changes.map(c => c.text).join('; ')}`;
log('play', `${tag}: ${what}${dry ? ' (dry)' : ''}`);
plan.push({ p, tag, body, version: conv.regionVersion?.version ?? '2022/02', cur, changes, regions: regions.length, listings: listings.length });
}
if (dry) { done('play', 'products checked (dry run, nothing written)'); return; }
// prices, regions and activation of existing products: the owner confirms the diff above first
const gated = plan.filter(x => x.cur && x.changes.some(c => c.owner));
const ok = !gated.length || await confirm(ctx, `Change prices / regions / activation of ${gated.length} existing product(s) on Google Play (${gated.map(x => x.p.id).join(', ')})? Buyers see new prices as soon as Play applies them.`);
if (!ok) warn('play', `price / region / activation changes of ${gated.length} existing product(s) skipped: confirm in a terminal (or the desktop owner action)`);
for (const x of plan) {
if (!x.changes.length) continue;
const id = encodeURIComponent(x.p.id);
const v = encodeURIComponent(x.version);
const ownerChange = !!x.cur && x.changes.some(c => c.owner);
const listingChange = x.changes.some(c => !c.owner);
if (x.cur && ownerChange && !ok) {
if (!listingChange) continue;
await play.call('PATCH', `${play.API}/onetimeproducts/${id}?regionsVersion.version=${v}&updateMask=listings`, x.body);
log('play', `${x.tag}: listings updated (prices unchanged)`);
continue; continue;
} }
const v = encodeURIComponent(conv.regionVersion?.version ?? '2022/02'); const mask = x.cur && !ownerChange ? 'listings' : 'listings,purchaseOptions';
await play.call('PATCH', `${play.API}/onetimeproducts/${encodeURIComponent(p.id)}?allowMissing=true&regionsVersion.version=${v}&updateMask=listings,purchaseOptions`, body); await play.call('PATCH', `${play.API}/onetimeproducts/${id}?allowMissing=true&regionsVersion.version=${v}&updateMask=${mask}`, x.body);
log('play', `${tag}: ${cur ? 'updated' : 'created'} · ${regions.length} regions · ${listings.length} listings`); log('play', `${x.tag}: ${x.cur ? 'updated' : 'created'} · ${x.regions} regions · ${x.listings} listings`);
const active = cur?.purchaseOptions?.find(o => o.purchaseOptionId === OPTION)?.state === 'ACTIVE'; if (x.cur?.purchaseOptions?.find(o => o.purchaseOptionId === OPTION)?.state === 'ACTIVE') continue;
if (active) continue;
try { try {
await play.call('POST', `${play.API}/oneTimeProducts/${encodeURIComponent(p.id)}/purchaseOptions:batchUpdateStates`, { await play.call('POST', `${play.API}/oneTimeProducts/${id}/purchaseOptions:batchUpdateStates`, {
requests: [{ activatePurchaseOptionRequest: { packageName: pkg, productId: p.id, purchaseOptionId: OPTION } }], requests: [{ activatePurchaseOptionRequest: { packageName: pkg, productId: x.p.id, purchaseOptionId: OPTION } }],
}); });
log('play', `${tag}: purchase option activated`); log('play', `${x.tag}: purchase option activated`);
} catch (e) { warn('play', `${tag}: activate failed: ${(e as Error).message}`); } } catch (e) { warn('play', `${x.tag}: activate failed: ${(e as Error).message}`); }
} }
done('play', dry ? 'products checked (dry run, nothing written)' : 'products done'); done('play', 'products done');
} }

View file

@ -25,18 +25,23 @@ Auto-renewable subscriptions are a separate list (`subscriptions`, `store-subscr
- Apple: Paid Applications agreement + banking + tax active (Business > Agreements), the app record exists. - Apple: Paid Applications agreement + banking + tax active (Business > Agreements), the app record exists.
## Google Play (API) ## Google Play (API)
1. `storebound check`, then `storebound play products --dry` (shows create/update and region count per product). 1. `storebound check`, then `storebound play products --dry` (read-only: per product create, unchanged, or exactly
what would change: listings, regional prices old -> new, dropped regions, activation). Show it to the owner.
2. `storebound play products`. Per product: `pricing:convertRegionPrices` (USD -> every region at local price points, 2. `storebound play products`. Per product: `pricing:convertRegionPrices` (USD -> every region at local price points,
and the `regionsVersion`), your overrides on top, `PATCH .../onetimeproducts/{id}?allowMissing=true&regionsVersion.version=...` and the `regionsVersion`), your overrides on top, `PATCH .../onetimeproducts/{id}?allowMissing=true&regionsVersion.version=...`
(create or update), then `oneTimeProducts/{id}/purchaseOptions:batchUpdateStates` to activate (new options are DRAFT). (create or update), then `oneTimeProducts/{id}/purchaseOptions:batchUpdateStates` to activate (new options are DRAFT).
New products and listing text go straight through. Price, region or activation changes of an EXISTING product
are the owner's decision: the run shows the diff and asks in a terminal; without a terminal (MCP, CI, the desktop
app's normal write) they are skipped with a warning, the listing text still updates. The owner confirms in a
terminal, or applies prices with the desktop Prices "Apply" (owner action, `prices import`).
3. Verify: `storebound play status` lists every product with `buy:ACTIVE`. 3. Verify: `storebound play status` lists every product with `buy:ACTIVE`.
4. Test: Play Console > Settings > License testing: add tester Gmail accounts; install from the internal testing 4. Test: Play Console > Settings > License testing: add tester Gmail accounts; install from the internal testing
link; purchases are free test orders. link; purchases are free test orders.
## App Store (API + UI) ## App Store (API + UI)
1. `storebound apple iap --dry`, then `storebound apple iap`: creates missing products, localizations, a price schedule 1. `storebound apple iap --dry`, then `storebound apple iap`: creates missing products, localizations, a price schedule
(USA base + overrides; Apple equalizes the rest) and availability. Existing schedules are not changed (change prices (USA base + overrides; Apple equalizes the rest) and availability. Existing schedules and availability are never
in the UI if needed). changed by it; price changes go through `storebound prices import` (diff first, then the owner confirms).
2. Review screenshot per product (a real device size, e.g. 1290 x 2796, showing the item in the shop): 2. Review screenshot per product (a real device size, e.g. 1290 x 2796, showing the item in the shop):
`storebound apple iap-review`. States move to READY_TO_SUBMIT when complete. `storebound apple iap-review`. States move to READY_TO_SUBMIT when complete.
3. **UI**: each IAP page > "Add for Review"; this puts them into the version's draft submission. Then submit the 3. **UI**: each IAP page > "Add for Review"; this puts them into the version's draft submission. Then submit the

View file

@ -19,7 +19,7 @@ import type { Loaded, ShipConfig } from '../cli/lib/config';
import { healthFindings, healthTable, issuesQuery, metricQuery } from '../cli/lib/health'; import { healthFindings, healthTable, issuesQuery, metricQuery } from '../cli/lib/health';
import { imageChange, run as imagesRun } from '../cli/play/images'; import { imageChange, run as imagesRun } from '../cli/play/images';
import { detailsChanges, listingChanges, run as listingRun } from '../cli/play/listing'; import { detailsChanges, listingChanges, run as listingRun } from '../cli/play/listing';
import { type Existing, productChanges } from '../cli/play/products'; import { type Existing, productChanges, run as productsRun } from '../cli/play/products';
import { toMoney } from '../cli/lib/money'; import { toMoney } from '../cli/lib/money';
const PKG = 'com.example.game'; const PKG = 'com.example.game';
@ -202,12 +202,79 @@ describe('play products --dry: what would change on an existing product', () =>
test('the same product converted again is unchanged (toMoney nanos 0 equals Money without nanos)', () => { test('the same product converted again is unchanged (toMoney nanos 0 equals Money without nanos)', () => {
expect(productChanges(CUR, want)).toEqual([]); expect(productChanges(CUR, want)).toEqual([]);
expect(productChanges(undefined, want)).toEqual(['create']); expect(productChanges(undefined, want)).toEqual([{ text: 'create', owner: false }]);
}); });
test('a price override, a changed and a dropped listing, a dropped region are named', () => { test('a price override, a changed and a dropped listing, a dropped region are named', () => {
const w = { ...want, listings: [{ ...want.listings[0]!, title: 'Remove Ads' }], regions: [want.regions[0]!, region('TR', 'TRY', 99.99)] }; const w = { ...want, listings: [{ ...want.listings[0]!, title: 'Remove Ads' }], regions: [want.regions[0]!, region('TR', 'TRY', 99.99)] };
expect(productChanges(CUR, w)).toEqual(['listings changed: en-US', 'listings removed: tr-TR', 'prices in 1 region(s): TR TRY 129.99 -> TRY 99.99', 'regions dropped: JP']); expect(productChanges(CUR, w)).toEqual([
const draft = { ...CUR, purchaseOptions: [{ ...CUR.purchaseOptions![0]!, state: 'DRAFT' }] }; { text: 'listings changed: en-US', owner: false }, { text: 'listings removed: tr-TR', owner: false },
expect(productChanges(draft, want)).toEqual(['purchase option activated']); { text: 'prices in 1 region(s): TR TRY 129.99 -> TRY 99.99', owner: true }, { text: 'regions dropped: JP', owner: true }]);
const inactive = { ...CUR, purchaseOptions: [{ ...CUR.purchaseOptions![0]!, state: 'INACTIVE' }] };
expect(productChanges(inactive, want)).toEqual([{ text: 'purchase option INACTIVE -> ACTIVE', owner: true }]);
});
});
describe('play products: price, region and activation changes of existing products ask first', () => {
// the existing product as listed (2 regions), and what convertRegionPrices answers for USD 2.99
const LISTED = { productId: 'com.example.game.no_ads',
listings: [{ languageCode: 'en-US', title: 'No Ads', description: 'Removes ads.' }],
purchaseOptions: [{ purchaseOptionId: 'buy', state: 'ACTIVE', buyOption: { legacyCompatible: true },
regionalPricingAndAvailabilityConfigs: [
{ regionCode: 'TR', price: { currencyCode: 'TRY', units: '129', nanos: 990000000 }, availability: 'AVAILABLE' },
{ regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 }, availability: 'AVAILABLE' }],
newRegionsConfig: { usdPrice: { currencyCode: 'USD', units: '2', nanos: 990000000 }, eurPrice: { currencyCode: 'EUR', units: '2', nanos: 670000000 }, availability: 'AVAILABLE' } }] };
const CONVERTED = { convertedRegionPrices: { TR: { regionCode: 'TR', price: { currencyCode: 'TRY', units: '129', nanos: 990000000 } }, US: { regionCode: 'US', price: { currencyCode: 'USD', units: '2', nanos: 990000000 } } },
convertedOtherRegionsPrice: { usdPrice: { currencyCode: 'USD', units: '2', nanos: 990000000 }, eurPrice: { currencyCode: 'EUR', units: '2', nanos: 670000000 } }, regionVersion: { version: '2026/01' } };
const env = { ...process.env };
afterEach(() => { for (const k of ['STOREBOUND_SERVE', 'STOREBOUND_OWNER_CONFIRMED']) { if (env[k] === undefined) delete process.env[k]; else process.env[k] = env[k]; } });
async function runWith(product: Record<string, unknown>, argv: string[] = []) {
playKey();
const root = mkdtempSync(join(tmpdir(), 'sb-post-'));
const config = { app: { name: 'Example Game' }, languages: [{ id: 'en', play: 'en-US' }], play: { packageName: PKG },
products: [{ id: 'com.example.game.no_ads', type: 'non_consumable', usd: 2.99, listings: { en: { title: 'No Ads', description: 'Removes ads.' } }, ...product },
{ id: 'com.example.game.gems_new', type: 'consumable', usd: 2.99, listings: { en: { title: 'Gems', description: 'A bag of gems.' } } }] } as unknown as ShipConfig;
const loaded: Loaded = { config, root, path: join(root, 'storebound.config.ts'), resolve: p => join(root, p) };
const calls = fake(c => {
if (c.url.startsWith(`${API}/oneTimeProducts?`)) return json({ oneTimeProducts: [LISTED] });
if (c.url === `${API}/pricing:convertRegionPrices`) return json(CONVERTED);
return json({});
});
const out: string[] = [];
const [l, w, e] = [console.log, console.warn, console.error];
console.log = console.warn = console.error = (...a: unknown[]) => { out.push(a.join(' ')); };
try { await productsRun({ loaded, args: parseArgs(argv) }); } finally { [console.log, console.warn, console.error] = [l, w, e]; }
const writes = calls.filter(c => c.method !== 'GET' && !c.url.endsWith(':convertRegionPrices')).map(c => `${c.method} ${c.url.replace(API, '').replace(/regionsVersion\.version=[^&]+&?/, '')}`);
return { writes, out: out.join('\n') };
}
test('without a terminal: an existing product\'s price change is skipped, its listing change and new products still go', async () => {
const r = await runWith({ overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }], listings: { en: { title: 'Remove Ads', description: 'Removes ads.' } } });
expect(r.out).toContain('update listings changed: en-US; prices in 1 region(s): TR TRY 129.99 -> TRY 99.99');
expect(r.writes).toEqual([
'PATCH /onetimeproducts/com.example.game.no_ads?updateMask=listings',
'PATCH /onetimeproducts/com.example.game.gems_new?allowMissing=true&updateMask=listings,purchaseOptions',
'POST /oneTimeProducts/com.example.game.gems_new/purchaseOptions:batchUpdateStates',
]);
expect(r.out).toContain('skipped: confirm in a terminal');
});
test('a price-only change is not written at all without a confirmation; --yes confirms in a terminal-less run', async () => {
const over = { overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }] };
expect((await runWith(over)).writes.filter(w => w.includes('no_ads'))).toEqual([]);
expect((await runWith(over, ['--yes'])).writes.filter(w => w.includes('no_ads'))).toEqual(['PATCH /onetimeproducts/com.example.game.no_ads?allowMissing=true&updateMask=listings,purchaseOptions']);
});
test('under serve: refused even with --yes; a verified desktop owner confirmation lets it through', async () => {
const over = { overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }] };
process.env.STOREBOUND_SERVE = '1';
expect((await runWith(over, ['--yes'])).writes.filter(w => w.includes('no_ads'))).toEqual([]);
process.env.STOREBOUND_OWNER_CONFIRMED = '1';
expect((await runWith(over)).writes.filter(w => w.includes('no_ads'))).toEqual(['PATCH /onetimeproducts/com.example.game.no_ads?allowMissing=true&updateMask=listings,purchaseOptions']);
});
test('nothing to change: no write for the existing product', async () => {
expect((await runWith({})).writes.filter(w => w.includes('no_ads'))).toEqual([]);
}); });
}); });