{
  "name": "Gumroad sales -> Airtable (ping + nightly backfill, deduped)",
  "nodes": [
    {
      "parameters": { "httpMethod": "POST", "path": "gumroad-sale", "responseMode": "onReceived", "options": {} },
      "name": "Gumroad Ping (each sale)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [0, 0],
      "webhookId": "b1d6a8e2-4c1f-4a77-9d0e-gumroad00001"
    },
    {
      "parameters": { "rule": { "interval": [ { "field": "cronExpression", "expression": "0 3 * * *" } ] } },
      "name": "Nightly backfill 3am",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [0, 300]
    },
    {
      "parameters": {
        "url": "https://api.gumroad.com/v2/sales",
        "sendQuery": true,
        "queryParameters": { "parameters": [
          { "name": "access_token", "value": "={{ $env.GUMROAD_TOKEN }}" },
          { "name": "after", "value": "={{ $now.minus({ days: 3 }).toFormat('yyyy-MM-dd') }}" }
        ] },
        "options": {
          "pagination": { "pagination": {
            "parameters": { "parameters": [ { "name": "page_key", "value": "={{ $response.body.next_page_key }}" } ] },
            "paginationCompleteWhen": "other",
            "completeExpression": "={{ !$response.body.next_page_key }}"
          } }
        }
      },
      "name": "Gumroad Sales API (last 3 days, all pages)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [240, 300]
    },
    {
      "parameters": { "jsCode": "// one item per sale from every API page\nreturn $input.all().flatMap(p => (p.json.sales || []).map(s => ({ json: { ...s, _source: 'api' } })));" },
      "name": "Split sales",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [480, 300]
    },
    {
      "parameters": { "jsCode": "// Ping and API use different field names. Map both to the same Airtable row.\n// Ping: sale_id, sale_timestamp, price (cents), product_id ... API: id, created_at, price (cents), product_id ...\nconst out = [];\nfor (const it of $input.all()) {\n  const s = it.json.body || it.json;\n  const cents = Number(s.price ?? s.price_cents ?? 0);\n  const row = {\n    'Sale ID': String(s.sale_id || s.id || ''),\n    'Email': String(s.email || s.purchase_email || '').trim().toLowerCase(),\n    'Purchased At': new Date(s.sale_timestamp || s.created_at || Date.now()).toISOString(),\n    'Amount': Math.round(cents) / 100,\n    'Currency': String(s.currency || 'usd').toUpperCase(),\n    'Product ID': String(s.product_id || ''),\n    'Product': String(s.product_name || ''),\n    'Quantity': Number(s.quantity || 1),\n    'Refunded': String(s.refunded) === 'true' || s.refunded === true,\n    'Test Purchase': String(s.test) === 'true' || s.test === true,\n    'Source': it.json._source || 'ping',\n  };\n  const problems = [];\n  if (!row['Sale ID']) problems.push('missing sale id');\n  if (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(row['Email'])) problems.push('missing/invalid email');\n  if (!row['Product ID']) problems.push('missing product id');\n  out.push({ json: { ...row, _ok: problems.length === 0, _problems: problems.join(', ') } });\n}\nreturn out;" },
      "name": "Map + validate sale",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [720, 100]
    },
    {
      "parameters": {
        "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict" },
          "conditions": [ { "id": "ok1", "leftValue": "={{ $json._ok }}", "rightValue": true, "operator": { "type": "boolean", "operation": "true", "singleValue": true } } ],
          "combinator": "and" },
        "options": {}
      },
      "name": "Complete?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [960, 100]
    },
    {
      "parameters": {
        "operation": "upsert",
        "base": { "__rl": true, "mode": "id", "value": "appYOURBASE" },
        "table": { "__rl": true, "mode": "id", "value": "tblSales" },
        "columns": { "mappingMode": "autoMapInputData", "value": {}, "matchingColumns": [ "Sale ID" ], "schema": [] },
        "options": {}
      },
      "name": "Airtable: upsert by Sale ID (no duplicates)",
      "type": "n8n-nodes-base.airtable",
      "typeVersion": 2.1,
      "position": [1200, 0],
      "disabled": true
    },
    {
      "parameters": { "assignments": { "assignments": [
        { "id": "r1", "name": "review", "value": "={{ 'Gumroad sale ' + ($json['Sale ID'] || '(no id)') + ' not synced: ' + $json._problems }}", "type": "string" }
      ] }, "options": {} },
      "name": "Flag for review (never silently dropped)",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [1200, 220]
    }
  ],
  "connections": {
    "Gumroad Ping (each sale)": { "main": [ [ { "node": "Map + validate sale", "type": "main", "index": 0 } ] ] },
    "Nightly backfill 3am": { "main": [ [ { "node": "Gumroad Sales API (last 3 days, all pages)", "type": "main", "index": 0 } ] ] },
    "Gumroad Sales API (last 3 days, all pages)": { "main": [ [ { "node": "Split sales", "type": "main", "index": 0 } ] ] },
    "Split sales": { "main": [ [ { "node": "Map + validate sale", "type": "main", "index": 0 } ] ] },
    "Map + validate sale": { "main": [ [ { "node": "Complete?", "type": "main", "index": 0 } ] ] },
    "Complete?": { "main": [ [ { "node": "Airtable: upsert by Sale ID (no duplicates)", "type": "main", "index": 0 } ], [ { "node": "Flag for review (never silently dropped)", "type": "main", "index": 0 } ] ] }
  },
  "settings": { "executionOrder": "v1", "saveDataSuccessExecution": "all", "saveManualExecutions": true }
}
