diff --git a/CHANGELOG.md b/CHANGELOG.md index 939e1678..28bdf3b2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- Fixes from a second read-only run (GET only) of the desktop read paths against live accounts: `analytics snapshot` + no longer writes a snapshot when every store failed (no ONGOING report request yet, no `play.reportsBucket`); it + exits with both reasons, so the desktop dry run shows them. `analytics compare --json` adds `errors` (why a store has + no days), and the Growth tab shows that reason instead of zero totals and "one day of data". Listing completeness + no longer counts a contact sheet in the language folder as a screenshot. Price sheet round trip (export, then + compare) checked on recorded App Store and Play price answers (`tests/desktop-real-reads.test.ts`). + +- Growth tab chart: impressions, downloads and conversion are drawn as an index (100 = each line's own average over + the days shown) on one axis, so downloads no longer lie flat under impressions; hover still shows the real numbers. + - **`storebound import fastlane`** (`--dir`, `--out`, `--profile`, `--dry`; MCP `import_fastlane`, dry run by default): reads Appfile / Deliverfile (plain `key("value")` lines only; Ruby logic is reported, never run), deliver and supply metadata and screenshots, and writes `storebound.config.ts`, `store/appstore.md`, `store/listing.md`, the Play icon diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index d05038e8..a751e38e 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -52,7 +52,7 @@ export function errorText(e: unknown): string { } /** Dev-only fixture mode (VITE_FIXTURES=1): every command answered from src/dev/fixtures.ts. */ -export const FIXTURES: boolean = import.meta.env.DEV && !!import.meta.env.VITE_FIXTURES; +export const FIXTURES: boolean = !!(import.meta.env.DEV && import.meta.env.VITE_FIXTURES); async function invoke(cmd: string, args?: Record): Promise { if (import.meta.env.DEV && import.meta.env.VITE_FIXTURES) return (await import('./dev/fixtures')).mockInvoke(cmd, args ?? {}); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 631477f4..c7088ab4 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1045,6 +1045,9 @@ export const en = { 'gr.chartAria': 'Daily store traffic on {store} with listing changes', 'gr.changes': '{count} listing changes', 'gr.changes_one': '1 listing change', + 'gr.indexLabel': 'Index: 100 = each line\'s own average over these days. Hover for the real numbers.', + 'gr.noDataTitle': 'No {store} days in the snapshots yet', + 'gr.noDataText': 'The snapshots read no daily numbers for this store yet. Take a new snapshot once the store has data.', 'gr.oneDay': 'One day of data so far: the chart starts with the second day.', 'gr.change': 'Listing change (git)', 'gr.before': 'Before', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 96558ffd..abcd1fba 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1047,6 +1047,9 @@ export const tr: Record = { 'gr.chartAria': '{store} üzerinde günlük mağaza trafiği ve mağaza metni değişiklikleri', 'gr.changes': '{count} mağaza metni değişikliği', 'gr.changes_one': '1 mağaza metni değişikliği', + 'gr.indexLabel': 'Endeks: 100 = her çizginin bu günlerdeki kendi ortalaması. Gerçek sayılar için üzerine gelin.', + 'gr.noDataTitle': 'Anlık görüntülerde henüz {store} günü yok', + 'gr.noDataText': 'Anlık görüntüler bu mağaza için henüz günlük sayı okumadı. Mağazada veri olunca yeni bir anlık görüntü alın.', 'gr.oneDay': 'Şimdilik bir günlük veri var: grafik ikinci günle başlar.', 'gr.change': 'Mağaza değişikliği (git)', 'gr.before': 'Önce', diff --git a/apps/desktop/src/lib/views.ts b/apps/desktop/src/lib/views.ts index 382fc412..d359f5b0 100644 --- a/apps/desktop/src/lib/views.ts +++ b/apps/desktop/src/lib/views.ts @@ -76,6 +76,17 @@ export function chartSeries(a: AnalyticsCompare, store: 'apple' | 'play'): Chart return { dates: pts.map(p => p.date), reach: pts.map(p => p.reach), installs: pts.map(p => p.installs), conversion: pts.map(p => (p.reach ? p.installs / p.reach : null)), events }; } +/** + * A daily series as an index: 100 = the average of its own non-empty days, so reach, installs and conversion share one + * axis although they differ by orders of magnitude (installs on a count axis next to impressions lie flat). Empty days + * stay empty; a series whose average is 0 has no index (all null). + */ +export function indexSeries(values: (number | null)[]): (number | null)[] { + const xs = values.filter((v): v is number => v !== null && Number.isFinite(v)); + const mean = xs.length ? xs.reduce((n, v) => n + v, 0) / xs.length : 0; + return values.map(v => (v === null || !Number.isFinite(v) || !mean ? null : (v / mean) * 100)); +} + /** Conversion before vs after one change (null when a side has no data). */ export const effectDelta = (before?: number | null, after?: number | null): number | null => (before && after !== undefined && after !== null ? ((after - before) / before) * 100 : null); diff --git a/apps/desktop/src/screens/tabs/Growth.tsx b/apps/desktop/src/screens/tabs/Growth.tsx index 0dc229b1..d6f338fb 100644 --- a/apps/desktop/src/screens/tabs/Growth.tsx +++ b/apps/desktop/src/screens/tabs/Growth.tsx @@ -47,7 +47,9 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec actions={<>{stores.length > 1 && }{actions}}> {none ? ( {t('gr.noneText')}{hasPlay && !playReports ? ` ${t('gr.noBucket')}` : ''} - ) : r.error ?
: !a || !s ?
: ( + ) : r.error ?
: !a || !s ?
: !s.dates.length ? ( + {a.errors?.[st] ?? t('gr.noDataText')}{st === 'play' && !playReports ? ` ${t('gr.noBucket')}` : ''} + ) : (
@@ -56,10 +58,11 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec
{s.dates.length > 1 ? ( ) : {t('gr.oneDay')}} {effects.length > 0 && ( diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index af4fa652..6d131c3c 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -855,6 +855,7 @@ textarea.input { height: auto; padding: 8px 10px; line-height: 1.45; resize: ver .lchart svg { width: 100%; height: auto; display: block; overflow: visible; outline: none; border-radius: 8px; } .lchart svg:focus-visible { box-shadow: 0 0 0 2px var(--focus); } .lchart .grid-l line { stroke: var(--line); stroke-width: 1; } +.lchart line.base { stroke: var(--line-2); stroke-width: 1; stroke-dasharray: 2 3; } .lchart text { font-size: 10.5px; fill: var(--muted); font-variant-numeric: tabular-nums; } .lchart .stop-a { stop-color: var(--accent-solid); stop-opacity: .18; } .lchart .stop-b { stop-color: var(--accent-solid); stop-opacity: 0; } @@ -868,6 +869,7 @@ textarea.input { height: auto; padding: 8px 10px; line-height: 1.45; resize: ver .lchart .hov line { stroke: var(--line-2); stroke-width: 1; } .lchart-legend { display: flex; flex-wrap: wrap; gap: 6px 16px; font-size: var(--t-meta); color: var(--muted); align-items: center; } .lchart-legend .lg { display: inline-flex; align-items: center; gap: 6px; } +.lchart-legend .lg.idx { flex-basis: 100%; } .lchart-legend b { color: var(--ink); font-weight: 650; } .lchart-legend .sw { width: 14px; height: 3px; border-radius: 2px; background: var(--accent-solid); } .lchart-legend .sw.l2 { background: var(--ok-solid); } diff --git a/apps/desktop/src/ui/LineChart.tsx b/apps/desktop/src/ui/LineChart.tsx index 4775e0c6..ead190d0 100644 --- a/apps/desktop/src/ui/LineChart.tsx +++ b/apps/desktop/src/ui/LineChart.tsx @@ -1,22 +1,42 @@ -// A small two-axis line chart for daily store analytics: counts on the left axis (reach, installs), a rate on the -// right (conversion), store changes from git as dashed markers. Hover (or arrow keys when focused) shows one day. +// A small line chart for daily store analytics. Reach (impressions, visitors), installs and conversion differ by one +// to three orders of magnitude, so on one count axis installs lay flat at the bottom. The chart therefore plots each +// line as an index (100 = that line's own average over the days shown, views.ts indexSeries) on one shared axis: every +// line uses the full height and a listing change shows as lines moving apart. Hover (or arrow keys when focused) shows +// the real values of one day; store changes from git are dashed markers. import { type KeyboardEvent, useId, useState } from 'react'; import { date, num, pct } from '../lib/format'; +import { indexSeries } from '../lib/views'; -export interface ChartLine { label: string; values: (number | null)[]; cls: 'l1' | 'l2' | 'l3'; axis: 'left' | 'right' } +export interface ChartLine { + label: string; + /** Real daily values (counts, or a 0-1 rate with unit "rate"); plotted as an index, shown as they are on hover. */ + values: (number | null)[]; + cls: 'l1' | 'l2' | 'l3'; + unit: 'count' | 'rate'; +} -export function LineChart({ dates, lines, events, label, eventsLabel }: { dates: string[]; lines: ChartLine[]; events: { date: string; subject: string }[]; label: string; eventsLabel: string }) { - const W = 800, H = 230, L = 46, R = 46, T = 12, B = 26; +const W = 800, H = 230, L = 46, R = 18, T = 14, B = 26; + +/** Index axis: a round top above the highest point (at least 150 so 100 sits in the lower two thirds) and 4 ticks. */ +export function indexAxis(lines: (number | null)[][]): { max: number; ticks: number[] } { + const hi = Math.max(150, ...lines.flat().filter((v): v is number => v !== null)); + const step = hi <= 200 ? 50 : hi <= 400 ? 100 : Math.ceil(hi / 4 / 100) * 100; + const max = Math.ceil(hi / step) * step; + return { max, ticks: Array.from({ length: max / step + 1 }, (_, i) => i * step) }; +} + +export function LineChart({ dates, lines, events, label, eventsLabel, indexLabel }: { + dates: string[]; lines: ChartLine[]; events: { date: string; subject: string }[]; label: string; eventsLabel: string; indexLabel: string; +}) { const gid = useId().replace(/:/g, ''); const [hover, setHover] = useState(null); const n = dates.length; if (n < 2) return null; + const plotted = lines.map(l => indexSeries(l.values)); + const { max, ticks } = indexAxis(plotted); const x = (i: number) => L + (i / (n - 1)) * (W - L - R); - const max = (axis: 'left' | 'right') => Math.max(...lines.filter(l => l.axis === axis).flatMap(l => l.values.filter((v): v is number => v !== null)), axis === 'right' ? 0.001 : 1) * 1.1; - const mL = max('left'), mR = max('right'); - const y = (v: number, axis: 'left' | 'right') => H - B - (v / (axis === 'left' ? mL : mR)) * (H - T - B); - const path = (l: ChartLine) => l.values.map((v, i) => (v === null ? '' : `${i && l.values[i - 1] !== null ? 'L' : 'M'}${x(i).toFixed(1)} ${y(v, l.axis).toFixed(1)}`)).join(' '); - const ticks = [0, 0.5, 1]; + const y = (v: number) => H - B - (v / max) * (H - T - B); + const path = (vs: (number | null)[]) => vs.map((v, i) => (v === null ? '' : `${i && vs[i - 1] !== null ? 'L' : 'M'}${x(i).toFixed(1)} ${y(v).toFixed(1)}`)).join(' '); const onMove = (ev: React.MouseEvent) => { const r = ev.currentTarget.getBoundingClientRect(); const px = ((ev.clientX - r.left) / r.width) * W; @@ -26,30 +46,31 @@ export function LineChart({ dates, lines, events, label, eventsLabel }: { dates: if (ev.key === 'ArrowRight') { ev.preventDefault(); setHover(h => Math.min(n - 1, (h ?? -1) + 1)); } if (ev.key === 'ArrowLeft') { ev.preventDefault(); setHover(h => Math.max(0, (h ?? n) - 1)); } }; - const fmt = (l: ChartLine, v: number | null) => (v === null ? '–' : l.axis === 'right' ? pct(v, 1) : num(v)); + const fmt = (l: ChartLine, v: number | null) => (v === null ? '–' : l.unit === 'rate' ? pct(v, 1) : num(v)); return (
- setHover(null)} onKeyDown={onKey} onBlur={() => setHover(null)}> + setHover(null)} onKeyDown={onKey} onBlur={() => setHover(null)}> - {ticks.map(f => ( - - - {num(f * mL / 1.1)} - {pct(f * mR / 1.1, 1)} + {ticks.map(v => ( + + + {v} ))} + {events.map((e, i) => { const k = dates.indexOf(e.date); if (k < 0) return null; return {`${date(e.date)} · ${e.subject}`}; })} - {lines[0] && } - {lines.map(l => )} - {hover !== null && {lines.map(l => (l.values[hover] === null ? null : ))}} + {plotted[0] && } + {lines.map((l, k) => )} + {hover !== null && {lines.map((l, k) => (plotted[k]![hover] === null ? null : ))}} {date(dates[0])} {date(dates[n - 1])}
+ {indexLabel} {hover !== null && {date(dates[hover])}} {lines.map(l => {l.label}{hover !== null && {fmt(l, l.values[hover] ?? null)}})} {events.length > 0 && {eventsLabel}} diff --git a/apps/desktop/tests/complete.test.ts b/apps/desktop/tests/complete.test.ts index a22b5289..d4176306 100644 --- a/apps/desktop/tests/complete.test.ts +++ b/apps/desktop/tests/complete.test.ts @@ -3,7 +3,8 @@ import { describe, expect, test } from 'bun:test'; import type { PricesCurrent } from '../src/api'; import { csv, mdTable, pricesCsv, reviewsCsv } from '../src/lib/exports'; -import { chartSeries, diffSummary, fixHint, priceMatrix, priceStats, regionRows } from '../src/lib/views'; +import { chartSeries, diffSummary, fixHint, indexSeries, priceMatrix, priceStats, regionRows } from '../src/lib/views'; +import { indexAxis } from '../src/ui/LineChart'; import { parsePriceCsv } from '../../../cli/lib/prices'; const P: PricesCurrent = { @@ -56,6 +57,17 @@ describe('views', () => { expect(s.conversion).toEqual([0.05, null]); expect(s.events).toEqual([{ date: '2026-01-02', subject: 'x', commit: 'abc' }]); }); + test('chart index: every line on one axis, 100 = its own average', () => { + // impressions ~4000 and downloads ~150 a day: on a count axis downloads lie flat; indexed both use the height + const imp = [3800, 4200, 4000, 4000], dl = [120, 150, 180, 150]; + expect(indexSeries(imp)).toEqual([95, 105, 100, 100]); + expect(indexSeries(dl)).toEqual([80, 100, 120, 100]); + expect(indexSeries([null, 0.04, 0.06])).toEqual([null, 80, 120]); + expect(indexSeries([0, 0, null])).toEqual([null, null, null]); + expect(indexAxis([[80, 120], [95, 105]])).toEqual({ max: 150, ticks: [0, 50, 100, 150] }); + expect(indexAxis([[40, 230]])).toEqual({ max: 300, ticks: [0, 100, 200, 300] }); + expect(indexAxis([[900]]).max).toBeGreaterThanOrEqual(900); + }); test('errors that say how to fix them', () => { expect(fixHint('PLAY_SERVICE_ACCOUNT is not set (env ...)')).toBe('hint.keys'); expect(fixHint('no snapshots in /x/.storebound/analytics (storebound analytics snapshot)')).toBe('hint.snapshot'); diff --git a/cli/analytics.ts b/cli/analytics.ts index 9c581dc8..6001aad9 100644 --- a/cli/analytics.ts +++ b/cli/analytics.ts @@ -14,7 +14,7 @@ import { ascClient, type Asc, type J } from './apple/asc'; import type { Ctx } from './lib/ctx'; import { type AppleDay, APPLE_REPORTS, appleDaily, appleTotals, bucketName, checksumOk, compareAroundEvents, decodeText, effectMarkdown, effectTable, inWindow, - latestPerDate, mergeSeries, monthsBetween, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot, + latestPerDate, mergeSeries, monthsBetween, snapshotProblem, storeErrors, parseGitLog, parseReport, pickReport, type PlayDay, playDaily, playObjects, playTotals, type Snapshot, } from './lib/analytics'; import { STORAGE_READ_SCOPE } from './lib/google-auth'; import { done, log, printJson, warn } from './lib/log'; @@ -127,6 +127,8 @@ export async function run(ctx: Ctx): Promise { if (snap.play && !('error' in snap.play)) { const t = snap.play.totals; rows.push(['play', `${t.visitors} visitors`, `${t.acquisitions} acquisitions`, `${t.installs} installs`, pct(t.conversion ?? null)]); } if (rows.length) console.log(textTable(['store', 'reach', 'interest', 'installs', 'conversion'], rows)); const file = join(dir, `${snap.date}.json`); + const problem = snapshotProblem(snap); + if (problem) throw new Error(`no store data, nothing written (${problem})`); if (dry) { done(TAG, `dry run: would write ${file} (${start} to ${end})`); return; } mkdirSync(dir, { recursive: true }); writeFileSync(file, JSON.stringify(snap, null, 2) + '\n'); @@ -145,7 +147,7 @@ export async function run(ctx: Ctx): Promise { const events = parseGitLog(g.stdout.toString()).reverse(); log(TAG, `${snaps.length} snapshot(s), ${series.apple.length} App Store day(s), ${series.play.length} Play day(s), ${events.length} store change(s) since ${first}`); const fx = compareAroundEvents(series, events, a.num('days', 7)); - if (a.has('json')) { printJson({ snapshots: snaps.length, since: first, series, effects: fx }); return; } + if (a.has('json')) { printJson({ snapshots: snaps.length, since: first, series, effects: fx, errors: storeErrors(snaps) }); return; } console.log(a.has('md') ? effectMarkdown(fx) : effectTable(fx)); log(TAG, 'reading: a change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too'); return; diff --git a/cli/lib/analytics.ts b/cli/lib/analytics.ts index f27b0fbf..0c5b0b0a 100644 --- a/cli/lib/analytics.ts +++ b/cli/lib/analytics.ts @@ -125,6 +125,30 @@ export interface Snapshot { play?: { daily: PlayDay[]; totals: Totals } | { error: string }; } +/** + * Why a fresh snapshot is not worth writing: every store it read failed (no ONGOING report request yet, no reports + * bucket, no access). Null when at least one store has days. A snapshot of errors only would make `snapshot` look done + * while `compare` and the desktop chart stay empty. + */ +export function snapshotProblem(s: Snapshot): string | null { + const parts = (['apple', 'play'] as const).filter(k => s[k]); + if (!parts.length) return 'no store to read (no apple or play section in the config, or --store names none)'; + if (parts.some(k => !('error' in s[k]!))) return null; + return parts.map(k => `${k}: ${(s[k] as { error: string }).error}`).join('; '); +} + +/** The newest error per store when that store has no days in any snapshot (shown instead of an empty chart). */ +export function storeErrors(snaps: Snapshot[]): { apple?: string; play?: string } { + const out: { apple?: string; play?: string } = {}; + const series = mergeSeries(snaps); + for (const k of ['apple', 'play'] as const) { + if (series[k].length) continue; + const last = [...snaps].sort((x, y) => x.date.localeCompare(y.date)).reverse().find(s => s[k] && 'error' in s[k]!); + if (last) out[k] = (last[k] as { error: string }).error; + } + return out; +} + export const inWindow = (rows: T[], start: string, end: string): T[] => rows.filter(r => r.date >= start && r.date <= end); // ---- compare with listing changes ---- diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index df9476dc..b04657ac 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -319,4 +319,6 @@ export interface AnalyticsCompare { play: { date: string; visitors: number; acquisitions: number; installs: number }[]; }; effects: { event: { date: string; commit: string; subject: string; files: string[] }; store: 'apple' | 'play'; before: AnalyticsTotals; after: AnalyticsTotals; daysBefore: number; daysAfter: number }[]; + /** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */ + errors?: { apple?: string; play?: string }; } diff --git a/cli/lib/project-files.ts b/cli/lib/project-files.ts index af864ecd..03d35390 100644 --- a/cli/lib/project-files.ts +++ b/cli/lib/project-files.ts @@ -90,12 +90,14 @@ export function appleSections(md: string): Map//...). Files right in the language + * folder (a contact sheet, a preview collage) are not store images and are not counted, like the gallery. */ +export function countImages(dir: string, depth = 0): number { let n = 0; try { for (const e of readdirSync(dir, { withFileTypes: true })) { - if (e.isDirectory()) n += countImages(join(dir, e.name)); - else if (/\.(png|jpe?g)$/i.test(e.name)) n++; + if (e.isDirectory()) n += countImages(join(dir, e.name), depth + 1); + else if (depth > 0 && /\.(png|jpe?g)$/i.test(e.name)) n++; } } catch { /* unreadable: 0 */ } return n; diff --git a/tests/desktop-real-reads.test.ts b/tests/desktop-real-reads.test.ts new file mode 100644 index 00000000..6c22dbaf --- /dev/null +++ b/tests/desktop-real-reads.test.ts @@ -0,0 +1,100 @@ +// The desktop read paths against what the stores really answered in a read-only run (GET only) on live accounts, +// 2026-10. Recorded responses are sanitized: ids, product ids and package names are placeholders. +// - prices.current: App Store manualPrices / automaticPrices pages (customerPrice "14900.0", territories priced in +// USD next to Play's local currency) and a Play oneTimeProduct (Money without nanos). The desktop price sheet +// export must import again with no change. +// - analytics: a team without the ONGOING report request and an app without play.reportsBucket gave a snapshot of +// errors only; `snapshot` wrote it and said done, the Growth chart then showed zero KPIs and "one day of data". +// - listings: a contact sheet in the language folder (//sheet.png) was counted as a screenshot. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pricesCsv } from '../apps/desktop/src/lib/exports'; +import { priceStats, regionRows } from '../apps/desktop/src/lib/views'; +import { mergeSeries, type Snapshot, snapshotProblem, storeErrors } from '../cli/lib/analytics'; +import type { PricesCurrent } from '../cli/lib/desktop-protocol'; +import { countImages } from '../cli/lib/project-files'; +import { applePriceRows, diffPrices, parsePriceCsv, type PlayProduct, playPriceRows } from '../cli/lib/prices'; +import real from './fixtures/real-prices.json'; + +const ID = 'com.example.game.no_ads'; +type Resp = Parameters[1]; + +/** What `prices export --json` builds from the recorded pages (pointId dropped, as in cli/prices.ts). */ +function current(): PricesCurrent { + const rows = [...applePriceRows(ID, real.apple.manual as Resp), ...applePriceRows(ID, real.apple.auto as Resp, 'auto'), ...playPriceRows(real.play as PlayProduct)]; + return { csv: '/x/store/prices.csv', products: [ID], stores: ['apple', 'play'], missing: [], rows: rows.map(({ pointId: _p, ...r }) => r) }; +} + +describe('prices.current from recorded store answers', () => { + test('rows: manual and equalized App Store prices, Play Money with and without nanos', () => { + const p = current(); + const by = (store: string, region: string) => p.rows.find(r => r.store === store && r.region === region); + expect(by('apple', 'TR')).toEqual({ product: ID, store: 'apple', region: 'TR', territory: 'TUR', currency: 'TRY', price: 129.99 }); + expect(by('apple', 'CO')).toEqual({ product: ID, store: 'apple', region: 'CO', territory: 'COL', currency: 'COP', price: 14900, kind: 'auto' }); + expect(by('play', 'CO')).toEqual({ product: ID, store: 'play', region: 'CO', currency: 'COP', price: 9500 }); + expect(by('play', 'TR')?.price).toBe(129.99); + }); + + test('price gaps: same currency compared, Apple USD territories next to Play USD', () => { + const rows = regionRows(current(), ID); + const g = (r: string) => rows.find(x => x.region === r)!.gapPct; + expect(g('US')).toBe(0); + expect(g('TR')).toBe(0); + expect(g('AM')!).toBeCloseTo(25.06, 1); + expect(g('CO')!).toBeCloseTo(36.24, 1); + expect(priceStats(current(), 10)).toMatchObject({ products: 1, regions: 4, manual: 6, auto: 2, gaps: 2, missing: 0 }); + }); + + test('the desktop price sheet imports again with no change (round trip)', () => { + const p = current(); + const sheet = pricesCsv(p); + expect(sheet.split('\n')[0]).toBe('product,store,region,currency,price,start_date,kind'); + const wanted = parsePriceCsv(sheet, { products: [ID], today: '2026-10-11' }); + const cur = [...applePriceRows(ID, real.apple.manual as Resp), ...applePriceRows(ID, real.apple.auto as Resp, 'auto'), ...playPriceRows(real.play as PlayProduct)]; + expect(diffPrices(cur, wanted).filter(d => d.change !== 'same')).toEqual([]); + // an edited sheet: one price changed, one scheduled App Store price added + const edited = sheet.replace(`${ID},apple,TR,TRY,129.99,,manual`, `${ID},apple,TR,TRY,149.99,,manual`) + `${ID},apple,US,USD,3.99,2027-01-15,manual\n`; + const d = diffPrices(cur, parsePriceCsv(edited, { products: [ID], today: '2026-10-11' })).filter(x => x.change !== 'same'); + expect(d).toEqual([ + { product: ID, store: 'apple', region: 'TR', currency: 'TRY', from: 129.99, to: 149.99, change: 'change' }, + { product: ID, store: 'apple', region: 'US', startDate: '2027-01-15', currency: 'USD', from: null, to: 3.99, change: 'new' }, + ]); + }); +}); + +const NO_REQUEST = 'no active ONGOING analytics report request: run storebound analytics setup (Admin key), data starts 1-2 days later'; +const NO_BUCKET = 'play.reportsBucket is not set (Play Console > Download reports > Statistics > Copy Cloud Storage URI)'; +const errorsOnly: Snapshot = { date: '2026-10-10', window: { start: '2026-09-12', end: '2026-10-09', days: 28 }, apple: { error: NO_REQUEST }, play: { error: NO_BUCKET } }; + +describe('analytics without store data', () => { + test('a snapshot of errors only is a problem (not written), one store with days is fine', () => { + expect(snapshotProblem(errorsOnly)).toBe(`apple: ${NO_REQUEST}; play: ${NO_BUCKET}`); + const day = { date: '2026-10-09', impressions: 10, uniqueImpressions: 8, pageViews: 3, uniquePageViews: 3, downloads: 1, firstTimeDownloads: 1 }; + expect(snapshotProblem({ ...errorsOnly, apple: { daily: [day], totals: { impressions: 10, pageViews: 3, downloads: 1, conversion: 0.1 } } })).toBeNull(); + expect(snapshotProblem({ date: '2026-10-10', window: errorsOnly.window })).toMatch(/no store to read/); + }); + + test('compare names why a store has no days (newest snapshot), and nothing for a store with days', () => { + expect(mergeSeries([errorsOnly])).toEqual({ apple: [], play: [] }); + expect(storeErrors([errorsOnly])).toEqual({ apple: NO_REQUEST, play: NO_BUCKET }); + const day = { date: '2026-10-11', impressions: 10, uniqueImpressions: 8, pageViews: 3, uniquePageViews: 3, downloads: 1, firstTimeDownloads: 1 }; + const later: Snapshot = { date: '2026-10-12', window: errorsOnly.window, apple: { daily: [day], totals: {} }, play: { error: 'GET b/o -> 403 forbidden' } }; + expect(storeErrors([errorsOnly, later])).toEqual({ play: 'GET b/o -> 403 forbidden' }); + }); +}); + +describe('listing completeness screenshots', () => { + test('images in size folders count, a contact sheet in the language folder does not', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-count-')); + for (const s of ['ios69', 'play', 'feature']) mkdirSync(join(dir, 'en', s), { recursive: true }); + writeFileSync(join(dir, 'en', 'ios69', '01.png'), 'x'); + writeFileSync(join(dir, 'en', 'ios69', '02.jpg'), 'x'); + writeFileSync(join(dir, 'en', 'play', '01.png'), 'x'); + writeFileSync(join(dir, 'en', 'feature', '1024x500.png'), 'x'); + writeFileSync(join(dir, 'en', 'sheet.png'), 'x'); + writeFileSync(join(dir, 'en', 'notes.txt'), 'x'); + expect(countImages(join(dir, 'en'))).toBe(4); + }); +}); diff --git a/tests/fixtures/real-prices.json b/tests/fixtures/real-prices.json new file mode 100644 index 00000000..2dfeca1c --- /dev/null +++ b/tests/fixtures/real-prices.json @@ -0,0 +1,242 @@ +{ + "_note": "Recorded during a read-only run against live accounts (2026-10): manualPrices / automaticPrices pages with include=inAppPurchasePricePoint,territory, and one Play oneTimeProduct. Ids, product ids and package rebuilt as placeholders; four territories kept.", + "apple": { + "manual": { + "data": [ + { + "type": "inAppPurchasePrices", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJUVVIiLCJwIjoiMTAwMDEiLCJzZCI6MC4wLCJlZCI6MC4wfQ", + "attributes": { + "startDate": null, + "endDate": null, + "manual": true + }, + "relationships": { + "inAppPurchasePricePoint": { + "data": { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJUVVIiLCJwIjoiMTAwMDEifQ" + } + }, + "territory": { + "data": { + "type": "territories", + "id": "TUR" + } + } + } + }, + { + "type": "inAppPurchasePrices", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJVU0EiLCJwIjoiMTAwMDIiLCJzZCI6MC4wLCJlZCI6MC4wfQ", + "attributes": { + "startDate": null, + "endDate": null, + "manual": true + }, + "relationships": { + "inAppPurchasePricePoint": { + "data": { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJVU0EiLCJwIjoiMTAwMDIifQ" + } + }, + "territory": { + "data": { + "type": "territories", + "id": "USA" + } + } + } + } + ], + "included": [ + { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJUVVIiLCJwIjoiMTAwMDEifQ", + "attributes": { + "customerPrice": "129.99", + "proceeds": "72.04" + } + }, + { + "type": "territories", + "id": "TUR", + "attributes": { + "currency": "TRY" + } + }, + { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJVU0EiLCJwIjoiMTAwMDIifQ", + "attributes": { + "customerPrice": "2.99", + "proceeds": "2.1" + } + }, + { + "type": "territories", + "id": "USA", + "attributes": { + "currency": "USD" + } + } + ] + }, + "auto": { + "data": [ + { + "type": "inAppPurchasePrices", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJBUk0iLCJwIjoiMTAwMDMiLCJzZCI6MC4wLCJlZCI6MC4wfQ", + "attributes": { + "startDate": null, + "endDate": null, + "manual": false + }, + "relationships": { + "inAppPurchasePricePoint": { + "data": { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJBUk0iLCJwIjoiMTAwMDMifQ" + } + }, + "territory": { + "data": { + "type": "territories", + "id": "ARM" + } + } + } + }, + { + "type": "inAppPurchasePrices", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJDT0wiLCJwIjoiMTAwMDQiLCJzZCI6MC4wLCJlZCI6MC4wfQ", + "attributes": { + "startDate": null, + "endDate": null, + "manual": false + }, + "relationships": { + "inAppPurchasePricePoint": { + "data": { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJDT0wiLCJwIjoiMTAwMDQifQ" + } + }, + "territory": { + "data": { + "type": "territories", + "id": "COL" + } + } + } + } + ], + "included": [ + { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJBUk0iLCJwIjoiMTAwMDMifQ", + "attributes": { + "customerPrice": "3.99", + "proceeds": "2.33" + } + }, + { + "type": "territories", + "id": "ARM", + "attributes": { + "currency": "USD" + } + }, + { + "type": "inAppPurchasePricePoints", + "id": "eyJzIjoiMTAwMDAwMDAwMSIsInQiOiJDT0wiLCJwIjoiMTAwMDQifQ", + "attributes": { + "customerPrice": "14900.0", + "proceeds": "8764.71" + } + }, + { + "type": "territories", + "id": "COL", + "attributes": { + "currency": "COP" + } + } + ] + } + }, + "play": { + "packageName": "com.example.game", + "productId": "com.example.game.no_ads", + "listings": [ + { + "languageCode": "en-US", + "title": "No Ads", + "description": "Removes ads." + } + ], + "purchaseOptions": [ + { + "purchaseOptionId": "buy", + "state": "ACTIVE", + "buyOption": { + "legacyCompatible": true + }, + "newRegionsConfig": { + "usdPrice": { + "currencyCode": "USD", + "units": "2", + "nanos": 990000000 + }, + "eurPrice": { + "currencyCode": "EUR", + "units": "2", + "nanos": 670000000 + }, + "availability": "AVAILABLE" + }, + "regionalPricingAndAvailabilityConfigs": [ + { + "regionCode": "AM", + "price": { + "currencyCode": "USD", + "units": "2", + "nanos": 990000000 + }, + "availability": "AVAILABLE" + }, + { + "regionCode": "CO", + "price": { + "currencyCode": "COP", + "units": "9500" + }, + "availability": "AVAILABLE" + }, + { + "regionCode": "TR", + "price": { + "currencyCode": "TRY", + "units": "129", + "nanos": 990000000 + }, + "availability": "AVAILABLE" + }, + { + "regionCode": "US", + "price": { + "currencyCode": "USD", + "units": "2", + "nanos": 990000000 + }, + "availability": "AVAILABLE" + } + ] + } + ], + "regionsVersion": { + "version": "2026/01" + } + } +} \ No newline at end of file