> ## Documentation Index
> Fetch the complete documentation index at: https://docs.waffo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 数据分析

> 收入、支付和客户分析的 GraphQL 查询示例

## 概述

分析查询返回单个商店的预聚合统计。每个分析查询都接受：

* 商店标识 —— `storeId` **或** `storeSlug`（顶层参数，至少提供一个）。
* 必填的 `filter`，类型为 `AnalyticsFilterInput!`。

```graphql theme={"system"}
input AnalyticsFilterInput {
  timeRange: TimeRangeInput!   # { startDate, endDate } ISO 8601 字符串 —— 必填
  currency: String             # 可选，ISO 4217
  status: String               # 可选
}
```

许多嵌套字段有自己的参数，最常见的是 `granularity` 和 `currency`。时间粒度使用 `TimePeriodGranularity` 枚举：`DAY`、`WEEK`、`MONTH`、`QUARTER`、`YEAR`、`ALL_TIME`。

<Note>
  每个分析查询返回的是**结构化对象**，不是标量总数。金额字段以展示字符串返回。按需选择嵌套字段 —— 下方示例展示了可用结构。
</Note>

***

## 订单统计

订单数量、双源收入、买家指标。

```graphql theme={"system"}
query($storeId: String!) {
  orderStatistics(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    totalCount
    countsByStatus { status count }
    countsByPeriod(granularity: MONTH) { period count }
    revenueByCurrency { currency pspTotalAmount snapshotTotalAmount mismatchCount paymentCount }
    revenueByPeriod(granularity: MONTH, currency: "usd") { period currency pspTotalAmount snapshotTotalAmount paymentCount }
    buyerMetrics { totalBuyers newBuyers returningBuyers }
    ordersByCountry { country count }
    revenueByCountry(currency: "usd") { country totalAmount paymentCount }
    b2bVsB2cBreakdown(currency: "usd") { isBusiness label totalAmount orderCount }
  }
}
```

<Note>
  `revenueByCurrency` / `revenueByPeriod` 为**双源**：`pspTotalAmount` 是 PSP 实际金额，`snapshotTotalAmount` 是快照预期金额，`mismatchCount` 统计两者不一致的支付笔数。
</Note>

**变量：**

```json theme={"system"}
{ "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" }
```

***

## 支付统计

成功率、失败原因、退款、支付方式分布、税额汇总。

```graphql theme={"system"}
query($storeId: String!) {
  paymentStatistics(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    successRate { totalAttempts succeeded failed pending successRate }
    failedReasons { reason count percentage }
    refunds {
      totalCount
      succeededCount
      pendingCount
      failedCount
      amountByCurrency { currency totalAmount paymentCount }
      refundRate
    }
    methodDistribution(currency: "usd") { methodType count totalAmount percentage }
    cardBrandDistribution(currency: "usd") { brand count totalAmount percentage }
    successRateByMethod { methodType total succeeded failed successRate }
    taxSummary { currency totalTax totalPreTax totalAmount paymentCount }
  }
}
```

<Note>
  `successRate` 是一个**对象**（`{ totalAttempts, succeeded, failed, pending, successRate }`），不是标量。
</Note>

***

## 产品统计

产品数量、畅销榜、收入贡献。

```graphql theme={"system"}
query($storeId: String!) {
  productStatistics(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    onetimeCountsByStatus { status count }
    subscriptionCountsByStatus { status count }
    onetimeTotalCount
    subscriptionTotalCount
    topByOrderCount(limit: 10) { productId productType productName orderCount totalRevenue currency }
    topByRevenue(limit: 10, currency: "usd") { productId productType productName orderCount totalRevenue currency }
    revenueContribution(currency: "usd") { productId productName revenue contributionPercentage cumulativePercentage }
  }
}
```

***

## 趋势分析

环比增长、累计收入、移动平均。

```graphql theme={"system"}
query($storeId: String!) {
  trendAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    orderGrowth(granularity: MONTH) { period currentValue previousValue growthRate }
    revenueGrowth(granularity: MONTH, currency: "usd") { period currentValue previousValue growthRate }
    cumulativeRevenue(granularity: MONTH, currency: "usd") { period periodValue cumulativeValue }
    orderMovingAverage(windowDays: 7) { date dailyValue movingAverage }
  }
}
```

***

## 分布分析

订单金额分位数、AOV（平均订单价值）趋势、金额分布桶。

```graphql theme={"system"}
query($storeId: String!) {
  distributionAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    orderAmountPercentiles(currency: "usd") { p10 p25 p50 p75 p90 p95 p99 min max avg stddev count }
    aovTrend(granularity: MONTH, currency: "usd") { period averageOrderValue orderCount totalRevenue }
    orderAmountBuckets(currency: "usd", bucketCount: 10) { rangeMin rangeMax count percentage }
  }
}
```

***

## 客户分析

留存、LTV 分布、复购频次、高价值客户。

```graphql theme={"system"}
query($storeId: String!) {
  customerAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    cohortRetention(granularity: MONTH) {
      cohortPeriod
      cohortSize
      retention { periodOffset activeCustomers retentionRate }
    }
    ltvDistribution(currency: "usd") {
      averageLtv
      medianLtv
      percentiles { p50 p90 p99 min max }
      buckets { rangeMin rangeMax count percentage }
    }
    purchaseFrequency { purchaseCount customerCount percentage }
    topCustomers(limit: 10, currency: "usd") { buyerEmail totalSpent orderCount firstPurchaseDate lastPurchaseDate }
  }
}
```

***

## 税务分析

按税种、税率组、国家的税额，以及 B2B/B2C 对比。

```graphql theme={"system"}
query($storeId: String!) {
  taxAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    byCategory(currency: "usd") { taxCategory totalTax totalAmount paymentCount }
    byRateGroup(currency: "usd") { taxRate totalTax totalAmount paymentCount }
    byCountry(currency: "usd") { country totalTax totalAmount paymentCount }
    b2bVsB2c(currency: "usd") { isBusiness label totalTax totalAmount orderCount }
    effectiveTaxRateTrend(granularity: MONTH, currency: "usd") { period avgTaxRate paymentCount }
  }
}
```

***

## 订阅分析

账期分布、取消统计、试用转化、流失率。

```graphql theme={"system"}
query($storeId: String!) {
  subscriptionAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    billingPeriodDistribution(currency: "usd") { billingPeriod count totalAmount percentage }
    activeCount
    cancellationStats { totalSubscriptions canceledCount cancellationRate avgLifetimeDays medianLifetimeDays }
    trialConversion { totalTrials convertedCount activeTrials conversionRate }
    churnRate(granularity: MONTH) { period startActive churned churnRate }
  }
}
```

***

## 退款工单分析

退款原因分布、审核效率、审批率。

```graphql theme={"system"}
query($storeId: String!) {
  refundTicketAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } }
  ) {
    reasonDistribution(currency: "usd") { reason count totalAmount percentage }
    statusDistribution { status count percentage }
    reviewEfficiency { avgHours medianHours p90Hours totalReviewed }
    ticketTrend(granularity: MONTH) { period totalCreated resolvedCount approvedCount rejectedCount }
    approvalRate { approved rejected rate }
  }
}
```

***

## 清分分析

基于结算文件的实际到账金额（已扣手续费、已扣退款）。这是对账的 ground truth，区别于 `paymentStatistics.settlementRevenueByCurrency`（支付时 PSP 的估算换算价）。

```graphql theme={"system"}
query($storeId: String!) {
  settlementAnalysis(
    storeId: $storeId
    filter: { timeRange: { startDate: "2026-04-01T00:00:00Z", endDate: "2026-05-01T00:00:00Z" } }
  ) {
    countsByAccountingStatus { status count }
    netSettlementByCurrency { currency totalAmount paymentCount }
    netSettlementByPeriod(granularity: DAY, currency: "usd") { period currency totalAmount paymentCount }
    refundTotalByCurrency { currency totalAmount paymentCount }
    feeTotalByCurrency { currency totalAmount paymentCount }
  }
}
```

<Note>
  `settlementAnalysis` 的时间范围基于结算日，而非 `created_at`。视角色不同还有其它分析查询可用，包括 `deliveryAnalysis`（Webhook/邮件投递）与 `payoutAnalysis`（出款工单，作用域为商户主体）。可用 schema 自省发现它们的完整字段集。
</Note>

**变量：**

```json theme={"system"}
{ "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" }
```
